From aadd2c4dd0f91a2b38cd6ec6cef1f5864d24f443 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:33:56 -0800 Subject: [PATCH 01/88] Cancellation reaches the paying wallet's check, sync and serve Cancelling a contract deploy or call, a paying grant command, dev's deploy or a test run's prep did nothing while the paying wallet was checked, synced or served: the call kept syncing (minutes of Dust on a hosted network) and held the serve's port until the script step. The Payer's methods take the paying call's signal. The funds check passes it to the repository's reads; the serve and the in-process connector pass it to the Dust warm-up, the facade sync and the Dust wait, stop what they started, and fail with CancelledError. Test prep starts no step after a cancel and hands the signal to its waits. --- src/__tests__/contract-deploy.test.ts | 26 ++++++++++++ src/__tests__/facade.test.ts | 42 +++++++++++++++++++ src/__tests__/payer.test.ts | 26 +++++++++++- .../prep-runner-cancellation.test.ts | 24 +++++++++++ src/commands/dev.ts | 2 +- src/commands/grant.ts | 4 +- src/commands/test.ts | 2 +- src/lib/contract/call.ts | 2 +- src/lib/contract/deploy.ts | 2 +- src/lib/contract/served-wallet.ts | 11 +++-- src/lib/dev/deploy.ts | 3 +- src/lib/facade.ts | 27 ++++++++++-- src/lib/grant/fee-wallet.ts | 4 +- src/lib/payer.ts | 11 +++-- src/lib/serve-manager.ts | 19 ++++++++- src/lib/serve-payer.ts | 9 ++-- src/lib/test/prep-runner.ts | 8 +++- src/lib/test/types.ts | 5 ++- src/lib/wallet-can-pay.ts | 8 ++-- 19 files changed, 203 insertions(+), 32 deletions(-) create mode 100644 src/__tests__/prep-runner-cancellation.test.ts diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 5656cb01..0e4105d7 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -13,6 +13,7 @@ import { resolvePayingTarget } from '../lib/payer.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; import { silentSpinner } from '../ui/spinner.ts'; import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; +import { CancelledError } from '../lib/errors.ts'; const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -73,4 +74,29 @@ describe('deployContract', () => { expect(asked).toEqual(['assertCanPay external', 'serve']); expect(fs.existsSync(path.join(home, '.midnight', 'wallets'))).toBe(false); }); + + it('hands the payer the call\'s cancellation, and serves nothing once the call is cancelled during the funds check', async () => { + const controller = new AbortController(); + const asked: string[] = []; + const ownPayer = { + assertCanPay: async (_target: unknown, _wallet: string | undefined, _progress: unknown, signal: AbortSignal | undefined) => { + asked.push(`assertCanPay ${signal === controller.signal ? 'with the call\'s signal' : 'without it'}`); + controller.abort(); // the user cancels while the wallet is checked + return { nightBalance: 1n, dustBalance: 1n }; + }, + serve: async () => { asked.push('serve'); throw new Error('must not be served'); }, + connect: async () => { throw new Error('not used'); }, + }; + const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); + await expect(deployContract({ + request: resolveContractDeployRequest(args), + target: resolvePayingTarget(args, 'contract', 'deploy'), + wallet: 'external', + payer: ownPayer, + progress: () => silentSpinner(), + sdkWarnings: createSdkWarningRouter().openCall().warnings, + signal: controller.signal, + })).rejects.toBeInstanceOf(CancelledError); + expect(asked).toEqual(['assertCanPay with the call\'s signal']); + }); }); diff --git a/src/__tests__/facade.test.ts b/src/__tests__/facade.test.ts index 5d10e873..90f1a2b5 100644 --- a/src/__tests__/facade.test.ts +++ b/src/__tests__/facade.test.ts @@ -256,4 +256,46 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { const url = await indexerWith({ dustLedgerEvents: { id: 0, maxId: 385 } }); await expect(syncWith(url)).resolves.toBeDefined(); }, 10_000); + + it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { + const url = await indexerWith({ zswapLedgerEvents: { id: 0, maxId: 384 }, dustLedgerEvents: { id: 0, maxId: 385 } }); + const rx = await import('rxjs'); + const { startAndSyncFacade } = await import('../lib/facade.ts'); + const { CancelledError } = await import('../lib/errors.ts'); + const bundle: any = { + facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, + seeds: {}, seedStartable: {}, keystore: {}, restoredFromCache: false, indexerWsUrl: url, + }; + const controller = new AbortController(); + const started = Date.now(); + setTimeout(() => controller.abort(), 100); + try { + await expect(startAndSyncFacade(bundle, { timeoutMs: 60_000, signal: controller.signal })).rejects.toBeInstanceOf(CancelledError); + } finally { + bundle.keepAlive?.unsubscribe(); + } + expect(Date.now() - started).toBeLessThan(30_000); + }, 60_000); +}); + +describe('waitForDustAvailable', () => { + it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { + const rx = await import('rxjs'); + const { waitForDustAvailable } = await import('../lib/facade.ts'); + const { CancelledError } = await import('../lib/errors.ts'); + // A wallet with no Dust, and no later state. + const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; + const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; + const controller = new AbortController(); + setTimeout(() => controller.abort(), 100); + await expect(waitForDustAvailable(bundle, 60_000, controller.signal)).rejects.toBeInstanceOf(CancelledError); + }, 60_000); + + it('returns the latest state when its timeout passes without Dust, as before', async () => { + const rx = await import('rxjs'); + const { waitForDustAvailable } = await import('../lib/facade.ts'); + const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; + const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; + await expect(waitForDustAvailable(bundle, 50, new AbortController().signal)).resolves.toBe(noDust); + }); }); diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index 14a9a88c..42ee6119 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -15,6 +15,8 @@ import { servePayerAt } from '../lib/serve-payer.ts'; import { probeServeNetwork } from '../lib/serve-manager.ts'; import { silentSpinner } from '../ui/spinner.ts'; import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; +import { CancelledError } from '../lib/errors.ts'; +import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import contractCommand from '../commands/contract.ts'; import grantCommand from '../commands/grant.ts'; import { cliCall } from './helpers/cli-call.ts'; @@ -98,7 +100,7 @@ describe('the serve payer', () => { const said: string[] = []; try { const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); - const served = await servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings); + const served = await servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings, undefined); expect(served.port).toBe(serve.port); expect(said).toEqual([`Reusing existing mn serve on port ${serve.port}`, `mn serve ready (port ${serve.port})`]); await served.stop(); @@ -107,4 +109,26 @@ describe('the serve payer', () => { await serve.close(); } }); + + it('serves nothing for a call already cancelled, not even probing the running serve', async () => { + const serve = await runningServe(); + const said: string[] = []; + try { + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); + const controller = new AbortController(); + controller.abort(); + await expect(servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings, controller.signal)).rejects.toBeInstanceOf(CancelledError); + expect(said).toEqual([]); + } finally { + await serve.close(); + } + }); + + it('checks no wallet for a call already cancelled', async () => { + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); + const controller = new AbortController(); + controller.abort(); + // Not cancelled, this would fail on the missing wallet file. + await expect(assertWalletCanPay(target, 'nobody', silentSpinner(), controller.signal)).rejects.toBeInstanceOf(CancelledError); + }); }); diff --git a/src/__tests__/prep-runner-cancellation.test.ts b/src/__tests__/prep-runner-cancellation.test.ts new file mode 100644 index 00000000..9396c760 --- /dev/null +++ b/src/__tests__/prep-runner-cancellation.test.ts @@ -0,0 +1,24 @@ +// A cancelled `mn test run` starts no further prep step. The steps here need +// no chain: a cancel stops the run before the step would reach one. + +import { describe, expect, it } from 'vitest'; +import { runPrepSteps } from '../lib/test/prep-runner.ts'; +import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; +import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; +import { CancelledError } from '../lib/errors.ts'; + +const config = { network: 'undeployed', prep: ['dust', 'mn-serve'] } as unknown as DappTestConfig; + +describe('runPrepSteps', () => { + it('starts no step once the run is cancelled', async () => { + const controller = new AbortController(); + controller.abort(); + const started: string[] = []; + await expect(runPrepSteps(config, '/nonexistent', createPrepContext(createSdkWarningRouter().openCall().warnings, controller.signal), { + onStepStart: (step) => started.push(step), + onStepComplete: () => {}, + onMessage: () => {}, + })).rejects.toBeInstanceOf(CancelledError); + expect(started).toEqual([]); + }); +}); diff --git a/src/commands/dev.ts b/src/commands/dev.ts index d0e8e636..90435a2a 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -244,7 +244,7 @@ async function deployContract(project: ProjectInfo, ctx: CallContext): Promise { + return withServedWallet({ target, wallet, payer, progress, sdkWarnings, signal }, { running: `Calling ${circuit}...`, done: `${circuit} called`, failed: 'Call failed' }, async (servePort, spinner) => { const result = await runCall({ dappDir, networkConfig: target.networkConfig, diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index aabe38e9..eb6f8bfa 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -30,7 +30,7 @@ export async function deployContract({ request, target, wallet, payer, progress, const { dappDir, info, constructorArgs, privateStateSecretKey } = request; const { runDeploy } = await import('./runner.ts'); - return withServedWallet({ target, wallet, payer, progress, sdkWarnings }, { running: 'Deploying contract...', done: 'Contract deployed', failed: 'Deploy failed' }, async (servePort, spinner) => { + return withServedWallet({ target, wallet, payer, progress, sdkWarnings, signal }, { running: 'Deploying contract...', done: 'Contract deployed', failed: 'Deploy failed' }, async (servePort, spinner) => { const result = await runDeploy({ dappDir, networkConfig: target.networkConfig, diff --git a/src/lib/contract/served-wallet.ts b/src/lib/contract/served-wallet.ts index 2446ba86..3d692adc 100644 --- a/src/lib/contract/served-wallet.ts +++ b/src/lib/contract/served-wallet.ts @@ -5,6 +5,7 @@ import type { Payer, PayingTarget } from '../payer.ts'; import type { Spinner } from '../../ui/spinner.ts'; import type { CallSdkWarnings } from '../sdk-warnings.ts'; +import { throwIfCancelled } from '../errors.ts'; export interface ServedWalletParams { target: PayingTarget; @@ -15,6 +16,8 @@ export interface ServedWalletParams { progress: (message: string) => Spinner; /** The paying call's SDK warnings, which a wallet served in this process keeps to. */ sdkWarnings: CallSdkWarnings; + /** The paying call's cancellation: checking and serving the wallet stop when it aborts. */ + signal: AbortSignal | undefined; } /** What the progress line says while the script runs, when it succeeds, and when it fails. */ @@ -25,15 +28,17 @@ export interface ServedRunLabels { } export async function withServedWallet( - { target, wallet, payer, progress, sdkWarnings }: ServedWalletParams, + { target, wallet, payer, progress, sdkWarnings, signal }: ServedWalletParams, labels: ServedRunLabels, run: (servePort: number, spinner: Spinner) => Promise, ): Promise { // Before anything is served: the payer's wallet has NIGHT and Dust to pay with. - await payer.assertCanPay(target, wallet, progress('Checking wallet...')); - const serve = await payer.serve(target, wallet, progress('Starting mn serve...'), sdkWarnings); + await payer.assertCanPay(target, wallet, progress('Checking wallet...'), signal); + throwIfCancelled(signal); + const serve = await payer.serve(target, wallet, progress('Starting mn serve...'), sdkWarnings, signal); const spinner = progress(labels.running); try { + throwIfCancelled(signal); const result = await run(serve.port, spinner); spinner.stop(labels.done); return result; diff --git a/src/lib/dev/deploy.ts b/src/lib/dev/deploy.ts index f881f098..98343ca5 100644 --- a/src/lib/dev/deploy.ts +++ b/src/lib/dev/deploy.ts @@ -10,7 +10,7 @@ import { resolvePayingTarget, type Payer } from '../payer.ts'; import type { Spinner } from '../../ui/spinner.ts'; import type { CallSdkWarnings } from '../sdk-warnings.ts'; -export async function deployDevContract(projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings): Promise { +export async function deployDevContract(projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { // The deploy as `mn contract deploy --path --wallet --network ` reads it. const args: ParsedArgs = { command: 'contract', @@ -25,5 +25,6 @@ export async function deployDevContract(projectRoot: string, wallet: string, net payer, progress: () => progress, sdkWarnings, + signal, }); } diff --git a/src/lib/facade.ts b/src/lib/facade.ts index f2b2546e..c2ee7389 100644 --- a/src/lib/facade.ts +++ b/src/lib/facade.ts @@ -33,6 +33,7 @@ import { import type { VerboseLog } from './verbose.ts'; import { assertNetworkAnswers } from './endpoint-check.ts'; import { isStreamEmpty } from './event-tip.ts'; +import { CancelledError, throwIfCancelled } from './errors.ts'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust @@ -392,15 +393,19 @@ export interface SyncOptions { requireStrictSync?: boolean; /** The call's verbose lines. */ log?: VerboseLog; + /** Cancels the wait: the sync fails with CancelledError. The caller stops the facade. */ + signal?: AbortSignal; } export async function startAndSyncFacade( bundle: FacadeBundle, options: SyncOptions = {}, ): Promise { - const { onProgress, onSyncDetail, timeoutMs, syncMode = 'full', requireStrictSync = false, log } = options; + const { onProgress, onSyncDetail, timeoutMs, syncMode = 'full', requireStrictSync = false, log, signal } = options; const { facade } = bundle; + throwIfCancelled(signal); + log?.('sync', 'Starting facade (connecting to node and indexer)...'); const [, emptyStreams] = await Promise.all([startFacade(bundle), readEmptyStreams(bundle.indexerWsUrl, syncMode)]); bundle.emptyStreams = emptyStreams; @@ -408,6 +413,7 @@ export async function startAndSyncFacade( log?.('sync', `The chain has no events in: ${[emptyStreams.zswap && 'zswap', emptyStreams.dust && 'dust'].filter(Boolean).join(', ')}`); } log?.('sync', 'Facade started, subscribing to state...'); + throwIfCancelled(signal); const effectiveTimeout = timeoutMs ?? SYNC_TIMEOUT_MS; log?.('sync', `Sync timeout: ${effectiveTimeout / 1000}s, mode: ${syncMode}`); @@ -422,9 +428,18 @@ export async function startAndSyncFacade( const graceEligible = !requireStrictSync && bundle.restoredFromCache; const startedAt = Date.now(); - return new Promise((resolve, reject) => { + return new Promise((resolveSync, rejectSync) => { let resolved = false; let emissionCount = 0; + const onAbort = (): void => { + if (resolved) return; + resolved = true; + clearTimeout(timeout); + log?.('sync', `Sync cancelled after ${emissionCount} emissions`); + rejectSync(new CancelledError()); + }; + const resolve = (state: FacadeState): void => { signal?.removeEventListener('abort', onAbort); resolveSync(state); }; + const reject = (err: unknown): void => { signal?.removeEventListener('abort', onAbort); rejectSync(err); }; let lastPendingKey = ''; let lastState: FacadeState | null = null; @@ -528,6 +543,7 @@ export async function startAndSyncFacade( } }, }); + if (!resolved) signal?.addEventListener('abort', onAbort, { once: true }); }); } @@ -630,16 +646,19 @@ export function hasDustAvailable(state: FacadeState): boolean { return state.dust.availableCoins.length > 0 || state.dust.balance(new Date()) > 0n; } -export async function waitForDustAvailable(bundle: FacadeBundle, timeoutMs = 60_000): Promise { - +export async function waitForDustAvailable(bundle: FacadeBundle, timeoutMs = 60_000, signal?: AbortSignal): Promise { + throwIfCancelled(signal); + const cancelled = signal === undefined ? rx.NEVER : rx.fromEvent(signal, 'abort'); try { return await rx.firstValueFrom( bundle.facade.state().pipe( rx.filter(hasDustAvailable), rx.timeout(timeoutMs), + rx.takeUntil(cancelled), ) ); } catch { + throwIfCancelled(signal); // Timeout — dust may not be available yet (fresh wallet, slow chain). // Return latest state; caller should handle gracefully. return await rx.firstValueFrom(bundle.facade.state()); diff --git a/src/lib/grant/fee-wallet.ts b/src/lib/grant/fee-wallet.ts index 89519750..ab0a47cd 100644 --- a/src/lib/grant/fee-wallet.ts +++ b/src/lib/grant/fee-wallet.ts @@ -16,9 +16,9 @@ export interface PayingWallet { } /** The payer's wallet for `target`, as the account package's fee wallet, keeping the SDK's warnings to the paying call's `sdkWarnings`. Stopping it stops the wallet. */ -export async function openPayingWallet(payer: Payer, target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings): Promise { +export async function openPayingWallet(payer: Payer, target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { feeWalletOver } = await import('@kuiralabs/midnight-account-chain/connector'); - const connection = await payer.connect(target, wallet, progress, sdkWarnings); + const connection = await payer.connect(target, wallet, progress, sdkWarnings, signal); try { const feeWallet = await feeWalletOver({ getShieldedAddresses: async () => (await connection.call('getShieldedAddresses', {})) as { shieldedCoinPublicKey: string; shieldedEncryptionPublicKey: string }, diff --git a/src/lib/payer.ts b/src/lib/payer.ts index c3907f6c..43e48e6f 100644 --- a/src/lib/payer.ts +++ b/src/lib/payer.ts @@ -64,17 +64,22 @@ export interface PayingFunds { dustBalance: bigint; } +/** + * How a command pays. Each method takes the paying call's cancellation + * signal: once it aborts, the method stops what it started and fails with + * CancelledError. + */ export interface Payer { /** * Refuses, before anything is served, unless the wallet this payer pays from * has NIGHT and Dust to pay with; what it holds otherwise. Each payer checks * its own wallet. */ - assertCanPay: (target: PayingTarget, wallet: string | undefined, progress: Spinner) => Promise; + assertCanPay: (target: PayingTarget, wallet: string | undefined, progress: Spinner, signal: AbortSignal | undefined) => Promise; /** Serves the wallet; one that runs in this process keeps the SDK's warnings to the paying call's `sdkWarnings`. */ - serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings) => Promise; + serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; /** Opens the wallet in this process, keeping the SDK's warnings to the paying call's `sdkWarnings`. */ - connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings) => Promise; + connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; } /** What a command's caller gives it for one call. */ diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 2d0d349c..c36f8921 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -18,6 +18,7 @@ import { DEFAULT_SERVE_PORT } from './constants.ts'; import type { FacadeBundle } from './facade.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; +import { CancelledError, throwIfCancelled } from './errors.ts'; /** A running mn serve, and how to stop it. */ export interface ServeHandle { @@ -36,6 +37,8 @@ export interface ServeManagerOptions { dustWaitMs?: number; /** The SDK warnings of the call that serves, listened to while its wallet runs. */ sdkWarnings: CallSdkWarnings; + /** Cancels the start: what was started is stopped, and the start fails with CancelledError. */ + signal?: AbortSignal; } /** The network and endpoints a serve for these options must use. */ @@ -165,6 +168,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise {}); + throwIfCancelled(options.signal); if (await isPortInUse(port)) { const actualSdkId = await probeServeNetwork(port); @@ -227,7 +231,9 @@ export interface OpenedConnector { */ export async function openConnector(options: ServeManagerOptions): Promise { const onMessage = options.onMessage ?? (() => {}); + const { signal } = options; + throwIfCancelled(signal); // Load wallet const config = await unlockWallet(resolveWalletPath(options.wallet)); const seedBuffer = Buffer.from(config.seed, 'hex'); @@ -255,7 +261,11 @@ export async function openConnector(options: ServeManagerOptions): Promise { if (highest > 0) { const pct = Math.min(Math.round((applied / highest) * 100), 100); @@ -276,7 +287,7 @@ export async function openConnector(options: ServeManagerOptions): Promise {}); const { connector, stop } = await openConnector(options); + if (options.signal?.aborted === true) { + await stop(); + throw new CancelledError(); + } // Start WebSocket server const server = createRpcServer({ diff --git a/src/lib/serve-payer.ts b/src/lib/serve-payer.ts index 0f83fc6c..14823d5c 100644 --- a/src/lib/serve-payer.ts +++ b/src/lib/serve-payer.ts @@ -20,7 +20,7 @@ const OWN_CONNECTION = 'mn-own-command'; * running there is reused (its stop does nothing); one on another network * refuses, saying what to do. */ -async function serveWallet(port: number, { network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings): Promise { +async function serveWallet(port: number, { network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { startServeOrReuse } = await import('./serve-manager.ts'); const handle = await startServeOrReuse({ port, @@ -30,6 +30,7 @@ async function serveWallet(port: number, { network, endpoints }: PayingTarget, w onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, + signal, }); progress.stop('mn serve ready (port ' + handle.port + ')'); return { port: handle.port, stop: () => handle.stop() }; @@ -41,9 +42,9 @@ async function serveWallet(port: number, { network, endpoints }: PayingTarget, w * is running already is reused. Stopping it reverts what it balanced but * never submitted. */ -async function connectWallet({ network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings): Promise { +async function connectWallet({ network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { openConnector } = await import('./serve-manager.ts'); - const opened = await openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings }); + const opened = await openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, signal }); let requestId = 0; const call = (method: PayingMethod, params: Record): Promise => { const handler = opened.connector.handlers[method]; @@ -62,7 +63,7 @@ export function servePayerAt(port: number): Payer { return { // The wallet mn serve pays from is mn's own: its balance is checked as mn keeps it. assertCanPay: assertWalletCanPay, - serve: (target, wallet, progress, sdkWarnings) => serveWallet(port, target, wallet, progress, sdkWarnings), + serve: (target, wallet, progress, sdkWarnings, signal) => serveWallet(port, target, wallet, progress, sdkWarnings, signal), connect: connectWallet, }; } diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index f6eacde0..e8f9d4cd 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -18,6 +18,7 @@ import type { DappTestConfig, PrepStepId, PrepStepResult, PrepContext, PrepCallb import { startServeOrReuse } from '../serve-manager.ts'; import { OWN_COMMAND_DUST_WAIT_MS } from '../dust-wait.ts'; import { startBuild } from './build-manager.ts'; +import { throwIfCancelled } from '../errors.ts'; /** * Run all prep steps defined in the config, in order. @@ -32,6 +33,7 @@ export async function runPrepSteps( const results: PrepStepResult[] = []; for (const step of config.prep) { + throwIfCancelled(ctx.signal); const start = Date.now(); callbacks.onStepStart(step); @@ -128,6 +130,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont try { const state = await startAndSyncFacade(bundle, { syncMode: 'lite', + signal: ctx.signal, onProgress: (applied, highest) => { if (highest > 0) { const pct = Math.min(Math.round((applied / highest) * 100), 100); @@ -199,7 +202,7 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre try { callbacks.onMessage('Syncing wallet...'); - await startAndSyncFacade(bundle, { syncMode: 'lite' }); + await startAndSyncFacade(bundle, { syncMode: 'lite', signal: ctx.signal }); // Register dust (auto-registers UTXOs if needed, no-op if already available) callbacks.onMessage('Ensuring dust...'); @@ -214,7 +217,7 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre // Dust was just registered — wait for coins to actually appear on-chain. // This MUST use the same facade to get real-time state updates. callbacks.onMessage('Dust registered. Waiting for coins to become available...'); - const dustState = await waitForDustAvailable(bundle, DUST_WAIT_TIMEOUT_MS); + const dustState = await waitForDustAvailable(bundle, DUST_WAIT_TIMEOUT_MS, ctx.signal); // Verify dust is actually available — don't trust silent timeouts const dustAvailable = hasDustAvailable(dustState); @@ -252,6 +255,7 @@ async function stepMnServe(config: DappTestConfig, ctx: PrepContext, callbacks: onMessage: (msg) => callbacks.onMessage(`[serve] ${msg}`), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings: ctx.sdkWarnings, + signal: ctx.signal, }); ctx.serveHandle = handle; diff --git a/src/lib/test/types.ts b/src/lib/test/types.ts index de2c8eb3..fb5b8222 100644 --- a/src/lib/test/types.ts +++ b/src/lib/test/types.ts @@ -145,16 +145,19 @@ export interface BuildHandle { export interface PrepContext { /** The SDK warnings of the call that runs the prep: the steps that run the SDK listen to them. */ sdkWarnings: CallSdkWarnings; + /** The run's cancellation: no step starts after it aborts, and the waits inside a step stop. */ + signal: AbortSignal | undefined; serveHandle?: ServeHandle; buildHandle?: BuildHandle; cleanups: (() => Promise)[]; addCleanup(fn: () => Promise): void; } -export function createPrepContext(sdkWarnings: CallSdkWarnings): PrepContext { +export function createPrepContext(sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): PrepContext { const cleanups: (() => Promise)[] = []; return { sdkWarnings, + signal, cleanups, addCleanup(fn: () => Promise) { cleanups.push(fn); diff --git a/src/lib/wallet-can-pay.ts b/src/lib/wallet-can-pay.ts index e34b32ea..9f5baef3 100644 --- a/src/lib/wallet-can-pay.ts +++ b/src/lib/wallet-can-pay.ts @@ -3,6 +3,7 @@ // and no strict sync is needed. import { NATIVE_TOKEN_TYPE } from './constants.ts'; +import { throwIfCancelled } from './errors.ts'; import type { NetworkName } from './network.ts'; import type { PayingTarget } from './payer.ts'; import { resolveWalletPath, unlockWallet } from './wallet-config.ts'; @@ -15,7 +16,8 @@ import type { Spinner } from '../ui/spinner.ts'; * active wallet is checked, the one the command's server will use. Returns * what it found, the Dust in Specks. */ -export async function assertWalletCanPay({ network, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner): Promise<{ nightBalance: bigint; dustBalance: bigint }> { +export async function assertWalletCanPay({ network, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner, signal?: AbortSignal): Promise<{ nightBalance: bigint; dustBalance: bigint }> { + throwIfCancelled(signal); const walletConfig = await unlockWallet(resolveWalletPath(wallet)); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; @@ -26,7 +28,7 @@ export async function assertWalletCanPay({ network, networkConfig }: PayingTarge // Two cheap reads through the repo: no facade, no proof server, no strict // sync. Its tip-aware memo makes the next check in the same MCP session // nearly free. - const balanceView = await repo.unshielded(address, networkConfig); + const balanceView = await repo.unshielded(address, networkConfig, { signal }); const nightBalance = balanceView.balances.get(NATIVE_TOKEN_TYPE) ?? 0n; if (nightBalance === 0n) { @@ -41,7 +43,7 @@ export async function assertWalletCanPay({ network, networkConfig }: PayingTarge ); } - const dustView = await repo.dust(seedBuffer, networkConfig, { onStatus: (s) => progress.update(s) }); + const dustView = await repo.dust(seedBuffer, networkConfig, { signal, onStatus: (s) => progress.update(s) }); if (dustView.balance === 0n && dustView.availableCoins === 0) { progress.fail('No dust available'); throw new Error( From 38fe5da11a6904319c1b22b7c72a22583240cc40 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:36:10 -0800 Subject: [PATCH 02/88] Cancellation fails with the typed CancelledError everywhere Commands and libraries threw a plain Error carrying the cancellation message, which only came out as CANCELLED because the exit-code classifier matched its text. They throw CancelledError now (its code is CANCELLED); grant's own copy of the check is gone. The runner's and the subscription's tests ask for the type, not the text. --- src/__tests__/contract-runner.test.ts | 7 ++++--- src/__tests__/graphql-ws-subscription.test.ts | 5 +++-- src/commands/airdrop.ts | 4 ++-- src/commands/dust.ts | 4 ++-- src/commands/grant.ts | 16 ++++++---------- src/commands/serve.ts | 4 ++-- src/commands/transfer.ts | 4 ++-- src/lib/contract/runner.ts | 6 +++--- src/lib/dust-register.ts | 6 +++--- src/lib/graphql-ws-subscription.ts | 4 ++-- src/lib/transfer.ts | 8 ++++---- src/lib/wallet-data-repository.ts | 12 ++++++------ 12 files changed, 39 insertions(+), 41 deletions(-) diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index 14ba9568..d9e35f20 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -3,6 +3,7 @@ // mn serve RPC (`rpcCall`) is stubbed. import { describe, it, expect, beforeAll, afterEach } from 'vitest'; +import { CancelledError } from '../lib/errors.ts'; import { spawnSync } from 'node:child_process'; import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -259,9 +260,9 @@ describe('a cancelled run', () => { const dappDir = mkdtempSync(join(tmpdir(), 'mn-cancelled-run-')); try { const common = { dappDir, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; - await expect(runDeploy({ ...common, servePort: 9932 })).rejects.toThrow('Operation cancelled'); - await expect(runCall({ ...common, servePort: 9932, contractAddress: 'ab'.repeat(32), circuit: 'increment' })).rejects.toThrow('Operation cancelled'); - await expect(runState({ ...common, contractAddress: 'ab'.repeat(32) })).rejects.toThrow('Operation cancelled'); + await expect(runDeploy({ ...common, servePort: 9932 })).rejects.toBeInstanceOf(CancelledError); + await expect(runCall({ ...common, servePort: 9932, contractAddress: 'ab'.repeat(32), circuit: 'increment' })).rejects.toBeInstanceOf(CancelledError); + await expect(runState({ ...common, contractAddress: 'ab'.repeat(32) })).rejects.toBeInstanceOf(CancelledError); expect(readdirSync(dappDir)).toEqual([]); } finally { rmSync(dappDir, { recursive: true, force: true }); diff --git a/src/__tests__/graphql-ws-subscription.test.ts b/src/__tests__/graphql-ws-subscription.test.ts index 76c576e2..99f0b854 100644 --- a/src/__tests__/graphql-ws-subscription.test.ts +++ b/src/__tests__/graphql-ws-subscription.test.ts @@ -4,6 +4,7 @@ // closed-early / initial-silence / error / abort) is exercised end-to-end. import { describe, it, expect, afterEach } from 'vitest'; +import { CancelledError } from '../lib/errors.ts'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; @@ -118,12 +119,12 @@ describe('subscribeGraphqlWs — settle semantics', () => { await expect(sub(url).run).rejects.toThrow(/GraphQL error: bad/); }); - it('abort rejects with Operation cancelled', async () => { + it('abort rejects with CancelledError', async () => { const url = await startServer((ws) => ws.send(next({ done: false }))); const ac = new AbortController(); const p = sub(url, { idleMs: 60_000, timeoutMs: 60_000, signal: ac.signal }).run; setTimeout(() => ac.abort(), 30); - await expect(p).rejects.toThrow(/Operation cancelled/); + await expect(p).rejects.toBeInstanceOf(CancelledError); }); it('a throw inside onNext rejects with that error', async () => { diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 52bd132e..ba328aeb 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -10,7 +10,7 @@ // A shielded address implies --shielded; the flag is optional there. import * as ledger from '@midnightntwrk/ledger-v9'; -import { CANCELLED_MESSAGE } from '../lib/errors.ts'; +import { throwIfCancelled } from '../lib/errors.ts'; import { MidnightBech32m, ShieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; import { loadWalletConfig, resolveWalletPath, saveShieldedAddress } from '../lib/wallet-config.ts'; @@ -297,7 +297,7 @@ async function shieldedAirdrop( spinner.update('Checking dust...'); await ensureDust(bundle, (status: string) => spinner.update(status)); - if (ctx.signal.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(ctx.signal); spinner.update('Building shielded transaction...'); const recipe = await bundle.facade.transferTransaction( diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 90894ce1..2e0df080 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -4,7 +4,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites } from '../lib/argv.ts'; -import { UsageError, CANCELLED_MESSAGE } from '../lib/errors.ts'; +import { UsageError, throwIfCancelled } from '../lib/errors.ts'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; @@ -182,7 +182,7 @@ async function dustRegistrationPreCheck( } }, ctx.signal); - if (ctx.signal.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(ctx.signal); const { registeredUtxos, unregisteredUtxos } = summary; spinner.stop('Registration checked'); diff --git a/src/commands/grant.ts b/src/commands/grant.ts index a9d7977f..79f74b66 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -23,7 +23,7 @@ import { payerFor } from '../lib/payer.ts'; import { dim } from '../ui/colors.ts'; import { header, keyValue, formatNight } from '../ui/format.ts'; import type { Spinner } from '../ui/spinner.ts'; -import { CANCELLED_MESSAGE } from '../lib/errors.ts'; +import { throwIfCancelled } from '../lib/errors.ts'; const SPINNER_LABEL: Record = { deploy: 'Deploying the account...', @@ -65,15 +65,12 @@ export default async function grantCommand(args: ParsedArgs, ctx: CallContext): ctx.output.stderr('\n'); } - const throwIfCancelled = (): void => { - if (ctx.signal.aborted) throw new Error(CANCELLED_MESSAGE); - }; // Reading the account or a request submits nothing: a wallet with no Dust can still do it, and none is opened. const payer = paysAFee(request) ? payerFor(`grant ${request.subcommand}`, ctx) : undefined; const funds = payer ? await payer.assertCanPay(target, walletFlag, spinnerFor('Checking wallet...'), ctx.signal) : undefined; const paying = payer ? await openPayingWallet(payer, target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal) : undefined; try { - await runOwned(request, { target, walletName, recordsDir, account, jsonMode, paying, funds, spinnerFor, throwIfCancelled }, ctx); + await runOwned(request, { target, walletName, recordsDir, account, jsonMode, paying, funds, spinnerFor }, ctx); } finally { await paying?.stop(); } @@ -88,11 +85,10 @@ interface OwnedRun { paying: PayingWallet | undefined; funds: { dustBalance: bigint } | undefined; spinnerFor: (label: string) => Spinner; - throwIfCancelled: () => void; } /** Runs the command on the account, with the wallet that pays (if it pays) already open. */ -async function runOwned(request: GrantRequest, { target, walletName, recordsDir, account, jsonMode, paying, funds, spinnerFor, throwIfCancelled }: OwnedRun, ctx: CallContext): Promise { +async function runOwned(request: GrantRequest, { target, walletName, recordsDir, account, jsonMode, paying, funds, spinnerFor }: OwnedRun, ctx: CallContext): Promise { const spinner = spinnerFor(SPINNER_LABEL[request.subcommand]); // This machine's device, made where no account is yet: it opens no account first. if (request.subcommand === 'device' && request.action === 'new') { @@ -134,7 +130,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, // interruption, and the next run finishes what this one left. const owned: GrantAccount = await openGrantAccount(target.networkConfig, recordsDir, (line) => { spinner.update(line); - throwIfCancelled(); + throwIfCancelled(ctx.signal); }); // How the account's owner key and records are kept: sealed, or in plain text until `wallet protect`. const common = { subcommand: request.subcommand, network: target.network, wallet: walletName, ownerKey: owned.protection }; @@ -142,7 +138,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, // The wallet that pays, which a paying command opened above. const payingWallet = async (): Promise => { if (paying === undefined) throw new Error(`${request.subcommand} was prepared as a command that pays nothing`); - throwIfCancelled(); + throwIfCancelled(ctx.signal); return paying; }; // The owner's session, paid by the wallet. @@ -164,7 +160,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, }; try { - throwIfCancelled(); + throwIfCancelled(ctx.signal); switch (request.subcommand) { case 'deploy': { const { deployOwnerAccount, freshOwnerDevice } = await import('@kuiralabs/midnight-account-chain/owner'); diff --git a/src/commands/serve.ts b/src/commands/serve.ts index a48d4e1f..943695cc 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -20,7 +20,7 @@ import { describeApprovalPolicy } from '../lib/approval.ts'; import { bold, dim, teal, green, red } from '../ui/colors.ts'; import type { Spinner } from '../ui/spinner.ts'; import type { CallContext } from '../lib/call-context.ts'; -import { UsageError, CANCELLED_MESSAGE } from '../lib/errors.ts'; +import { UsageError, throwIfCancelled } from '../lib/errors.ts'; export default async function serveCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); @@ -115,7 +115,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // Save cache after successful sync (checkpoint before opening RPC). try { await saveWalletCache(address, networkName, bundle.facade); } catch { /* best-effort */ } - if (ctx.signal.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(ctx.signal); let server: RpcServer | undefined; let connector: ReturnType | undefined; diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 92cbcff4..3aef8846 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -2,7 +2,7 @@ // Usage: midnight transfer [--shielded] import * as ledger from '@midnightntwrk/ledger-v9'; -import { CANCELLED_MESSAGE } from '../lib/errors.ts'; +import { throwIfCancelled } from '../lib/errors.ts'; import { MidnightBech32m } from '@midnightntwrk/wallet-sdk/address-format'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; import { saveShieldedAddress, unlockWallet } from '../lib/wallet-config.ts'; @@ -170,7 +170,7 @@ async function shieldedTransfer( spinner.update('Checking dust...'); await ensureDust(bundle, (status: string) => spinner.update(status)); - if (ctx.signal.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(ctx.signal); spinner.update('Building shielded transaction...'); // Right after another payment the wallet's Dust can be short of this diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 71210c63..3128865e 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -13,7 +13,7 @@ import type { NetworkConfig } from '../network.ts'; import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; import { coerceArg } from './arg-coerce.ts'; import { resolvePrivateStateSecretKey } from './private-state-secret.ts'; -import { CANCELLED_MESSAGE } from '../errors.ts'; +import { CancelledError, throwIfCancelled } from '../errors.ts'; // The generated deploy/call script imports SDK packages by bare specifier // (`@midnight-ntwrk/midnight-js-contracts`, `ws`, etc.); without help, Node @@ -737,7 +737,7 @@ export function scriptRuntime( /** Runs a generated script and returns what it wrote to stdout. Throws its marked error when it fails. */ export async function executeScript({ dir: dappDir, script, onMessage, env: extraEnv, cwd, overlaySdk = true, label = 'contract', signal, findRuntime = scriptRuntime }: ScriptRun): Promise { - if (signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(signal); // ESM resolution walks up from the importing file's location to find // node_modules; NODE_PATH does NOT work for ESM. Three different files // need to resolve bare imports during a deploy: @@ -805,7 +805,7 @@ export async function executeScript({ dir: dappDir, script, onMessage, env: extr child.on('close', (code) => { settle(); if (signal?.aborted) { - reject(new Error(CANCELLED_MESSAGE)); + reject(new CancelledError()); return; } if (code !== 0) { diff --git a/src/lib/dust-register.ts b/src/lib/dust-register.ts index 066d5ae7..65e65d72 100644 --- a/src/lib/dust-register.ts +++ b/src/lib/dust-register.ts @@ -2,7 +2,7 @@ // Dust to spend. `mn dust register` and `mn dev` both register through here. import { waitForLiteSyncedState } from './facade.ts'; -import { CANCELLED_MESSAGE } from './errors.ts'; +import { throwIfCancelled } from './errors.ts'; import { ensureDust } from './transfer.ts'; import { defaultRepository } from './wallet-data-repository.ts'; import type { NetworkConfig } from './network.ts'; @@ -41,14 +41,14 @@ export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, o seed, networkConfig, async ({ bundle, state }) => { - if (signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(signal); onStatus?.('Checking dust status...'); // ensureDust handles: early return if dust exists, registration // of unregistered UTXOs, waiting for dust coins. const result = await ensureDust(bundle, (status: string) => onStatus?.(status), state); - if (signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(signal); // Wait for dust data to be fully populated before reading balance. const finalState = await waitForLiteSyncedState(bundle); diff --git a/src/lib/graphql-ws-subscription.ts b/src/lib/graphql-ws-subscription.ts index c06f410c..5e90333d 100644 --- a/src/lib/graphql-ws-subscription.ts +++ b/src/lib/graphql-ws-subscription.ts @@ -18,7 +18,7 @@ // `partial=true` means "state is valid but not caught up — persist and resume". import WebSocket from 'ws'; -import { CANCELLED_MESSAGE } from './errors.ts'; +import { CancelledError } from './errors.ts'; import { assertEndpointUsable, endpointRefusalFromWsError } from './blockfrost.ts'; /** Why the subscription settled. `timeout`/`closed-early` are the partial cases. */ @@ -114,7 +114,7 @@ export function subscribeGraphqlWs( reject(err); }; - const onAbort = () => finishErr(new Error(CANCELLED_MESSAGE)); + const onAbort = () => finishErr(new CancelledError()); signal?.addEventListener('abort', onAbort, { once: true }); const resetIdleTimer = () => { diff --git a/src/lib/transfer.ts b/src/lib/transfer.ts index 4b5f554a..3c67b1e1 100644 --- a/src/lib/transfer.ts +++ b/src/lib/transfer.ts @@ -2,7 +2,7 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { CANCELLED_MESSAGE } from './errors.ts'; +import { throwIfCancelled } from './errors.ts'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; import * as rx from 'rxjs'; @@ -477,7 +477,7 @@ export async function executeTransfer(params: TransferParams): Promise { - if (signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(signal); log?.('transfer', 'Sync complete, checking balance...'); const unshieldedBalance = state.unshielded.balances[ledger.unshieldedToken().raw] ?? 0n; @@ -495,7 +495,7 @@ export async function executeTransfer(params: TransferParams): Promise 0 @@ -509,7 +509,7 @@ export class WalletDataRepository { try { // ── Sync-retry loop (build + start) ──────────────────── for (let attempt = 1; attempt <= SYNC_MAX_ATTEMPTS; attempt++) { - if (opts.signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(opts.signal); const cacheBeforeBuild = opts.forceFresh ? null : await this.walletStateToRestore(seed, network, networkName, opts.log); @@ -525,7 +525,7 @@ export class WalletDataRepository { }); break; } catch (err: any) { - if (opts.signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(opts.signal); if (err instanceof StaleCacheError && attempt < SYNC_MAX_ATTEMPTS && writeMode) { opts.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); @@ -566,7 +566,7 @@ export class WalletDataRepository { let attempt = 0; while (true) { attempt++; - if (opts.signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(opts.signal); try { result = await fn({ bundle, state: syncedState }); break; @@ -579,7 +579,7 @@ export class WalletDataRepository { await stopFacade(bundle).catch(() => {}); bundle = undefined; await new Promise((r) => setTimeout(r, COLD_START_DELAY_MS)); - if (opts.signal?.aborted) throw new Error(CANCELLED_MESSAGE); + throwIfCancelled(opts.signal); const retryCache = loadWalletCache(address, networkName, this.cacheDir); bundle = await buildFacade(seed, network, retryCache, opts.log); syncedState = await startAndSyncFacade(bundle, { From eb6f9c481964476767cff84d9b149d6dd6b53fd8 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:37:39 -0800 Subject: [PATCH 03/88] Layering: rules for the shell and the MCP server, checked by the suite The check reported the shell's and the MCP server's imports but failed on none of them, a deferral that waited for the command registry, and nothing ran the check but a hand. The shell may import every package and the MCP server; the MCP server may import core, the shell's host and runner, and connect's serve payer, and nothing else. No package may import either. The suite now runs the check, with tests of the rules; --all, which only failed the deferred imports too, is gone. --- scripts/check-layering.d.mts | 2 + scripts/check-layering.mjs | 84 +++++++++++++++++----------------- src/__tests__/layering.test.ts | 40 ++++++++++++++++ 3 files changed, 83 insertions(+), 43 deletions(-) create mode 100644 src/__tests__/layering.test.ts diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 2ed43000..68074d49 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -2,3 +2,5 @@ export function sourceFiles(dir?: string): string[]; export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; +export function importRule(fromRel: string, toRel: string): string | undefined; +export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 41546bf2..bc386343 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -8,12 +8,10 @@ // commands: a command is an adapter over library functions, and only the shell // and the MCP server dispatch to one. // -// Usage: node scripts/check-layering.mjs [--all] -// Imported, it exports sourceFiles and homeOf: which package each file of src/ is in, -// and guidanceRule: the rule an import breaks around a package's agent guidance. -// Exits 1 when a file has no package, or an import breaks a rule. The shell and -// the MCP server are reported but do not fail the check until the command -// registry rewires them; --all makes them fail too. +// Usage: node scripts/check-layering.mjs +// Imported, it exports sourceFiles and homeOf: which package each file of src/ is in; +// importRule and guidanceRule: the rule an import breaks; and findLayeringProblems, +// which the suite runs. Exits 1 when a file has no package, or an import breaks a rule. import { readFileSync, readdirSync, statSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; @@ -78,10 +76,17 @@ const MAY_IMPORT = { connect: ['core', 'chain', 'wallet', 'connect'], dev: ['core', 'chain', 'wallet', 'contract', 'connect', 'dev'], grant: ['core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'grant'], + // The shell installs every package's commands and guidance, picks the payer + // and the protectors, and starts the MCP server. + shell: [...PACKAGES, 'mcp', 'shell'], + // The MCP server runs the registry the shell installs, through the shell's + // host and runner, and pays through connect's serve payer. It reaches no + // other package: every tool comes from the registry. + mcp: ['core', 'connect', 'shell', 'mcp'], }; -// Rewired by the command registry, so reported but not failed until then. -const DEFERRED = new Set(['shell', 'mcp']); +// They dispatch to commands and assemble every package's guidance. +const DISPATCHERS = new Set(['shell', 'mcp']); const MIDNIGHT_SDK = /^@midnight(-ntwrk|ntwrk)\//; const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; @@ -121,7 +126,24 @@ export function guidanceRule(fromRel, toRel) { const targetHome = homeOf(join(SRC, toRel)); if (home === undefined || targetHome === undefined || targetHome === home) return undefined; if (isGuidance(fromRel) && targetHome !== 'core') return `${home} guidance → ${targetHome}`; - if (isGuidance(toRel) && !DEFERRED.has(home)) return `${home} → ${targetHome} guidance`; + if (isGuidance(toRel) && !DISPATCHERS.has(home)) return `${home} → ${targetHome} guidance`; + return undefined; +} + +/** + * The rule an import from one file of src/ to another breaks, or undefined. + * Paths are relative to src/; a target with no package is not judged here. + */ +export function importRule(fromRel, toRel) { + const home = homeOf(join(SRC, fromRel)); + const targetHome = homeOf(join(SRC, toRel)); + if (home === undefined || targetHome === undefined) return undefined; + const guidance = guidanceRule(fromRel, toRel); + if (guidance !== undefined) return guidance; + const isCommand = (path) => path.startsWith('commands/'); + const callsCommand = isCommand(toRel) && (!isCommand(fromRel) || targetHome !== home); + if (callsCommand && !DISPATCHERS.has(home)) return `${isCommand(fromRel) ? 'command' : 'library'} → ${targetHome} command`; + if (!MAY_IMPORT[home].includes(targetHome)) return `${home} → ${targetHome}`; return undefined; } @@ -135,7 +157,8 @@ function importsOf(file) { return found; } -function check() { +/** Files with no package, and imports that break a rule. */ +export function findLayeringProblems() { const unhomed = []; const violations = []; for (const file of sourceFiles(SRC)) { @@ -148,26 +171,8 @@ function check() { for (const { specifier, line } of importsOf(file)) { const where = `src/${rel}:${line}`; if (specifier.startsWith('.')) { - const target = resolve(dirname(file), specifier); - const targetHome = homeOf(target); - if (targetHome === undefined) continue; - const guidance = guidanceRule(rel, relative(SRC, target)); - if (guidance !== undefined) { - violations.push({ home, rule: guidance, where, specifier }); - continue; - } - const isCommand = (path) => path.startsWith('commands/'); - const callsCommand = isCommand(relative(SRC, target)) && (!isCommand(rel) || targetHome !== home); - if (callsCommand && !DEFERRED.has(home)) { - violations.push({ home, rule: `${isCommand(rel) ? 'command' : 'library'} → ${targetHome} command`, where, specifier }); - continue; - } - if (targetHome === home) continue; - if (DEFERRED.has(home)) { - violations.push({ home, rule: `${home} → ${targetHome}`, where, specifier }); - } else if (!MAY_IMPORT[home].includes(targetHome)) { - violations.push({ home, rule: `${home} → ${targetHome}`, where, specifier }); - } + const rule = importRule(rel, relative(SRC, resolve(dirname(file), specifier))); + if (rule !== undefined) violations.push({ home, rule, where, specifier }); } else if (SDK_FREE.has(home) && MIDNIGHT_SDK.test(specifier)) { violations.push({ home, rule: `${home} → Midnight SDK`, where, specifier }); } else if (home !== 'grant' && ACCOUNT_CHAIN.test(specifier)) { @@ -178,10 +183,7 @@ function check() { return { unhomed, violations }; } -function report({ unhomed, violations }, failDeferred) { - const failing = violations.filter((v) => failDeferred || !DEFERRED.has(v.home)); - const deferred = violations.filter((v) => !failDeferred && DEFERRED.has(v.home)); - +function report({ unhomed, violations }) { for (const rel of unhomed) process.stdout.write(`no package: src/${rel}\n`); const byRule = (list) => { @@ -189,22 +191,18 @@ function report({ unhomed, violations }, failDeferred) { for (const v of list) groups.set(v.rule, [...(groups.get(v.rule) ?? []), v]); return [...groups].sort(([a], [b]) => a.localeCompare(b)); }; - for (const [rule, list] of byRule(failing)) { + for (const [rule, list] of byRule(violations)) { process.stdout.write(`\n${rule} (${list.length})\n`); for (const v of list) process.stdout.write(` ${v.where} ${v.specifier}\n`); } - if (deferred.length > 0) { - process.stdout.write(`\nDeferred to the command registry, not failing: ${deferred.length} imports from the shell and the MCP server\n`); - for (const [rule, list] of byRule(deferred)) process.stdout.write(` ${rule}: ${list.length}\n`); - } - const problems = unhomed.length + failing.length; - process.stdout.write(`\n${problems === 0 ? 'Layering holds.' : `${failing.length} import(s) break the layering; ${unhomed.length} file(s) have no package.`}\n`); + const problems = unhomed.length + violations.length; + process.stdout.write(`\n${problems === 0 ? 'Layering holds.' : `${violations.length} import(s) break the layering; ${unhomed.length} file(s) have no package.`}\n`); return problems === 0; } -// Run as a script; imported (by the SDK-free base test), it only lends its package table. +// Run as a script; imported, it lends its package table and its rules. if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { - const ok = report(check(), process.argv.includes('--all')); + const ok = report(findLayeringProblems()); process.exit(ok ? 0 : 1); } diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts new file mode 100644 index 00000000..6dffaa4b --- /dev/null +++ b/src/__tests__/layering.test.ts @@ -0,0 +1,40 @@ +// The package layering, checked on every run of the suite: every file of src/ +// has a package, and no import crosses the layering the planned split needs. + +import { describe, expect, it } from 'vitest'; +import { findLayeringProblems, importRule } from '../../scripts/check-layering.mjs'; + +describe('the layering', () => { + it('holds across src/', () => { + const { unhomed, violations } = findLayeringProblems(); + expect(unhomed).toEqual([]); + expect(violations.map((v) => `${v.rule}: ${v.where} ${v.specifier}`)).toEqual([]); + }); + + it('lets the shell install every package and start the MCP server', () => { + expect(importRule('lib/installed-commands.ts', 'commands/grant.definition.ts')).toBeUndefined(); + expect(importRule('lib/installed-commands.ts', 'commands/wallet.guidance.ts')).toBeUndefined(); + expect(importRule('wallet.ts', 'lib/grant/account-protector.ts')).toBeUndefined(); + expect(importRule('wallet.ts', 'mcp-server.ts')).toBeUndefined(); + }); + + it('keeps the MCP server to core, the shell and the serve payer', () => { + expect(importRule('mcp-server.ts', 'lib/run-command.ts')).toBeUndefined(); + expect(importRule('mcp-server.ts', 'lib/serve-payer.ts')).toBeUndefined(); + expect(importRule('lib/mcp/registry-tools.ts', 'lib/command-definition.ts')).toBeUndefined(); + expect(importRule('mcp-server.ts', 'lib/facade.ts')).toBe('mcp → wallet'); + expect(importRule('lib/mcp/skills.ts', 'lib/contract/runner.ts')).toBe('mcp → contract'); + expect(importRule('mcp-server.ts', 'lib/grant/prepare.ts')).toBe('mcp → grant'); + }); + + it('keeps every package off the shell and the MCP server', () => { + expect(importRule('lib/facade.ts', 'lib/run-command.ts')).toBe('wallet → shell'); + expect(importRule('lib/argv.ts', 'lib/mcp/known-params.ts')).toBe('core → mcp'); + expect(importRule('commands/grant.ts', 'mcp-server.ts')).toBe('grant → mcp'); + }); + + it('lets no library or other package call a command', () => { + expect(importRule('lib/dev/deploy.ts', 'commands/contract.ts')).toBe('library → contract command'); + expect(importRule('commands/dev.ts', 'commands/contract.ts')).toBe('command → contract command'); + }); +}); From a211c60d81ec45759056585de0fa29c582a65c4c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:40:53 -0800 Subject: [PATCH 04/88] Help's order from the definitions; config keys and global flags checked The shell kept help's order as a list of every command's name, a second list of commands next to the registry. Each definition now holds its place, as its intro line and its tools already do, and the registry refuses two commands in one place; a plugin's command takes its own. Help, the manual and the snapshot are unchanged. The manual's config keys and help --json's global flags stay prose, now with tests that fail when config accepts a key the manual doesn't describe, or the shell a global flag help doesn't list. --- src/__tests__/agent-guidance.test.ts | 34 +++++++++++----------- src/__tests__/command-registry.test.ts | 3 +- src/__tests__/manual-command.test.ts | 21 +++++++++++++ src/__tests__/mcp-registry-tools.test.ts | 1 + src/commands/address.definition.ts | 1 + src/commands/airdrop.definition.ts | 1 + src/commands/balance.definition.ts | 1 + src/commands/cache.definition.ts | 1 + src/commands/config.definition.ts | 1 + src/commands/contract.definition.ts | 1 + src/commands/dev.definition.ts | 1 + src/commands/dust.definition.ts | 1 + src/commands/generate.definition.ts | 1 + src/commands/genesis-address.definition.ts | 1 + src/commands/grant.definition.ts | 1 + src/commands/help.definition.ts | 1 + src/commands/info.definition.ts | 1 + src/commands/inspect-cost.definition.ts | 1 + src/commands/localnet.definition.ts | 1 + src/commands/manual.definition.ts | 1 + src/commands/serve.definition.ts | 1 + src/commands/status.definition.ts | 1 + src/commands/test.definition.ts | 1 + src/commands/transfer.definition.ts | 1 + src/commands/wallet.definition.ts | 1 + src/lib/command-definition.ts | 17 ++++------- src/lib/installed-commands.ts | 8 +---- 27 files changed, 69 insertions(+), 36 deletions(-) diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index 09214a30..c088db46 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -32,9 +32,7 @@ const SECTIONS: Record = { /** The installed packages but one, as the shell would install them without it. */ function withoutPackage(name: string): CommandRegistry { const packages = installedCommands.packages.filter((pkg) => pkg.name !== name); - const gone = new Set(installedCommands.packages.find((pkg) => pkg.name === name)!.commands.map((c) => c.name)); - const order = installedCommands.commands.map((c) => c.name).filter((n) => !gone.has(n)); - return createPackageRegistry(packages, order, installedCommands.globalFlags, installedCommands.globalFlagsHelp); + return createPackageRegistry(packages, installedCommands.globalFlags, installedCommands.globalFlagsHelp); } /** The manual's AVAILABLE MCP TOOLS section, up to the next one. */ @@ -63,8 +61,10 @@ describe('assembleGuidance', () => { }); describe('createPackageRegistry', () => { - const command = (name: string, tools: string[] = []): CommandDefinition => ({ + let nextPlace = 0; + const command = (name: string, tools: string[] = [], order = ++nextPlace): CommandDefinition => ({ name, + order, flags: [], needsWalletSdk: false, shell: {}, @@ -73,32 +73,32 @@ describe('createPackageRegistry', () => { }); const pkg = (name: string, commands: CommandDefinition[], guidance: CommandPackage['guidance'] = { pieces: [] }): CommandPackage => ({ name, commands, guidance }); - it('lists commands in help\'s order, then the ones it doesn\'t name in their package\'s order, and keeps the packages', () => { - const packages = [pkg('p', [command('a'), command('b')]), pkg('plugin', [command('zz'), command('yy')])]; - const registry = createPackageRegistry(packages, ['b', 'a'], []); - expect(registry.commands.map((c) => c.name)).toStrictEqual(['b', 'a', 'zz', 'yy']); + it('lists commands in their definitions\' order, a plugin\'s among them, and keeps the packages', () => { + const packages = [pkg('p', [command('a', [], 20), command('b', [], 10)]), pkg('plugin', [command('zz', [], 40), command('yy', [], 15)])]; + const registry = createPackageRegistry(packages, []); + expect(registry.commands.map((c) => c.name)).toStrictEqual(['b', 'yy', 'a', 'zz']); expect(registry.packages).toBe(packages); }); - it('refuses a command in two packages, a package twice, and a help order naming a command no package installs', () => { - expect(() => createPackageRegistry([pkg('p', [command('a')]), pkg('q', [command('a')])], [], [])).toThrow(/command "a"/); - expect(() => createPackageRegistry([pkg('p', [command('a')]), pkg('p', [command('b')])], [], [])).toThrow(/package "p"/); - expect(() => createPackageRegistry([pkg('p', [command('a')])], ['a', 'gone'], [])).toThrow(/"gone"/); + it('refuses a command in two packages, a package twice, and two commands in one place', () => { + expect(() => createPackageRegistry([pkg('p', [command('a')]), pkg('q', [command('a')])], [])).toThrow(/command "a"/); + expect(() => createPackageRegistry([pkg('p', [command('a')]), pkg('p', [command('b')])], [])).toThrow(/package "p"/); + expect(() => createPackageRegistry([pkg('p', [command('a', [], 5)]), pkg('plugin', [command('b', [], 5)])], [])).toThrow(/command place "5"/); }); it('refuses two packages\' pieces in one place', () => { const p = pkg('p', [command('a')], { pieces: [piece('s', 10, 'x')] }); const q = pkg('q', [command('b')], { pieces: [piece('s', 10, 'y')] }); - expect(() => createPackageRegistry([p, q], [], [])).toThrow(CommandDefinitionError); + expect(() => createPackageRegistry([p, q], [])).toThrow(CommandDefinitionError); }); it('refuses a tools table row for another package\'s tool, a tool given two rows, and two rows in one place', () => { const row = (tool: string, order = 1) => ({ tool, group: 'g', order, description: ['d'] }); const tooled = command('a', ['t_a']); - expect(() => createPackageRegistry([pkg('p', [tooled]), pkg('q', [command('bb')], { pieces: [], toolsTable: [row('t_a')] })], [], [])) + expect(() => createPackageRegistry([pkg('p', [tooled]), pkg('q', [command('bb')], { pieces: [], toolsTable: [row('t_a')] })], [])) .toThrow(/q: its tools table has a row for t_a/); - expect(() => createPackageRegistry([pkg('p', [tooled], { pieces: [], toolsTable: [row('t_a', 1), row('t_a', 2)] })], [], [])).toThrow(/t_a/); - expect(() => createPackageRegistry([pkg('p', [command('a', ['t_a', 't_b'])], { pieces: [], toolsTable: [row('t_a'), row('t_b')] })], [], [])) + expect(() => createPackageRegistry([pkg('p', [tooled], { pieces: [], toolsTable: [row('t_a', 1), row('t_a', 2)] })], [])).toThrow(/t_a/); + expect(() => createPackageRegistry([pkg('p', [command('a', ['t_a', 't_b'])], { pieces: [], toolsTable: [row('t_a'), row('t_b')] })], [])) .toThrow(/tools table place/); }); }); @@ -155,7 +155,7 @@ describe('the texts, assembled from the installed packages', () => { it('shows a tool no package gives a row for under Other, with its own description, so the count stays right', () => { const packages = installedCommands.packages.map((pkg) => (pkg.name === 'grant' ? { ...pkg, guidance: { pieces: pkg.guidance.pieces } } : pkg)); - const registry = createPackageRegistry(packages, installedCommands.commands.map((c) => c.name), installedCommands.globalFlags, installedCommands.globalFlagsHelp); + const registry = createPackageRegistry(packages, installedCommands.globalFlags, installedCommands.globalFlagsHelp); const section = toolsSection(agentManual(registry)); expect(section).not.toContain('Grants (experimental)'); expect(section).toContain(' Other\n midnight_grant_status The wallet\'s account: address, owner key, what it holds, number of grants (see skill).'); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 579dfb2b..5cdb68f2 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -73,7 +73,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry since 2C) const payer = { name: 'test payer' } as unknown as Payer; const protector = { name: 'test protector' } as unknown as WalletProtector; const testCommand = (name: string, shell: CommandDefinition['shell'], outcome?: CommandOutcome): CommandDefinition => ({ - name, flags: [], needsWalletSdk: false, shell, + name, order: 1, flags: [], needsWalletSdk: false, shell, load: async () => { loaded.push(name); return { @@ -376,6 +376,7 @@ describe('the MCP tools, generated from the registry', () => { describe('createCommandRegistry', () => { const base: CommandDefinition = { name: 'x', + order: 1, flags: [{ name: 'a', takesValue: false, help: ['--a A'] }], help: { description: 'X', usage: 'midnight x', flags: ['note', { flag: 'a' }] }, needsWalletSdk: false, diff --git a/src/__tests__/manual-command.test.ts b/src/__tests__/manual-command.test.ts index 010758ce..9839184e 100644 --- a/src/__tests__/manual-command.test.ts +++ b/src/__tests__/manual-command.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect } from 'vitest'; import { buildManual } from '../commands/manual.ts'; +import { getConfigValue } from '../lib/cli-config.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; function stripAnsi(s: string): string { return s.replace(/\x1b\[[0-9;]*m/g, ''); @@ -74,4 +76,23 @@ describe('mn manual', () => { const m = stripAnsi(buildManual()); expect(m.split('\n').length).toBeGreaterThanOrEqual(200); }); + + it('describes every key `config` accepts', () => { + // The keys config accepts, as its refusal of an unknown key lists them. + let refusal = ''; + try { getConfigValue('no-such-key'); } catch (err) { refusal = (err as Error).message; } + const keys = refusal.split('Valid keys: ')[1]!.split(', '); + expect(keys.length).toBeGreaterThan(0); + const section = stripAnsi(buildManual()).split('Config keys')[1]!.split('Compatibility alias')[0]!; + for (const key of keys) expect(section, key).toMatch(new RegExp(`^ {4}${key}\\b`, 'm')); + }); +}); + +describe('help --json global flags', () => { + it('describes every flag the shell accepts on every command', () => { + const described = installedCommands.globalFlagsHelp.map((flag) => flag.name).join(' '); + for (const flag of installedCommands.globalFlags) { + expect(described, flag.name).toContain(flag.name.length === 1 ? `-${flag.name}` : `--${flag.name}`); + } + }); }); diff --git a/src/__tests__/mcp-registry-tools.test.ts b/src/__tests__/mcp-registry-tools.test.ts index 37a1cab8..39299236 100644 --- a/src/__tests__/mcp-registry-tools.test.ts +++ b/src/__tests__/mcp-registry-tools.test.ts @@ -11,6 +11,7 @@ import { MINIMAL_FLAG, type ParsedArgs } from '../lib/argv.ts'; const received: ParsedArgs[] = []; const command = (tools: ToolDefinition[]): CommandDefinition => ({ name: 'thing', + order: 1, subcommands: ['make', 'show'], flags: [{ name: 'size', takesValue: true, agent: { type: 'string', description: 'How big' } }, { name: 'go', takesValue: false, subcommands: ['make'], agent: { notForAgents: 'a person\'s' } }], needsWalletSdk: false, diff --git a/src/commands/address.definition.ts b/src/commands/address.definition.ts index b74daf55..b55d5811 100644 --- a/src/commands/address.definition.ts +++ b/src/commands/address.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition export const addressDefinition: CommandDefinition = { name: 'address', + order: 50, flags: [ { name: 'index', diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index 33a80ceb..62343b0e 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/c export const airdropDefinition: CommandDefinition = { name: 'airdrop', + order: 80, flags: [ { name: 'network', diff --git a/src/commands/balance.definition.ts b/src/commands/balance.definition.ts index 2804bc12..6f5a7263 100644 --- a/src/commands/balance.definition.ts +++ b/src/commands/balance.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/c export const balanceDefinition: CommandDefinition = { name: 'balance', + order: 40, flags: [ { name: 'force-shielded', diff --git a/src/commands/cache.definition.ts b/src/commands/cache.definition.ts index 96276fe5..51f6434d 100644 --- a/src/commands/cache.definition.ts +++ b/src/commands/cache.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition export const cacheDefinition: CommandDefinition = { name: 'cache', + order: 120, subcommands: ['clear'], flags: [ { diff --git a/src/commands/config.definition.ts b/src/commands/config.definition.ts index f9de7660..58abf1b0 100644 --- a/src/commands/config.definition.ts +++ b/src/commands/config.definition.ts @@ -5,6 +5,7 @@ import { INDEXER_GRAPHQL_WS_PATH } from '../lib/constants.ts'; export const configDefinition: CommandDefinition = { name: 'config', + order: 110, subcommands: ['get', 'set', 'unset'], flags: [ { diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index badb3bac..08da4f66 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -13,6 +13,7 @@ async function checkSendingWallet(params: Readonly>): Pr export const contractDefinition: CommandDefinition = { name: 'contract', + order: 160, subcommands: ['inspect', 'deploy', 'call', 'state'], flags: [ { diff --git a/src/commands/dev.definition.ts b/src/commands/dev.definition.ts index 5a555ac7..ac01e0ae 100644 --- a/src/commands/dev.definition.ts +++ b/src/commands/dev.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const devDefinition: CommandDefinition = { name: 'dev', + order: 150, flags: [], help: { description: 'Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy)', diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index 2b6fd43f..441e205f 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/c export const dustDefinition: CommandDefinition = { name: 'dust', + order: 100, subcommands: ['register', 'status', 'export'], flags: [ { name: 'network', takesValue: true, agent: { ...NETWORK_PARAM, description: 'Network (default: the selected one)' } }, diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index 3322f486..5389f0e0 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const generateDefinition: CommandDefinition = { name: 'generate', + order: 20, flags: [ { name: 'force', diff --git a/src/commands/genesis-address.definition.ts b/src/commands/genesis-address.definition.ts index 6e119c5e..ecf7fc49 100644 --- a/src/commands/genesis-address.definition.ts +++ b/src/commands/genesis-address.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition export const genesisAddressDefinition: CommandDefinition = { name: 'genesis-address', + order: 60, flags: [ { name: 'network', diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index 51e3c822..572922fd 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -13,6 +13,7 @@ async function checkGrant(params: Readonly>, call: ToolC export const grantDefinition: CommandDefinition = { name: 'grant', + order: 170, subcommands: [ 'deploy', 'deposit', diff --git a/src/commands/help.definition.ts b/src/commands/help.definition.ts index 83dc649c..7c94669d 100644 --- a/src/commands/help.definition.ts +++ b/src/commands/help.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const helpDefinition: CommandDefinition = { name: 'help', + order: 200, flags: [ { name: 'agent', takesValue: false }, { name: 'intro', takesValue: false }, diff --git a/src/commands/info.definition.ts b/src/commands/info.definition.ts index e58d24cf..29f77172 100644 --- a/src/commands/info.definition.ts +++ b/src/commands/info.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition export const infoDefinition: CommandDefinition = { name: 'info', + order: 30, flags: [ { name: 'network', diff --git a/src/commands/inspect-cost.definition.ts b/src/commands/inspect-cost.definition.ts index cf5944f8..9013c41e 100644 --- a/src/commands/inspect-cost.definition.ts +++ b/src/commands/inspect-cost.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const inspectCostDefinition: CommandDefinition = { name: 'inspect-cost', + order: 70, flags: [ { name: 'network', diff --git a/src/commands/localnet.definition.ts b/src/commands/localnet.definition.ts index 7d4a1b95..ac85ed14 100644 --- a/src/commands/localnet.definition.ts +++ b/src/commands/localnet.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const localnetDefinition: CommandDefinition = { name: 'localnet', + order: 180, subcommands: ['up', 'stop', 'down', 'status', 'logs', 'clean'], flags: [ { diff --git a/src/commands/manual.definition.ts b/src/commands/manual.definition.ts index 96ee4d48..7c832b2c 100644 --- a/src/commands/manual.definition.ts +++ b/src/commands/manual.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const manualDefinition: CommandDefinition = { name: 'manual', + order: 210, flags: [ { name: 'no-pager', diff --git a/src/commands/serve.definition.ts b/src/commands/serve.definition.ts index aafcd685..6680c91e 100644 --- a/src/commands/serve.definition.ts +++ b/src/commands/serve.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const serveDefinition: CommandDefinition = { name: 'serve', + order: 130, flags: [ { name: 'approve-all', diff --git a/src/commands/status.definition.ts b/src/commands/status.definition.ts index 8efad595..39e57459 100644 --- a/src/commands/status.definition.ts +++ b/src/commands/status.definition.ts @@ -4,6 +4,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; export const statusDefinition: CommandDefinition = { name: 'status', + order: 190, // Y29: the shell dispatches status only to refuse it, help and the intro // don't list it, and the MCP server can load it with no tool to call it. // Recorded as each list has it, fixed in 2C–2G. diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index 9464bd2d..5ca51ae2 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition export const testDefinition: CommandDefinition = { name: 'test', + order: 140, subcommands: ['create', 'run', 'list', 'results'], flags: [ { diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 60ef5ff0..837f623a 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTar export const transferDefinition: CommandDefinition = { name: 'transfer', + order: 90, flags: [ { name: 'force-shielded', diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 0061ba2c..000849ac 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -4,6 +4,7 @@ import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition export const walletDefinition: CommandDefinition = { name: 'wallet', + order: 10, subcommands: ['generate', 'list', 'use', 'info', 'remove', 'seed', 'protect'], flags: [ { diff --git a/src/lib/command-definition.ts b/src/lib/command-definition.ts index 52f33512..a2ebdbdc 100644 --- a/src/lib/command-definition.ts +++ b/src/lib/command-definition.ts @@ -183,6 +183,8 @@ export interface ToolDefinition { export interface CommandDefinition { readonly name: string; + /** Its place among the installed commands, which help lists in this order; a plugin takes one no other command has. */ + readonly order: number; readonly subcommands?: readonly string[]; readonly flags: readonly FlagDefinition[]; /** Absent: help does not list the command. */ @@ -448,26 +450,19 @@ function checkGuidance(packages: readonly CommandPackage[]): void { } /** - * Collects packages into a registry. `helpOrder` names commands in the order - * help lists them; a command it doesn't name follows in its package's order - * (a plugin's, D5). Every command is in one package. + * Collects packages into a registry, its commands in their definitions' + * order. Every command is in one package. */ export function createPackageRegistry( packages: readonly CommandPackage[], - helpOrder: readonly string[], globalFlags: readonly FlagDefinition[], globalFlagsHelp: readonly GlobalFlagHelp[] = [], ): CommandRegistry { assertUnique(packages.map((pkg) => pkg.name), 'package'); const all = packages.flatMap((pkg) => pkg.commands); assertUnique(all.map((command) => command.name), 'command'); - assertUnique(helpOrder, 'help place for'); - const ordered = helpOrder.map((name) => { - const command = all.find((c) => c.name === name); - if (command === undefined) throw new CommandDefinitionError(`help's order names "${name}", which no package installs`); - return command; - }); - const commands = [...ordered, ...all.filter((command) => !helpOrder.includes(command.name))]; + assertUnique(all.map((command) => String(command.order)), 'command place'); + const commands = [...all].sort((a, b) => a.order - b.order); checkGuidance(packages); return { ...createCommandRegistry(commands, globalFlags, globalFlagsHelp), packages }; } diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 060b8026..a38fc5a6 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -59,12 +59,6 @@ const GLOBAL_FLAGS_HELP: readonly GlobalFlagHelp[] = [ { name: '--help, -h', description: 'Show help' }, ]; -/** Every command, by name, in help's order (status, which help doesn't list, where its old help entry sat). */ -const HELP_ORDER = [ - 'wallet', 'generate', 'info', 'balance', 'address', 'genesis-address', 'inspect-cost', 'airdrop', 'transfer', 'dust', - 'config', 'cache', 'serve', 'test', 'dev', 'contract', 'grant', 'localnet', 'status', 'help', 'manual', -]; - /** Every package, in the layering's order; the shell's own commands last, its guidance being the skeletons. */ export const installedCommands = createPackageRegistry([ { name: 'core', commands: [configDefinition], guidance: coreGuidance }, @@ -79,4 +73,4 @@ export const installedCommands = createPackageRegistry([ { name: 'dev', commands: [testDefinition, devDefinition, localnetDefinition], guidance: devGuidance }, { name: 'grant', commands: [grantDefinition], guidance: grantGuidance }, { name: 'shell', commands: [helpDefinition, manualDefinition], guidance: { pieces: [] } }, -], HELP_ORDER, GLOBAL_FLAGS, GLOBAL_FLAGS_HELP); +], GLOBAL_FLAGS, GLOBAL_FLAGS_HELP); From d3ac5682f344c4cc0d9f6870626eece2cb523bc9 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:42:55 -0800 Subject: [PATCH 05/88] MCP runner: a command's non-zero exit code is a failure captureCommand ignored the outcome a handler returns, so a command that fails by returning an exit code instead of throwing (a test run whose tests failed, a status that finds a network down) would reach an agent as a success. It throws CommandFailedError now, with the code and the result the command wrote. No tool runs such a command today. --- src/__tests__/run-command.test.ts | 16 ++++++++++++++-- src/lib/errors.ts | 18 ++++++++++++++++++ src/lib/run-command.ts | 7 +++++-- 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index 8f418436..bbd1e63d 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { captureCommand } from '../lib/run-command.ts'; -import { SecondResultError } from '../lib/call-context.ts'; -import { CancelledError } from '../lib/errors.ts'; +import { SecondResultError, type CommandHandler } from '../lib/call-context.ts'; +import { CancelledError, CommandFailedError } from '../lib/errors.ts'; import { classifyError } from '../lib/exit-codes.ts'; import type { Spinner } from '../ui/spinner.ts'; import { parseArgs, type ParsedArgs } from '../lib/argv.ts'; @@ -51,6 +51,18 @@ afterEach(() => { }); describe('captureCommand', () => { + it('fails a command that returns a non-zero exit code, with the result it wrote, and passes one that returns 0', async () => { + const failing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'fail' }); return { exitCode: 1 }; }; + const err = await captureCommand(failing, parseArgs(['test', 'run'])).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CommandFailedError); + expect((err as CommandFailedError).exitCode).toBe(1); + expect((err as CommandFailedError).result).toStrictEqual({ overall: 'fail' }); + expect(classifyError(err as Error).exitCode).toBe(1); + + const passing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'pass' }); return { exitCode: 0 }; }; + expect(await captureCommand(passing, parseArgs(['test', 'run']))).toStrictEqual({ overall: 'pass' }); + }); + it('captures JSON output from generate command', async () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const args = parseArgs(['generate', '--network', 'undeployed', '--output', walletFile]); diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 4dff4a18..37d6f251 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -42,6 +42,24 @@ export class CancelledError extends Error { } } +/** + * A command that ended with a non-zero exit code without throwing (a test run + * whose tests failed): the code, and the JSON result it wrote. A runner with no + * process exit code to set, such as the MCP server, reports it as a failure. + */ +export class CommandFailedError extends Error { + readonly exitCode: number; + readonly result: Readonly>; + + constructor(command: string, exitCode: number, result: Readonly>) { + super(`${command} ended with exit code ${exitCode}: ${JSON.stringify(result)}`); + this.exitCode = exitCode; + this.result = result; + this.name = 'CommandFailedError'; + Object.setPrototypeOf(this, CommandFailedError.prototype); + } +} + /** Throws CancelledError when the call's signal has aborted, so the call stops before its next step. */ export function throwIfCancelled(signal: AbortSignal | undefined): void { if (signal?.aborted === true) throw new CancelledError(); diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index 3270bf2d..5956f334 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -5,6 +5,7 @@ import { type ParsedArgs, MINIMAL_FLAG } from './argv.ts'; import type { Payer } from './payer.ts'; import { createCallContext, runHandler, type CommandHandler, type OutputSink } from './call-context.ts'; import { createSdkWarningRouter, sdkWarningCallsOn, type SdkWarningCalls } from './sdk-warnings.ts'; +import { CommandFailedError } from './errors.ts'; export interface CommandRun { /** Cancels the command; a call already cancelled never starts. None: it runs to the end. */ @@ -43,7 +44,8 @@ const serverStderr = (text: string): void => { process.stderr.write(text); }; * at once never report each other's. * * Returns the result as a JSON object ({} when the command wrote none). - * Throws the original error if the handler throws. + * Throws the original error if the handler throws, and CommandFailedError, + * carrying the result, if it returns a non-zero exit code. */ export async function captureCommand( handler: CommandHandler, @@ -65,7 +67,7 @@ export async function captureCommand( let running = true; const report = onProgress === undefined ? undefined : (message: string): void => { if (running) onProgress(message); }; try { - await sdkWarnings.run((warnings) => runHandler(handler, args, createCallContext({ + const outcome = await sdkWarnings.run((warnings) => runHandler(handler, args, createCallContext({ args, signal: signal ?? new AbortController().signal, output, @@ -73,6 +75,7 @@ export async function captureCommand( ...(report === undefined ? {} : { onProgress: report }), ...(payer === undefined ? {} : { payer }), }))); + if (outcome !== undefined && outcome.exitCode !== 0) throw new CommandFailedError(args.command ?? 'the command', outcome.exitCode, result); return result; } finally { running = false; From 2a2cb26783c5a6bce64dbd8b41f8c2efefe8f1a3 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:48:13 -0800 Subject: [PATCH 06/88] Comments say what they mean, not where it was planned Source comments, test names and script comments cited internal planning IDs and documents that readers of this repository can't see. Each now says what the reference meant, or drops it where the sentence stands alone. Also corrects stale comments: verbose is per call, not process-wide; status is dispatched only to be refused while it is reworked; the wallet migration comment sits by its call; the MCP server exposes the installed commands' tools, not every command. Three test constants named after plan steps are renamed to say "before the registry". No behaviour changes. --- scripts/check-layering.mjs | 10 ++--- scripts/check-process-safety.mjs | 30 ++++++------- scripts/measure-mcp-tokens.sh | 3 +- scripts/write-skill-docs.ts | 2 +- src/__tests__/agent-guidance.test.ts | 2 +- src/__tests__/call-context.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 4 +- src/__tests__/command-flags.test.ts | 4 +- src/__tests__/command-registry.test.ts | 38 ++++++++-------- src/__tests__/exec-program.test.ts | 2 +- src/__tests__/help.test.ts | 2 +- src/__tests__/helpers/cli-call.ts | 2 +- src/__tests__/localnet-cancellation.test.ts | 6 +-- src/__tests__/mcp-registry-tools.test.ts | 4 +- .../mcp-server-concurrent-calls.test.ts | 2 +- .../mcp-server-unknown-parameter.test.ts | 13 +++--- src/__tests__/process-safety.test.ts | 10 ++--- src/__tests__/provision-wallets.test.ts | 2 +- src/__tests__/read-cancellation.test.ts | 2 +- src/__tests__/run-command.test.ts | 4 +- src/__tests__/sdk-warnings.test.ts | 2 +- src/__tests__/settings.test.ts | 2 +- src/__tests__/skill-docs.test.ts | 2 +- src/__tests__/state-root.test.ts | 6 +-- src/__tests__/terminal-prompter.test.ts | 2 +- src/__tests__/verbose-per-call.test.ts | 2 +- src/__tests__/wallet-protect.test.ts | 2 +- src/commands/address.definition.ts | 2 +- src/commands/airdrop.definition.ts | 4 +- src/commands/balance.definition.ts | 4 +- src/commands/cache.definition.ts | 2 +- src/commands/chain.guidance.ts | 4 +- src/commands/config.definition.ts | 2 +- src/commands/connect.guidance.ts | 6 +-- src/commands/contract.definition.ts | 8 ++-- src/commands/contract.guidance.ts | 6 +-- src/commands/core.guidance.ts | 2 +- src/commands/dev.definition.ts | 2 +- src/commands/dev.guidance.ts | 2 +- src/commands/dust.definition.ts | 6 +-- src/commands/generate.definition.ts | 4 +- src/commands/genesis-address.definition.ts | 2 +- src/commands/grant.definition.ts | 4 +- src/commands/grant.guidance.ts | 6 +-- src/commands/help.definition.ts | 2 +- src/commands/help.ts | 6 +-- src/commands/info.definition.ts | 2 +- src/commands/inspect-cost.definition.ts | 2 +- src/commands/localnet.definition.ts | 2 +- src/commands/localnet.ts | 2 +- src/commands/manual.definition.ts | 2 +- src/commands/serve.definition.ts | 2 +- src/commands/status.definition.ts | 8 ++-- src/commands/test.definition.ts | 2 +- src/commands/transfer.definition.ts | 4 +- src/commands/wallet.definition.ts | 4 +- src/commands/wallet.guidance.ts | 2 +- src/lib/agent-guidance.ts | 2 +- src/lib/agent-manual.ts | 4 +- src/lib/call-context.ts | 6 +-- src/lib/cli-host.ts | 2 +- src/lib/command-definition.ts | 43 +++++++++---------- src/lib/command-dispatch.ts | 2 +- src/lib/command-flags.ts | 4 +- src/lib/errors.ts | 2 +- src/lib/grant/account-protector.ts | 2 +- src/lib/installed-commands.ts | 10 ++--- src/lib/json-output.ts | 2 +- src/lib/localnet.ts | 4 +- src/lib/mcp/known-params.ts | 9 ++-- src/lib/mcp/registry-tools.ts | 2 +- src/lib/mcp/skills.ts | 2 +- src/lib/resolve-network.ts | 2 +- src/lib/run-command.ts | 6 +-- src/lib/sdk-noise.ts | 2 +- src/lib/sdk-warnings.ts | 2 +- src/lib/settings.ts | 6 +-- src/lib/state-root.ts | 2 +- src/lib/verbose.ts | 2 +- src/lib/wallet-cache.ts | 4 +- src/mcp-server.ts | 6 +-- src/ui/spinner.ts | 2 +- src/wallet.ts | 4 +- 83 files changed, 198 insertions(+), 204 deletions(-) diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index bc386343..36c82ae4 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -27,14 +27,14 @@ const PACKAGES = ['core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'gran // under src/ wins. A file that matches nothing fails the check. const HOMES = [ ['shell', /^wallet\.ts$/], - // help plays the shell's intro, and manual builds the full manual; both render the installed registry (Y24, 2D). + // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|command-dispatch|agent-manual)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], - // A package's agent guidance (.guidance.ts) sits beside its commands (2G). + // A package's agent guidance (.guidance.ts) sits beside its commands. ...PACKAGES.map((pkg) => [pkg, new RegExp(`^commands/${pkg}\\.guidance\\.ts$`)]), // A command's definition (.definition.ts) lives in its command's package. @@ -116,9 +116,9 @@ export function homeOf(file) { const isGuidance = (rel) => /\.guidance\.ts$/.test(rel); /** - * Agent guidance is plain text for the shell and the MCP server to assemble - * (2G): a guidance file imports only core (the guidance type) and its own - * package, and no other package imports it. Paths are relative to src/. + * Agent guidance is plain text for the shell and the MCP server to assemble: + * a guidance file imports only core (the guidance type) and its own package, + * and no other package imports it. Paths are relative to src/. * Returns the rule the import breaks, or undefined. */ export function guidanceRule(fromRel, toRel) { diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 079da67f..48322130 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -1,16 +1,15 @@ #!/usr/bin/env node -// Checks that library code leaves the host process alone (spec §3.1, decision -// 20): no writing to the terminal, exiting, installing process handlers, +// Checks that library code leaves the host process alone: no writing to the terminal, exiting, installing process handlers, // patching console, changing directory, opening a prompt, reading the -// environment, or computing a path from the home directory (spec §7). Commands, ui/, the shell and the MCP server may; so may the +// environment, or computing a path from the home directory. Commands, ui/, the shell and the MCP server may; so may the // modules marked below as shell concerns. Commands may not write to the -// terminal either (2F, S8): their text goes through their call's output +// terminal either: their text goes through their call's output // (ctx.output.stdout / stderr), which the CLI writes to the process's streams // and the MCP server to its stderr. String and template-literal // contents and comments are skipped, so the contract runner's generated // scripts (which run as their own process) don't count. // -// And that nothing about a call lives in module globals (spec §4.4, D21, 2F): +// And that nothing about a call lives in module globals: // - library, ui and command code keeps no mutable state at module level (a // `let` or `var`, or a Map, Set or array that isn't typed readonly, or an // empty object to fill); what is shared on purpose is allowlisted by name, @@ -21,8 +20,8 @@ // call's context explicitly. // // Usage: node scripts/check-process-safety.mjs -// Exits 1 when a library does something §3.1 forbids, or any code breaks the -// 2F rules, and the allowlist doesn't name it. Imported, it exports +// Exits 1 when a library does something the rules above forbid, or any code +// breaks the module-state rules, and the allowlist doesn't name it. Imported, it exports // findViolations. import { readFileSync } from 'node:fs'; @@ -43,7 +42,7 @@ const RULES = [ ['reads the environment', /\bprocess\.env\b/], ['reads the terminal', /\bprocess\.stdin\b|\bsetRawMode\s*\(/], ['hands a child the terminal', /\bstdio\s*:\s*['"]inherit['"]|['"]inherit['"]/], - // Spec §7: the host gives the state root; a library never builds a path from the home directory. + // The host gives the state root; a library never builds a path from the home directory. ['computes a path from the home directory', /\bhomedir\s*\(|\bos\.homedir\b/], ]; @@ -52,7 +51,7 @@ const RAW_RULES = new Set(['opens a prompt', 'hands a child the terminal']); // What a command may not do: its text for the person goes through its call's output. const COMMAND_RULES = RULES.filter(([rule]) => rule === 'writes to the terminal'); -// The 2F rules, each with the code it applies to. +// The module-state rules, each with the code it applies to. const MODULE_STATE = 'keeps module state'; const STALE_STATE = 'allowlists module state it no longer keeps'; const AMBIENT = 'keeps ambient per-call storage'; @@ -66,7 +65,7 @@ const CALL_RULES = [ [AMBIENT, /\bfrom\s+['"](node:)?async_hooks['"]|\brequire\(\s*['"](node:)?async_hooks['"]\s*\)/, notNoiseFilter, true], ]; -// Shell concerns by design (1F): what they do to the process is their job. +// Shell concerns by design: what they do to the process is their job. const SHELL_CONCERNS = new Set([ 'lib/json-output.ts', // the --json output channel ]); @@ -80,9 +79,8 @@ export const ALLOWED = { 'lib/contract/runner.ts': ['reads the environment'], }; -// Module-level state that the 2F rule allows, by file and name, and why. A -// call's state is allowed only until the step of 2F that moves it into the -// call's context; what is shared on purpose holds no call's state. +// Module-level state that the module-state rule allows, by file and name, and +// why. A call's state is allowed only until it moves into the call's context; what is shared on purpose holds no call's state. export const ALLOWED_STATE = { // Shared on purpose: none holds a call's state. 'lib/passphrase.ts': { unlocked: 'shared on purpose: the passphrase this process has unlocked, by state root (one prompt per run)' }, @@ -90,7 +88,7 @@ export const ALLOWED_STATE = { 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/ws-rpc.ts': { connectionCounter: 'shared on purpose: the RPC connection id counter, unique across servers in the process' }, 'lib/wallet-config.ts': { warnedPlain: 'shared on purpose: each plain-text wallet is warned about once per run' }, - // The host sources, set once by the host at start (decision 1: host-set until phase 3; handlers see them through the context). + // The host sources, set once by the host at start (handlers see them through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, 'lib/state-root.ts': { source: 'shared on purpose: the host sets the paths source once' }, 'lib/notices.ts': { sink: 'shared on purpose: the host sets the notice sink once' }, @@ -252,8 +250,8 @@ function isLibrary(rel, file) { const isCommand = (rel) => rel.startsWith('commands/'); /** - * Every §3.1 break in library code, every terminal write in a command, and - * every 2F break, that the allowlists don't name: { file, line, rule }, and + * Every break of the library rules, every terminal write in a command, and + * every module-state break, that the allowlists don't name: { file, line, rule }, and * the name for module state. `src` is the folder the files' kinds are read * from (commands/, ui/, …): src/, unless a test plants files elsewhere. */ diff --git a/scripts/measure-mcp-tokens.sh b/scripts/measure-mcp-tokens.sh index 6f6b0d32..68524a48 100755 --- a/scripts/measure-mcp-tokens.sh +++ b/scripts/measure-mcp-tokens.sh @@ -1,7 +1,6 @@ #!/bin/bash # measure-mcp-tokens.sh — measure the byte size of MCP responses so we can -# track token consumption over time. See docs/tasks/archived/token-budget-plan.md -# for the policy this script supports. +# track token consumption over time. # # Usage: ./scripts/measure-mcp-tokens.sh # Output: per-call bytes + estimated tokens to stdout, one CSV-ish line each. diff --git a/scripts/write-skill-docs.ts b/scripts/write-skill-docs.ts index b07563a9..ea5dd4a9 100644 --- a/scripts/write-skill-docs.ts +++ b/scripts/write-skill-docs.ts @@ -1,5 +1,5 @@ // Writes docs/SKILL-CORE.md and docs/SKILL.md from the installed packages' -// guidance, as the MCP server assembles skill/core and skill/full (plan 2G). +// guidance, as the MCP server assembles skill/core and skill/full. // The copies stay in the repository for the README's links and the npm // package; a test fails when they differ from the assembly. // diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index c088db46..cb6310c0 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -1,4 +1,4 @@ -// Agent guidance per package (plan 2G, D19): each package is installed with its +// Agent guidance per package: each package is installed with its // pieces of the agent manual and the two skills, and the shell and the MCP // server assemble them. What the texts say is pinned by the behaviour snapshot // and by the docs/ copies (skill-docs.test.ts); these tests check the diff --git a/src/__tests__/call-context.test.ts b/src/__tests__/call-context.test.ts index f6b7b122..f0631fd4 100644 --- a/src/__tests__/call-context.test.ts +++ b/src/__tests__/call-context.test.ts @@ -1,4 +1,4 @@ -// A call's context (src/lib/call-context.ts, plan 2F): what each call's +// A call's context (src/lib/call-context.ts): what each call's // handler is given. Its output takes one result and passes each piece on as it // comes; its diagnostics show lines only when the call is verbose; a call // already cancelled never starts. diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 6276b3ea..a81146ce 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -1,4 +1,4 @@ -// Every command honours its call's cancellation (2F, S7). The 13 that ignored +// Every command honours its call's cancellation. The 13 that ignored // it: quick ones never start once cancelled (the runners refuse the call); // the ones that write check before each whole write; balance, status and // inspect-cost pass the signal into their reads; localnet is in @@ -171,7 +171,7 @@ describe('inspect-cost passes the signal into its reads', () => { await expect(cliCall(inspectCostCommand, parseArgs(['inspect-cost', '--network', 'undeployed', '--indexer-ws', `ws://127.0.0.1:${port}/api/v4/graphql/ws`, '--json']), { signal: call.signal })) .rejects.toMatchObject({ code: 'CANCELLED' }); - // Before 2F's S7 it waited out the probe's own 5s time limit, then went on to read the parameters. + // Before the signal reached it, it waited out the probe's own 5s time limit, then went on to read the parameters. expect(cancelledAt).toBeGreaterThan(0); expect(Date.now() - cancelledAt).toBeLessThan(2_000); expect(pending).toBe(1); diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index e71a392a..8ee8bf9d 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -74,7 +74,7 @@ describe('the accepted flags match the code', () => { 'resolveSeedSource(': ['seed', 'wallet'], 'resolveSeed(': ['seed', 'wallet'], 'isVerbose(': ['verbose'], - // The call's diagnostics are verbose when its --verbose is given (2F): a command that writes them, or hands them to a library, reads it. + // The call's diagnostics are verbose when its --verbose is given: a command that writes them, or hands them to a library, reads it. 'ctx.diagnostics.': ['verbose'], 'rejectNoCacheForWrites(': ['no-cache'], 'resolveTransferRequest(': ['shielded', 'force-shielded', 'wallet', 'network'], @@ -94,7 +94,7 @@ describe('the accepted flags match the code', () => { } // A command's definition (.definition.ts) sits beside it and is not a - // command, nor is a package's agent guidance (.guidance.ts, 2G). + // command, nor is a package's agent guidance (.guidance.ts). const commandFiles = readdirSync(COMMANDS_DIR).filter((f) => f.endsWith('.ts') && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts')); it('has an entry for every command file, and no entry without one', () => { diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 5cdb68f2..9fd588cd 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -1,7 +1,7 @@ -// The command registry (plan 2B): every command defined once, beside it. -// Since 2C the CLI's dispatch, its SDK commands and its accepted flags come -// from it, since 2D help, the manual and the intro, and since 2E the MCP -// server's tools. The lists they replaced are gone (Y13); what each output +// The command registry: every command defined once, beside it. The CLI's +// dispatch, its SDK commands and its accepted flags come from it, and so do +// help, the manual, the intro and the MCP server's tools. The lists they +// replaced are gone; what each output // says is pinned by the behaviour snapshot, and the tests here check what the // registry must hold on its own. @@ -38,13 +38,13 @@ import type { WalletProtector } from '../lib/wallet-protector.ts'; const SRC = join(import.meta.dirname, '..'); const registry = installedCommands; -describe('the dispatch (src/lib/command-dispatch.ts, from the registry since 2C)', () => { - // What the switch in src/wallet.ts gave each command before 2C, as it was +describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => { + // What the switch in src/wallet.ts gave each command before the registry, as it was // read from that switch at b5dc946: the registry's dispatch must give the same. const GENERATE_NOTICE = '\n Note: "midnight generate" is deprecated.\n Use "midnight wallet generate " instead.\n\n'; const STATUS_REFUSAL = 'The "status" command is currently being reworked. Check back soon.'; - // Since 2F every handler gets its call's signal, so the definitions no longer say which do (decision 2). - const SWITCH_BEFORE_2C: Record = { + // Every handler gets its call's signal, so the definitions don't say which do. + const SWITCH_BEFORE_REGISTRY: Record = { 'address': {}, 'airdrop': {}, 'balance': {}, 'cache': {}, 'config': {}, 'contract': { payer: true }, 'dev': { payer: true }, 'dust': {}, 'generate': { notice: GENERATE_NOTICE }, 'genesis-address': {}, 'grant': { payer: true }, @@ -55,7 +55,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry since 2C) it('gives every command what the switch gave it, the signal now to every one', () => { const given = Object.fromEntries(registry.commands.map((c) => [c.name, { ...c.shell }])); - expect(given).toStrictEqual(SWITCH_BEFORE_2C); + expect(given).toStrictEqual(SWITCH_BEFORE_REGISTRY); }); it('loads each handler from its own command\'s module', async () => { @@ -183,13 +183,13 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry since 2C) }); describe('the commands that need the wallet SDK (heap re-exec and forced exit)', () => { - // FACADE_COMMANDS in src/wallet.ts before 2C. - const FACADE_COMMANDS_BEFORE_2C = ['airdrop', 'transfer', 'dust', 'balance', 'serve', 'test', 'contract', 'dev', 'grant']; + // FACADE_COMMANDS in src/wallet.ts before the registry. + const FACADE_COMMANDS_BEFORE_REGISTRY = ['airdrop', 'transfer', 'dust', 'balance', 'serve', 'test', 'contract', 'dev', 'grant']; it('are the ones FACADE_COMMANDS listed', () => { const rebuilt = registry.commands.filter((c) => commandNeedsWalletSdk(registry, c.name)).map((c) => c.name); - expect(new Set(rebuilt)).toStrictEqual(new Set(FACADE_COMMANDS_BEFORE_2C)); - expect(rebuilt).toHaveLength(FACADE_COMMANDS_BEFORE_2C.length); + expect(new Set(rebuilt)).toStrictEqual(new Set(FACADE_COMMANDS_BEFORE_REGISTRY)); + expect(rebuilt).toHaveLength(FACADE_COMMANDS_BEFORE_REGISTRY.length); }); it('do not include a command that is not installed', () => { @@ -274,7 +274,7 @@ describe('the MCP tools, generated from the registry', () => { expect(NETWORK_PARAM.enum).toStrictEqual(getValidNetworkNames()); }); - // Confirmed since 2E (Y29): it was marked destructive yet ran at once. + // Confirmed since tools came from the registry: it was marked destructive yet ran at once. const NEWLY_CONFIRMED = 'midnight_wallet_remove'; it('needs confirmation for wallet remove, and every confirmed tool checks the call before a token is given', () => { @@ -287,7 +287,7 @@ describe('the MCP tools, generated from the registry', () => { expect(confirmationText(remove, { name: 'bob' })).toBe('Remove wallet bob: its file, and the seed in it, is deleted from this machine'); }); - it('lets a tool pass on its command\'s flags beyond its schema only when its argv passes the rest on (2C\'s rule, superseded by the schema)', () => { + it('lets a tool pass on its command\'s flags beyond its schema only when its argv passes the rest on (the old pass-through rule, superseded by the schema)', () => { expect(toolPassThroughFlags(registry, 'midnight_transfer')).toStrictEqual([ ...registry.find('transfer')!.flags.map((f) => f.name), 'help', 'h', 'json', 'version', 'v', ]); @@ -308,12 +308,12 @@ describe('the MCP tools, generated from the registry', () => { } }); - // The argv each tool's own handler built before 2E (src/lib/mcp/tools.ts at + // The argv each tool's own handler built before the registry (src/lib/mcp/tools.ts at // 03b55c4), for a call with these parameters. The generic mapping must // build the same. const args = (command: string, subcommand: string | undefined, positionals: string[], flags: Record): ParsedArgs => ({ command, subcommand, positionals, flags: { json: true, ...flags } }); - const ARGV_BEFORE_2E: [tool: string, params: Record, argv: ParsedArgs][] = [ + const ARGV_BEFORE_REGISTRY: [tool: string, params: Record, argv: ParsedArgs][] = [ ['midnight_wallet_generate', { name: 'alice', network: 'preprod', seed: 'ab', force: 'true' }, args('wallet', 'generate', ['alice'], { network: 'preprod', seed: 'ab', force: true })], ['midnight_wallet_generate', { name: 'alice', mnemonic: 'w o r d s', force: true }, args('wallet', 'generate', ['alice'], { mnemonic: 'w o r d s', force: true })], ['midnight_wallet_list', {}, args('wallet', 'list', [], {})], @@ -364,12 +364,12 @@ describe('the MCP tools, generated from the registry', () => { ]; it('builds the argv each tool\'s own handler built', () => { - for (const [name, params, expected] of ARGV_BEFORE_2E) { + for (const [name, params, expected] of ARGV_BEFORE_REGISTRY) { const tool = registry.tools.find((t) => t.name === name)!; expect(toolArgv(tool, params), `${name} ${JSON.stringify(params)}`).toStrictEqual(expected); } // Every tool is covered. - expect(new Set(ARGV_BEFORE_2E.map(([name]) => name))).toStrictEqual(new Set(registry.tools.map((t) => t.name))); + expect(new Set(ARGV_BEFORE_REGISTRY.map(([name]) => name))).toStrictEqual(new Set(registry.tools.map((t) => t.name))); }); }); diff --git a/src/__tests__/exec-program.test.ts b/src/__tests__/exec-program.test.ts index c7c2e64a..fd800701 100644 --- a/src/__tests__/exec-program.test.ts +++ b/src/__tests__/exec-program.test.ts @@ -1,4 +1,4 @@ -// The runner localnet's Docker commands go through (2F, S7): asynchronous, +// The runner localnet's Docker commands go through: asynchronous, // and it kills the program when the call is cancelled. Checked on real // processes (this Node, running a short script), never on Docker. diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index a11db819..a325bf43 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -148,7 +148,7 @@ describe('help\'s specs (from the registry)', () => { }); }); -describe('help — the lists come from the registry (2D)', () => { +describe('help — the lists come from the registry', () => { /** The intro's command lines, in the order shown: ` name brief`. */ function introLines(stderr: string): string[] { return stderr.split('\n').filter((line) => /^ {2}[a-z-]+ {2,}\S/.test(line)).map((line) => line.trim().replace(/\s{2,}/, ' ')); diff --git a/src/__tests__/helpers/cli-call.ts b/src/__tests__/helpers/cli-call.ts index 7a09d0fc..eb3a39d7 100644 --- a/src/__tests__/helpers/cli-call.ts +++ b/src/__tests__/helpers/cli-call.ts @@ -1,4 +1,4 @@ -// A handler called as the CLI calls it (2F): with a context built as the +// A handler called as the CLI calls it: with a context built as the // shell builds one, its result written at once to stdout as one JSON line. // Tests that read a command's output from the process's streams call it so. diff --git a/src/__tests__/localnet-cancellation.test.ts b/src/__tests__/localnet-cancellation.test.ts index 5384f53a..9c1b9dbf 100644 --- a/src/__tests__/localnet-cancellation.test.ts +++ b/src/__tests__/localnet-cancellation.test.ts @@ -1,4 +1,4 @@ -// localnet honours its call's cancellation (2F, S7). Regression: it ran Docker +// localnet honours its call's cancellation. Regression: it ran Docker // with execSync, so a `localnet up` froze the MCP server, and a cancelled call // ran to the end. Docker now runs through a runner the call passes its signal // to, which kills the Docker client on cancel. No real Docker runs here: the @@ -110,7 +110,7 @@ describe('localnet commands, cancelled while Docker runs', () => { }); it('clean: cancelled during its compose down, it stops there and removes no container', async () => { - // Before 2F's S7 the clean swallowed any failure of its compose down, a cancellation included, and went on removing. + // Before the cancellation fix, the clean swallowed any failure of its compose down, a cancellation included, and went on removing. const call = new AbortController(); const docker = standInDocker( (args) => { @@ -135,7 +135,7 @@ describe('localnet commands, cancelled while Docker runs', () => { }); }); -describe('localnet up, cancelled (decision 4: started containers stay, and it says which)', () => { +describe('localnet up, cancelled (started containers stay, and it says which)', () => { const dockerCall = (exec: ExecRunner, signal: AbortSignal): DockerCall => ({ signal, exec, onStderr: () => {} }); it('during docker compose up: the client is killed, and the error names the containers left in place', async () => { diff --git a/src/__tests__/mcp-registry-tools.test.ts b/src/__tests__/mcp-registry-tools.test.ts index 39299236..c2d95b27 100644 --- a/src/__tests__/mcp-registry-tools.test.ts +++ b/src/__tests__/mcp-registry-tools.test.ts @@ -1,5 +1,5 @@ -// The MCP server's tools from a registry (src/lib/mcp/registry-tools.ts, plan -// 2E), with test commands whose handlers record the argv they get and write +// The MCP server's tools from a registry (src/lib/mcp/registry-tools.ts), +// with test commands whose handlers record the argv they get and write // their JSON result through their call's context, as a command does. import { describe, expect, it } from 'vitest'; diff --git a/src/__tests__/mcp-server-concurrent-calls.test.ts b/src/__tests__/mcp-server-concurrent-calls.test.ts index a81373b7..b7b5e577 100644 --- a/src/__tests__/mcp-server-concurrent-calls.test.ts +++ b/src/__tests__/mcp-server-concurrent-calls.test.ts @@ -1,4 +1,4 @@ -// The gate test of 2F (S9): two calls at once in one real MCP server, one of +// Two calls at once in one real MCP server, one of // them cancelled. Run through this checkout's MCP server as a process of its // own, over stdio, with a temporary home. Each call reads an address's balance // from its own stand-in indexer (a WebSocket run by this test, answering diff --git a/src/__tests__/mcp-server-unknown-parameter.test.ts b/src/__tests__/mcp-server-unknown-parameter.test.ts index 5fd938b6..e178f849 100644 --- a/src/__tests__/mcp-server-unknown-parameter.test.ts +++ b/src/__tests__/mcp-server-unknown-parameter.test.ts @@ -1,6 +1,5 @@ -// A tool parameter the tool doesn't take is refused (Y29): since 2E, one -// outside the tool's schema, which lists every parameter the tool takes (2C -// also let through any flag of the tool's command). The server used to turn +// A tool parameter the tool doesn't take is refused: one outside the tool's +// schema, which lists every parameter the tool takes. The server used to turn // every parameter into a flag unchecked, so a misspelt one was silently // dropped and the command ran on its defaults (the CLI has refused unknown flags since the wrong-chain write). // Run through this checkout's MCP server as a real process with a temporary @@ -40,7 +39,7 @@ const call = async (name: string, args: Record) => { // A port nothing listens on: an endpoint a call is given never reaches a chain. const CLOSED = { node: 'ws://127.0.0.1:1', 'indexer-ws': 'ws://127.0.0.1:1/api/v4/graphql/ws', 'proof-server': 'http://127.0.0.1:1' }; -describe('a tool\'s schema, generated from its command\'s flags (plan 2E)', () => { +describe('a tool\'s schema, generated from its command\'s flags', () => { it('shows midnight_transfer\'s network and endpoints, which agents could pass but not see', async () => { const { tools } = await client.listTools(); const transfer = tools.find((tool) => tool.name === 'midnight_transfer')!; @@ -53,7 +52,7 @@ describe('a tool\'s schema, generated from its command\'s flags (plan 2E)', () = expect(transfer.inputSchema.required).toStrictEqual(['to', 'amount']); }, 60_000); - it('is the one check: a flag of the command outside it is refused, though 2C let it through', async () => { + it('is the one check: a flag of the command outside it is refused, though the old pass-through rule let it through', async () => { // --json is a flag every command takes, and the server always sets it. const { isError, body } = await call('midnight_genesis_address', { network: 'undeployed', json: true }); expect(isError).toBe(true); @@ -98,7 +97,7 @@ describe('a tool parameter outside the tool\'s schema', () => { const { isError, body } = await call('midnight_transfer', { to: 'mn_addr_undeployed1x', amount: '1', network: 'undeployed', nodes: 'ws://x' }); expect(isError).toBe(true); expect(body).toMatchObject({ error: true, code: 'INVALID_ARGS' }); - // network is in the schema since 2E: transfer accepts --network and the tool passes it on. + // network is in the schema: transfer accepts --network and the tool passes it on. expect(body.message).toBe( 'Unknown parameter for midnight_transfer: nodes\n' + 'Its parameters: to, amount, wallet, force-shielded, network, shielded, node, indexer-ws, proof-server', @@ -107,7 +106,7 @@ describe('a tool parameter outside the tool\'s schema', () => { expect(body.pending).toBeUndefined(); }, 60_000); - it('lets through a flag of the command its schema gained in 2E, which reaches the command', async () => { + it('lets through a flag of the command its schema gained, which reaches the command', async () => { // address's schema gained --wallet; with --seed given too, the seed wins, as at the CLI. const { tools } = await client.listTools(); expect(Object.keys(tools.find((t) => t.name === 'midnight_address')!.inputSchema.properties ?? {})).toContain('wallet'); diff --git a/src/__tests__/process-safety.test.ts b/src/__tests__/process-safety.test.ts index 1de4770b..dd167000 100644 --- a/src/__tests__/process-safety.test.ts +++ b/src/__tests__/process-safety.test.ts @@ -1,4 +1,4 @@ -// Libraries leave the host process alone (spec §3.1). The check finds each +// Libraries leave the host process alone. The check finds each // kind of break in a module planted for it, skips strings and comments, and // finds nothing in src/ beyond what its allowlist names. The SDK's noise is // filtered by the shell: a transient Wallet.* rejection reaches the library @@ -71,7 +71,7 @@ describe('the process-safety check', () => { expect(findViolations([quiet], {})).toEqual([]); }); - it('finds a command writing to the terminal itself, not through its call (2F, S8), and lets ui/ write', () => { + it('finds a command writing to the terminal itself, not through its call, and lets ui/ write', () => { // Planted under a folder of their own, read as src/ is. for (const sub of ['commands', 'ui']) mkdirSync(join(dir, sub)); const command = join(dir, 'commands', 'planted.ts'); @@ -94,7 +94,7 @@ describe('the process-safety check', () => { }); }); -// Nothing about a call lives in module globals (spec §4.4, D21, 2F). +// Nothing about a call lives in module globals. describe("the process-safety check keeps calls' state out of modules", () => { const plant = (name: string, lines: string[]) => { const file = join(dir, name); @@ -156,7 +156,7 @@ describe("the process-safety check keeps calls' state out of modules", () => { 'let other = 0;', ]); const rel = relative(resolve(ROOT, 'src'), file); - expect(found(file, { [rel]: { unlocked: 'shared on purpose', removed: 'removed by S9 (2F)' } })).toEqual([ + expect(found(file, { [rel]: { unlocked: 'shared on purpose', removed: 'no longer kept' } })).toEqual([ '2 keeps module state other', '0 allowlists module state it no longer keeps removed', ]); @@ -273,7 +273,7 @@ describe('the shell filters the SDK noise', () => { }); }); -// Each call's SDK warnings are its own (2F, S5). Regression: one listener +// Each call's SDK warnings are its own. Regression: one listener // stack for the process, whose newest listener got every warning, so two // calls at once in the MCP server got each other's. describe("the shell gives each call its own SDK warnings", () => { diff --git a/src/__tests__/provision-wallets.test.ts b/src/__tests__/provision-wallets.test.ts index ddf967be..f84d4dd5 100644 --- a/src/__tests__/provision-wallets.test.ts +++ b/src/__tests__/provision-wallets.test.ts @@ -81,7 +81,7 @@ describe('provisionDevWallets', () => { const airdrop = steps.airdrop; steps.airdrop = async (name, amount, signal) => { await airdrop(name, amount, signal); controller.abort(); }; - // Regression (2F, S7): it failed with the signal's own AbortError, which mn's error codes don't read as CANCELLED. + // Regression: it failed with the signal's own AbortError, which mn's error codes don't read as CANCELLED. await expect(provisionDevWallets({ names: ['dev-alice'], amountNight: 1000, steps, signal: controller.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(calls).toEqual(['generate dev-alice', 'airdrop dev-alice 1000']); }); diff --git a/src/__tests__/read-cancellation.test.ts b/src/__tests__/read-cancellation.test.ts index 3cdd473a..617be8a0 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/src/__tests__/read-cancellation.test.ts @@ -1,5 +1,5 @@ // The reads balance, inspect-cost and localnet's readiness waits make take -// the call's signal (2F, S7): cancelled, each stops at once with +// the call's signal: cancelled, each stops at once with // CancelledError (code CANCELLED), instead of waiting out its own time limit. // The endpoints are servers run by the test that take each request and never // answer. diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index bbd1e63d..1e5842f3 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -243,7 +243,7 @@ describe('captureCommand', () => { }); }); - // Regression (2F, S2): the capture target was one module global. Two calls + // Regression: the capture target was one module global. Two calls // in one server that overlapped shared it: the first to finish cleared it, // and the other's result fell through to stdout, the MCP protocol channel, // while its call returned {}. @@ -267,7 +267,7 @@ describe('captureCommand', () => { expect(io.stdout()).toBe(''); }); - // Regression (2F, S3): the progress target and the active spinner were + // Regression: the progress target and the active spinner were // module globals. The second call to start took the target, so what the // first call's spinners said went to the second call's client, and the // first call's went nowhere once the second ended. diff --git a/src/__tests__/sdk-warnings.test.ts b/src/__tests__/sdk-warnings.test.ts index 6402758d..63235266 100644 --- a/src/__tests__/sdk-warnings.test.ts +++ b/src/__tests__/sdk-warnings.test.ts @@ -1,4 +1,4 @@ -// The router of the SDK's warnings to the calls they came from (2F, S5). The +// The router of the SDK's warnings to the calls they came from. The // shell's filters, which tag a warning with the call that raised it, are // tested in a process of their own (process-safety.test.ts). diff --git a/src/__tests__/settings.test.ts b/src/__tests__/settings.test.ts index 95791219..6ea9e325 100644 --- a/src/__tests__/settings.test.ts +++ b/src/__tests__/settings.test.ts @@ -1,4 +1,4 @@ -// The environment variables of spec §5.4 reach libraries only as settings +// The environment variables reach libraries only as settings // the shell gives them: each maps to its setting, and a library with no // settings source behaves as if none were set, whatever the environment says. diff --git a/src/__tests__/skill-docs.test.ts b/src/__tests__/skill-docs.test.ts index c8b2dd0d..f438bbfa 100644 --- a/src/__tests__/skill-docs.test.ts +++ b/src/__tests__/skill-docs.test.ts @@ -1,5 +1,5 @@ // docs/SKILL-CORE.md and docs/SKILL.md are generated copies of the skills the -// MCP server assembles from the installed packages (plan 2G, decision 2): they +// MCP server assembles from the installed packages: they // stay in the repository for the README's links and the npm package. When one // differs from the assembly, run `npm run skill-docs`. The server itself is run // as a real process with a temporary home, to show it serves the assembly. diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 9a541c57..050be28c 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -1,5 +1,5 @@ -// Each owner builds its paths under the state root the host gives (spec §7), -// and the files land where they did before 1G, with the same contents: the +// Each owner builds its paths under the state root the host gives, +// and the files land where they did before the state root, with the same contents: the // fixture was recorded from the code before the change. A root outside the // home gets the same layout and nothing is written to the home; with no root // given, a library refuses instead of guessing. @@ -53,7 +53,7 @@ function layout(root: string, base: string): string[] { } describe('the state root the host gives', () => { - it('lays out every owner\'s files as before 1G, with the same contents', async () => { + it('lays out every owner\'s files as before the state root, with the same contents', async () => { const home = path.join(dir, 'home'); setHostPathsSource(() => ({ stateRoot: path.join(home, MIDNIGHT_DIR), home })); await writeEveryOwnersFiles(); diff --git a/src/__tests__/terminal-prompter.test.ts b/src/__tests__/terminal-prompter.test.ts index 6886f0f2..37eeb819 100644 --- a/src/__tests__/terminal-prompter.test.ts +++ b/src/__tests__/terminal-prompter.test.ts @@ -28,7 +28,7 @@ describe('the terminal prompter', () => { }); }); -// One terminal, one question at a time (2F, S6). The busy flag was a module +// One terminal, one question at a time. The busy flag was a module // global in approval.ts; it is the prompter's own now. describe('the terminal prompter asks one question at a time', () => { const terminal = () => { diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 5a8c0453..381c0bb4 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -1,4 +1,4 @@ -// Verbose is a call's own (2F, S4). Regression: --verbose switched on one +// Verbose is a call's own. Regression: --verbose switched on one // module global, which stayed on, so once one call in a server asked for // verbose lines, every later call wrote them too, and so did every library // that any call reached. diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index 6095781f..012f069a 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -2,7 +2,7 @@ // seals every plain-text wallet under it, saying which it sealed; run again, // it seals nothing new; with another passphrase than the one set, it changes // nothing. The accounts grant keeps are sealed by the protector grant -// provides, which the CLI passes in (decision 24); without it, wallet seals +// provides, which the CLI passes in; without it, wallet seals // only wallets. import * as fs from 'node:fs'; diff --git a/src/commands/address.definition.ts b/src/commands/address.definition.ts index b55d5811..cff35eb0 100644 --- a/src/commands/address.definition.ts +++ b/src/commands/address.definition.ts @@ -1,4 +1,4 @@ -// The `address` command, described once (plan 2B, spec §4.1). +// The `address` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index 62343b0e..30364ea7 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -1,4 +1,4 @@ -// The `airdrop` command, described once (plan 2B, spec §4.1). +// The `airdrop` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/command-definition.ts'; @@ -26,7 +26,7 @@ export const airdropDefinition: CommandDefinition = { { name: 'verbose', takesValue: false, - // Its lines go to the server's stderr, which no agent reads, and it switches verbose on for the whole process (2F). + // Its lines go to the server's stderr, which no agent reads. agent: { notForAgents: 'diagnostics for a person at a terminal' }, }, { diff --git a/src/commands/balance.definition.ts b/src/commands/balance.definition.ts index 6f5a7263..69842f4d 100644 --- a/src/commands/balance.definition.ts +++ b/src/commands/balance.definition.ts @@ -1,4 +1,4 @@ -// The `balance` command, described once (plan 2B, spec §4.1). +// The `balance` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/command-definition.ts'; @@ -37,7 +37,7 @@ export const balanceDefinition: CommandDefinition = { { name: 'verbose', takesValue: false, - // Its lines go to the server's stderr, which no agent reads, and it switches verbose on for the whole process (2F). + // Its lines go to the server's stderr, which no agent reads. agent: { notForAgents: 'diagnostics for a person at a terminal' }, }, { name: 'wallet', takesValue: true, agent: { type: 'string' } }, diff --git a/src/commands/cache.definition.ts b/src/commands/cache.definition.ts index 51f6434d..727edded 100644 --- a/src/commands/cache.definition.ts +++ b/src/commands/cache.definition.ts @@ -1,4 +1,4 @@ -// The `cache` command, described once (plan 2B, spec §4.1). +// The `cache` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; diff --git a/src/commands/chain.guidance.ts b/src/commands/chain.guidance.ts index 57b29da3..71714605 100644 --- a/src/commands/chain.guidance.ts +++ b/src/commands/chain.guidance.ts @@ -1,5 +1,5 @@ -// What the chain package (the error codes its chain checks raise) tells agents -// (plan 2G, D19): its pieces of `help --agent` and of the two skills, each +// What the chain package (the error codes its chain checks raise) tells agents: +// its pieces of `help --agent` and of the two skills, each // naming its section and its place there. import type { PackageGuidance } from '../lib/agent-guidance.ts'; diff --git a/src/commands/config.definition.ts b/src/commands/config.definition.ts index 58abf1b0..c2f42cdc 100644 --- a/src/commands/config.definition.ts +++ b/src/commands/config.definition.ts @@ -1,4 +1,4 @@ -// The `config` command, described once (plan 2B, spec §4.1). +// The `config` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; import { INDEXER_GRAPHQL_WS_PATH } from '../lib/constants.ts'; diff --git a/src/commands/connect.guidance.ts b/src/commands/connect.guidance.ts index b238bcd0..66601c7c 100644 --- a/src/commands/connect.guidance.ts +++ b/src/commands/connect.guidance.ts @@ -1,6 +1,6 @@ -// What the connect package (serve, the DApp connector) tells agents (plan 2G, -// D19): its pieces of `help --agent` and of the two skills, each naming its -// section and its place there. +// What the connect package (serve, the DApp connector) tells agents: +// its pieces of `help --agent` and of the two skills, each naming its section +// and its place there. import type { PackageGuidance } from '../lib/agent-guidance.ts'; diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index 08da4f66..3e6a661f 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -1,4 +1,4 @@ -// The `contract` command, described once (plan 2B, spec §4.1). +// The `contract` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '../lib/command-definition.ts'; @@ -160,7 +160,7 @@ export const contractDefinition: CommandDefinition = { name: 'midnight_contract_inspect', description: 'Inspect a compiled Compact contract: name, circuits (with arg/return types), witnesses, compiler/language/runtime versions. Reads managed//compiler/contract-info.json under the dapp dir. Returns a `siblings` array listing other contracts in the same project — call again with `name` to inspect a sibling.', annotations: { readOnlyHint: true, idempotentHint: true }, - // As this tool showed them before 2E. + // As this tool showed them before tool schemas came from the flags. params: [ { flag: 'path', schema: { type: 'string', description: 'Path to dApp directory (defaults to cwd)' } }, { flag: 'managed', schema: { type: 'string', description: 'Direct path to a managed// directory (overrides path)' } }, @@ -181,7 +181,7 @@ export const contractDefinition: CommandDefinition = { { flag: 'wallet' }, { flag: 'network' }, { - // As this tool showed it before 2E. + // As this tool showed it before tool schemas came from the flags. flag: 'path', schema: { type: 'string', description: 'dApp directory (defaults to cwd; needed to find the compiled artifact for state decoding)' }, }, @@ -199,7 +199,7 @@ export const contractDefinition: CommandDefinition = { params: [ { flag: 'wallet' }, { flag: 'network' }, - // As this tool showed it before 2E. + // As this tool showed it before tool schemas came from the flags. { flag: 'args', schema: { type: 'string', description: 'JSON-encoded array or object of constructor arguments' } }, { flag: 'path' }, { flag: 'managed' }, diff --git a/src/commands/contract.guidance.ts b/src/commands/contract.guidance.ts index 7862aace..d66dce61 100644 --- a/src/commands/contract.guidance.ts +++ b/src/commands/contract.guidance.ts @@ -1,6 +1,6 @@ -// What the contract package (contract and inspect-cost) tells agents (plan 2G, -// D19): its pieces of `help --agent` and of the two skills, each naming its -// section and its place there, and its tools' rows in the manual's tools table. +// What the contract package (contract and inspect-cost) tells agents: +// its pieces of `help --agent` and of the two skills, each naming its section +// and its place there, and its tools' rows in the manual's tools table. import type { PackageGuidance } from '../lib/agent-guidance.ts'; diff --git a/src/commands/core.guidance.ts b/src/commands/core.guidance.ts index bfd8e8fc..1abe43b7 100644 --- a/src/commands/core.guidance.ts +++ b/src/commands/core.guidance.ts @@ -1,5 +1,5 @@ // What the core package (config, and the error codes its base raises) tells -// agents (plan 2G, D19): its pieces of `help --agent` and of the two skills, +// agents: its pieces of `help --agent` and of the two skills, // each naming its section and its place there, and its tools' rows in the // manual's tools table. diff --git a/src/commands/dev.definition.ts b/src/commands/dev.definition.ts index ac01e0ae..60d1253e 100644 --- a/src/commands/dev.definition.ts +++ b/src/commands/dev.definition.ts @@ -1,4 +1,4 @@ -// The `dev` command, described once (plan 2B, spec §4.1). +// The `dev` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; diff --git a/src/commands/dev.guidance.ts b/src/commands/dev.guidance.ts index 770fa6d8..55e769ed 100644 --- a/src/commands/dev.guidance.ts +++ b/src/commands/dev.guidance.ts @@ -1,4 +1,4 @@ -// What the dev package (localnet, test and dev) tells agents (plan 2G, D19): +// What the dev package (localnet, test and dev) tells agents: // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index 441e205f..68ae85d0 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -1,4 +1,4 @@ -// The `dust` command, described once (plan 2B, spec §4.1). +// The `dust` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/command-definition.ts'; @@ -26,7 +26,7 @@ export const dustDefinition: CommandDefinition = { { name: 'verbose', takesValue: false, - // Its lines go to the server's stderr, which no agent reads, and it switches verbose on for the whole process (2F). + // Its lines go to the server's stderr, which no agent reads. agent: { notForAgents: 'diagnostics for a person at a terminal' }, }, { @@ -111,7 +111,7 @@ export const dustDefinition: CommandDefinition = { name: 'midnight_dust_status', description: 'Dust status. Default: { network, registered, registeredUtxos, unregisteredUtxos, dustBalance, dustAvailable }. Pass { full: true } for sync internals (eventsApplied, ownedUtxos, cached).', annotations: { readOnlyHint: true, openWorldHint: true }, - // As this tool showed them before 2E. + // As this tool showed them before tool schemas came from the flags. params: [ { flag: 'wallet' }, { flag: 'proof-server', schema: { type: 'string' } }, diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index 5389f0e0..10083f7e 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -1,4 +1,4 @@ -// The `generate` command, described once (plan 2B, spec §4.1). +// The `generate` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; @@ -57,6 +57,6 @@ export const generateDefinition: CommandDefinition = { needsWalletSdk: false, shell: { notice: '\n Note: "midnight generate" is deprecated.\n Use "midnight wallet generate " instead.\n\n' }, load: () => import('./generate.ts'), - // Y29: the MCP server can load generate's handler, but its tool was removed (agents use midnight_wallet_generate). + // The MCP server can load generate's handler, but its tool was removed (agents use midnight_wallet_generate). mcp: { tools: [] }, }; diff --git a/src/commands/genesis-address.definition.ts b/src/commands/genesis-address.definition.ts index ecf7fc49..bf545c5c 100644 --- a/src/commands/genesis-address.definition.ts +++ b/src/commands/genesis-address.definition.ts @@ -1,4 +1,4 @@ -// The `genesis-address` command, described once (plan 2B, spec §4.1). +// The `genesis-address` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index 572922fd..a90a3508 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -1,4 +1,4 @@ -// The `grant` command, described once (plan 2B, spec §4.1). +// The `grant` command, described once. import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '../lib/command-definition.ts'; @@ -162,7 +162,7 @@ export const grantDefinition: CommandDefinition = { blockHeight: 'The block it landed in (deposit)', }, }, - // Y29: the intro had no line for grant until 2D; it sits beside the contract commands. + // The intro's line for grant sits beside the contract commands. intro: { brief: 'Grants that let agents spend', order: 12 }, needsWalletSdk: true, shell: { payer: true }, diff --git a/src/commands/grant.guidance.ts b/src/commands/grant.guidance.ts index 3624b885..2da4bd23 100644 --- a/src/commands/grant.guidance.ts +++ b/src/commands/grant.guidance.ts @@ -1,6 +1,6 @@ -// What the grant package (mn grant, the first plugin) tells agents (plan 2G, -// D19): its pieces of `help --agent` and of the two skills, each naming its -// section and its place there, and its tools' rows in the manual's tools table. +// What the grant package (mn grant, the first plugin) tells agents: +// its pieces of `help --agent` and of the two skills, each naming its section +// and its place there, and its tools' rows in the manual's tools table. import type { PackageGuidance } from '../lib/agent-guidance.ts'; diff --git a/src/commands/help.definition.ts b/src/commands/help.definition.ts index 7c94669d..947719fb 100644 --- a/src/commands/help.definition.ts +++ b/src/commands/help.definition.ts @@ -1,4 +1,4 @@ -// The `help` command, described once (plan 2B, spec §4.1). +// The `help` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; diff --git a/src/commands/help.ts b/src/commands/help.ts index e912e1e1..1a4a968e 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -2,8 +2,8 @@ // Horizontal layout: logo on left, commands on right (all on stderr) // Agent-friendly: plain text when piped (non-TTY) // JSON mode: outputs capability manifest for agent self-discovery -// Every list of commands it shows comes from the command registry (plan 2D), -// and the agent manual from the installed packages' guidance (2G). +// Every list of commands it shows comes from the command registry, and the +// agent manual from the installed packages' guidance. import { type ParsedArgs, hasFlag } from '../lib/argv.ts'; import { bold, teal, gray, dim } from '../ui/colors.ts'; @@ -105,7 +105,7 @@ function outputJsonManifest(ctx: CallContext): void { ctx.output.result(manifest); } -// The agent manual: the shell's skeleton and each installed package's pieces (2G). +// The agent manual: the shell's skeleton and each installed package's pieces. function printAgentManual(output: CallOutput): void { output.stdout(agentManual(installedCommands)); } diff --git a/src/commands/info.definition.ts b/src/commands/info.definition.ts index 29f77172..4609f0e9 100644 --- a/src/commands/info.definition.ts +++ b/src/commands/info.definition.ts @@ -1,4 +1,4 @@ -// The `info` command, described once (plan 2B, spec §4.1). +// The `info` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; diff --git a/src/commands/inspect-cost.definition.ts b/src/commands/inspect-cost.definition.ts index 9013c41e..661a416a 100644 --- a/src/commands/inspect-cost.definition.ts +++ b/src/commands/inspect-cost.definition.ts @@ -1,4 +1,4 @@ -// The `inspect-cost` command, described once (plan 2B, spec §4.1). +// The `inspect-cost` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; diff --git a/src/commands/localnet.definition.ts b/src/commands/localnet.definition.ts index ac85ed14..86c28cb5 100644 --- a/src/commands/localnet.definition.ts +++ b/src/commands/localnet.definition.ts @@ -1,4 +1,4 @@ -// The `localnet` command, described once (plan 2B, spec §4.1). +// The `localnet` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index a8f43218..aa3ba67f 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -93,7 +93,7 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) } } } catch (err) { - // Cancelled: the containers already started stay in place, and the error says which (decision 4). + // Cancelled: the containers already started stay in place, and the error says which. if (err instanceof CancelledError) { spinner.fail('Cancelled: containers already started stay in place'); throw err; diff --git a/src/commands/manual.definition.ts b/src/commands/manual.definition.ts index 7c832b2c..4e80fefd 100644 --- a/src/commands/manual.definition.ts +++ b/src/commands/manual.definition.ts @@ -1,4 +1,4 @@ -// The `manual` command, described once (plan 2B, spec §4.1). +// The `manual` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; diff --git a/src/commands/serve.definition.ts b/src/commands/serve.definition.ts index 6680c91e..39a3cfb1 100644 --- a/src/commands/serve.definition.ts +++ b/src/commands/serve.definition.ts @@ -1,4 +1,4 @@ -// The `serve` command, described once (plan 2B, spec §4.1). +// The `serve` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; diff --git a/src/commands/status.definition.ts b/src/commands/status.definition.ts index 39e57459..8722c00d 100644 --- a/src/commands/status.definition.ts +++ b/src/commands/status.definition.ts @@ -1,13 +1,13 @@ -// The `status` command, described once (plan 2B, spec §4.1). +// The `status` command, described once. import type { CommandDefinition } from '../lib/command-definition.ts'; export const statusDefinition: CommandDefinition = { name: 'status', order: 190, - // Y29: the shell dispatches status only to refuse it, help and the intro - // don't list it, and the MCP server can load it with no tool to call it. - // Recorded as each list has it, fixed in 2C–2G. + // status is being reworked: the shell dispatches it only to refuse it, help + // and the intro don't list it, and the MCP server can load it with no tool + // to call it. flags: [ { name: 'all', takesValue: false }, { name: 'network', takesValue: true }, diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index 5ca51ae2..8e452718 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -1,4 +1,4 @@ -// The `test` command, described once (plan 2B, spec §4.1). +// The `test` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 837f623a..8bb04603 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -1,4 +1,4 @@ -// The `transfer` command, described once (plan 2B, spec §4.1). +// The `transfer` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '../lib/command-definition.ts'; @@ -34,7 +34,7 @@ export const transferDefinition: CommandDefinition = { { name: 'verbose', takesValue: false, - // Its lines go to the server's stderr, which no agent reads, and it switches verbose on for the whole process (2F). + // Its lines go to the server's stderr, which no agent reads. agent: { notForAgents: 'diagnostics for a person at a terminal' }, }, { diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 000849ac..1f143c93 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -1,4 +1,4 @@ -// The `wallet` command, described once (plan 2B, spec §4.1). +// The `wallet` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; @@ -156,7 +156,7 @@ export const walletDefinition: CommandDefinition = { order: 4, }, { - // Destructive, so confirmed like the other destructive tools (Y29). + // Destructive, so confirmed like the other destructive tools. name: 'midnight_wallet_remove', description: 'Remove wallet.', annotations: { destructiveHint: true }, diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index ed5c4e7f..35ffdb98 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -1,5 +1,5 @@ // What the wallet package (wallets, balances, transfers, Dust and the cache) -// tells agents (plan 2G, D19): its pieces of `help --agent` and of the two +// tells agents: its pieces of `help --agent` and of the two // skills, each naming its section and its place there, and its tools' rows in // the manual's tools table. diff --git a/src/lib/agent-guidance.ts b/src/lib/agent-guidance.ts index 831dec6b..cc267b26 100644 --- a/src/lib/agent-guidance.ts +++ b/src/lib/agent-guidance.ts @@ -1,4 +1,4 @@ -// Agent guidance per package (spec §4.3, D19, plan 2G): each package brings +// Agent guidance per package: each package brings // its pieces of the three texts that teach agents to use mn, the way it brings // its commands. `help --agent` is the shell's; the two skills the MCP server // serves (skill/core, and skill/full with its legacy alias) are the server's. diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index afdc12f8..0d090b05 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -1,4 +1,4 @@ -// The `help --agent` manual (plan 2G, D19): the shell's skeleton of sections +// The `help --agent` manual: the shell's skeleton of sections // and its own text (the overview, networks, JSON conventions, the MCP server's // setup, its tools table and resources), with each installed package's pieces // placed in the sections they name. The tools table is generated from the @@ -30,7 +30,7 @@ export const AGENT_MANUAL_SECTIONS = [ /** * The tools table's topic groups, in order. `width` is the description - * column's, as the hand-written table aligned each group before 2G. + * column's, as the old hand-written table aligned each group. */ export const TOOL_GROUPS: readonly { readonly id: string; readonly title: string; readonly width: number }[] = [ { id: 'wallet-management', title: 'Wallet Management', width: 53 }, diff --git a/src/lib/call-context.ts b/src/lib/call-context.ts index 8ba48708..79e58754 100644 --- a/src/lib/call-context.ts +++ b/src/lib/call-context.ts @@ -1,4 +1,4 @@ -// One call, one context (spec §4.4, D21, plan 2F). Every handler gets the +// One call, one context. Every handler gets the // context of its call: its cancellation signal, where its output goes, its // progress, its diagnostics, where the SDK's warnings go, its configuration, // and the payer and protectors its caller gives. Nothing about a call lives in @@ -54,7 +54,7 @@ export interface CallDiagnostics { export type { CallSdkWarnings } from './sdk-warnings.ts'; -/** A call's configuration, read when the call starts (decision 1: host-set until phase 3). */ +/** A call's configuration, read when the call starts (set by the host). */ export interface CallConfig { readonly settings: Settings; readonly paths: HostPaths; @@ -62,7 +62,7 @@ export interface CallConfig { /** * The context of one call. `Protector` is what `wallet protect` runs (the - * wallet package defines it, D24); other commands never look at it. + * wallet package defines it); other commands never look at it. */ export interface CallContext { /** The call's cancellation, always present. */ diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 89ca2f7d..5328daf2 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -1,5 +1,5 @@ // A shell concern: what the CLI and the MCP server, as hosts, give the -// libraries at start (spec §3.1, §5.4, §7). Libraries never set these +// libraries at start. Libraries never set these // themselves; a consumer sets its own. // - the filters for the SDK's noise, acting while a call listens, and the // calls it runs, whose SDK warnings go to the call that raised them; diff --git a/src/lib/command-definition.ts b/src/lib/command-definition.ts index a2ebdbdc..89ceb708 100644 --- a/src/lib/command-definition.ts +++ b/src/lib/command-definition.ts @@ -1,15 +1,14 @@ -// One command, described once (spec §4.1, plan 2B): its subcommands, flags, -// help, the intro's line, whether it needs the wallet SDK, what the shell -// passes its handler, its handler, and its MCP tools. Plain data and a lazily -// loaded handler, tied to no CLI framework (D10). Each command's definition -// sits beside it (src/commands/.definition.ts) and must not load the -// handler's module until asked, so reading the registry loads no SDK. +// One command, described once: its subcommands, flags, help, the intro's +// line, whether it needs the wallet SDK, what the shell passes its handler, +// its handler, and its MCP tools. Plain data and a lazily loaded handler, +// tied to no CLI framework. Each command's definition sits beside it +// (src/commands/.definition.ts) and must not load the handler's module +// until asked, so reading the registry loads no SDK. // -// The shell's dispatch and flag checks read the registry since 2C; help, the -// manual and the intro since 2D; the MCP server's tools since 2E, each tool's -// schema generated from what it takes and its command's flags. Where the old -// lists disagreed, Y29 (the plan's STATUS) fixes them in 2C–2G. Since 2G a -// package is installed with its commands and its agent guidance (D19). +// The shell's dispatch and flag checks, help, the manual, the intro and the +// MCP server's tools all read the registry; each tool's schema is generated +// from what it takes and its command's flags. A package is installed with its +// commands and its agent guidance. import { FULL_FLAG, type ParsedArgs } from './argv.ts'; import { type PackageGuidance, type ToolsTableRow, assertDistinctPlaces } from './agent-guidance.ts'; @@ -25,7 +24,7 @@ export interface ParamSchema { /** A network as tools show it: one of the networks mn knows (a test keeps it equal to network.ts's). */ export const NETWORK_PARAM: ParamSchema = { type: 'string', enum: ['preprod', 'preview', 'undeployed'] }; -/** The endpoint flags, as the tools that took them unseen until 2E describe them. */ +/** The endpoint flags, as the tools that used to take them unseen describe them. */ export const ENDPOINT_PARAMS = { node: { type: 'string', description: 'Node RPC URL (default: the configured one, or the network\'s)' }, 'indexer-ws': { type: 'string', description: 'Indexer WebSocket URL (default: the configured one, or the network\'s)' }, @@ -69,11 +68,11 @@ export interface CommandHelp { readonly jsonFields?: Readonly>; } -/** What the shell does for a command around its handler. Every handler gets its call's signal (2F). */ +/** What the shell does for a command around its handler. Every handler gets its call's signal. */ export interface ShellCall { - /** The handler gets the shell's payer, the served wallet (D24). */ + /** The handler gets the shell's payer, the served wallet. */ readonly payer?: true; - /** The handler gets the protectors other packages provide (wallet protect, D24). */ + /** The handler gets the protectors other packages provide (wallet protect). */ readonly protectors?: true; /** Written to stderr before the handler runs. */ readonly notice?: string; @@ -82,7 +81,7 @@ export interface ShellCall { } /** - * A command's module: its handler takes the call's context (2F) and may return + * A command's module: its handler takes the call's context and may return * its exit code. Method syntax, so a handler may narrow the protectors it is * given (wallet protect's are the wallet package's). */ @@ -109,8 +108,8 @@ export interface ToolInputSchema { * One parameter of a tool, in its schema's order: one of its own (filling the * subcommand slot or a positional, or `full`), or one of its command's flags * placed there. A flag shows as its definition's `agent` says, unless the tool - * gives `schema`: how this tool showed it before 2E, kept so tools/list reads - * the same. + * gives `schema`: how this tool showed it before schemas were generated, + * kept so tools/list reads the same. */ export type ToolParam = | { readonly name: string; readonly schema: ParamSchema } @@ -200,7 +199,7 @@ export interface CommandDefinition { readonly mcp?: { readonly tools: readonly ToolDefinition[] }; } -/** A package as the shell installs it: its commands and what it tells agents (spec §6.1, D19). */ +/** A package as the shell installs it: its commands and what it tells agents. */ export interface CommandPackage { readonly name: string; readonly commands: readonly CommandDefinition[]; @@ -468,11 +467,11 @@ export function createPackageRegistry( } /** - * Superseded by the registry (2E: a tool's schema lists every parameter it - * takes, and is the one check); removal waits for Y13. + * Superseded by the registry (a tool's schema lists every parameter it takes, + * and is the one check); kept until its last callers go. * * The flags a call of the tool could set besides its schema's parameters - * under 2C's interim rule: when its argv passes every other parameter on as a + * under the old pass-through rule: when its argv passes every other parameter on as a * flag (`flags: 'rest'`), the flags its command accepts and the global ones; * otherwise none. Empty for a tool no command defines (the server's own * confirm tool). diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index f8b4bde9..38d4fcfb 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -1,4 +1,4 @@ -// The CLI's dispatch, from the command registry (plan 2C): which command runs, +// The CLI's dispatch, from the command registry: which command runs, // what the shell gives its handler, and whether it needs the wallet SDK. The // shell (src/wallet.ts) owns the process: it passes in what a handler may be // given and where a notice goes, and decides the heap and the exit. diff --git a/src/lib/command-flags.ts b/src/lib/command-flags.ts index 484a616d..c49c8810 100644 --- a/src/lib/command-flags.ts +++ b/src/lib/command-flags.ts @@ -1,8 +1,8 @@ // The unknown-flag refusal. The CLI rejects any flag a command doesn't accept // before the command runs: an unrecognised flag used to be silently ignored, so // a typo or a malformed argument fell back to defaults (for endpoints, a -// different chain). The accepted flags come from the command registry (plan -// 2C): each command's definition, and the registry's global flags. +// different chain). The accepted flags come from the command registry: +// each command's definition, and the registry's global flags. import { type ParsedArgs } from './argv.ts'; import type { CommandRegistry } from './command-definition.ts'; diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 37d6f251..d1dc10bd 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -31,7 +31,7 @@ export function isUsageError(err: unknown): err is UsageError { /** What a cancelled operation fails with; exit-codes' classifyError reads it as CANCELLED. */ export const CANCELLED_MESSAGE = 'Operation cancelled'; -/** A cancelled call (2F): the cancellation error, typed with its code. */ +/** A cancelled call: the cancellation error, typed with its code. */ export class CancelledError extends Error { readonly code = 'CANCELLED'; diff --git a/src/lib/grant/account-protector.ts b/src/lib/grant/account-protector.ts index d753a7d0..f879b024 100644 --- a/src/lib/grant/account-protector.ts +++ b/src/lib/grant/account-protector.ts @@ -1,4 +1,4 @@ -// Grant's protector for `wallet protect` (decision 24): seals every +// Grant's protector for `wallet protect`: seals every // plain-text account an earlier mn made, under the same passphrase as the // wallets. The caller passes it to the wallet command. The sealing code (and // the account chain it loads) is loaded only when the protector runs. diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index a38fc5a6..6b8564d2 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -1,9 +1,9 @@ // The packages this mn has, with their commands and agent guidance, collected -// into one registry (plan 2B, 2G). The shell assembles it: a definition and a -// package's guidance sit beside its commands, and the base can't import a -// package's commands. Reading it loads no handler, so no SDK. The shell's -// dispatch and flag checks read it (2C), and so do help, the manual and the -// intro (2D), the MCP server's tools (2E), and the agent manual and skills (2G). +// into one registry. The shell assembles it: a definition and a package's +// guidance sit beside its commands, and the base can't import a package's +// commands. Reading it loads no handler, so no SDK. The shell's dispatch and +// flag checks read it, and so do help, the manual and the intro, the MCP +// server's tools, and the agent manual and skills. import { createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from './command-definition.ts'; import { walletDefinition } from '../commands/wallet.definition.ts'; diff --git a/src/lib/json-output.ts b/src/lib/json-output.ts index 9f4f7094..bf1a05bf 100644 --- a/src/lib/json-output.ts +++ b/src/lib/json-output.ts @@ -14,7 +14,7 @@ import { type ErrorCode } from './exit-codes.ts'; /** * Write a structured JSON result to stdout: the CLI's way to write a call's - * result (its context's output, 2F). Always outputs a single line of JSON + * result (its context's output). Always outputs a single line of JSON * followed by a newline. The MCP server keeps each call's result in that * call's context instead, so nothing here is shared between calls. */ diff --git a/src/lib/localnet.ts b/src/lib/localnet.ts index 8fc51940..bff2be93 100644 --- a/src/lib/localnet.ts +++ b/src/lib/localnet.ts @@ -1,7 +1,7 @@ // Localnet management — Docker Compose helpers for midnight-local-network // Manages a compose.yml at ~/.midnight/localnet/ and runs docker compose: // asynchronously, as a step of the call that asked, and killed when that call -// is cancelled (2F). +// is cancelled. import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; @@ -292,7 +292,7 @@ export async function startLocalnet(docker: DockerCall, onStatus: (status: strin const CANCELLED_LISTING_TIMEOUT_MS = 10_000; /** - * What a cancelled `localnet up` fails with (decision 4): the containers it + * What a cancelled `localnet up` fails with: the containers it * started stay in place, and the error says which, as Docker lists them now. * Listing them is not cancelled with the call (it has been already); it is * bounded by its own time limit. When Docker can't list them, the error says diff --git a/src/lib/mcp/known-params.ts b/src/lib/mcp/known-params.ts index 394fb1f4..4e751fe6 100644 --- a/src/lib/mcp/known-params.ts +++ b/src/lib/mcp/known-params.ts @@ -16,11 +16,10 @@ export function findUnknownParams(tool: ToolSchema, params: Record): void { const unknown = findUnknownParams(tool, params); diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index 94229904..3bf88238 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -1,4 +1,4 @@ -// The MCP server's tools, from the command registry (plan 2E): each command's +// The MCP server's tools, from the command registry: each command's // definition gives its tools' names, descriptions, annotations, schemas, argv // mapping and confirmation; the server runs the command's own handler. The // server's one tool of its own, midnight_confirm_operation, redeems the tokens diff --git a/src/lib/mcp/skills.ts b/src/lib/mcp/skills.ts index 90dc3f63..94c43e41 100644 --- a/src/lib/mcp/skills.ts +++ b/src/lib/mcp/skills.ts @@ -1,4 +1,4 @@ -// The two skills the MCP server serves (plan 2G, D19): skill/core (intent +// The two skills the MCP server serves: skill/core (intent // routing and the safety rules) and skill/full (flows, error recovery, concept // primers). Each is the server's skeleton of sections and its own text (the // concepts, networks, safety rules and its own setup), with each installed diff --git a/src/lib/resolve-network.ts b/src/lib/resolve-network.ts index 19c9b4c7..ccf8072e 100644 --- a/src/lib/resolve-network.ts +++ b/src/lib/resolve-network.ts @@ -48,7 +48,7 @@ export function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName { return 'undeployed'; } -// The Blockfrost variables' names are settings.ts's (spec §5.4), re-exported for the callers that name them. +// The Blockfrost variables' names are settings.ts's, re-exported for the callers that name them. export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; /** diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index 5956f334..9d085d81 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -18,13 +18,13 @@ export interface CommandRun { sdkWarnings?: SdkWarningCalls; } -/** The server's stderr: where a call's text for the person goes (decision 3), never the protocol channel on stdout. */ +/** The server's stderr: where a call's text for the person goes, never the protocol channel on stdout. */ const serverStderr = (text: string): void => { process.stderr.write(text); }; /** * Execute a command handler with --json mode, capturing the JSON result. * - * The call gets a context of its own (2F): its result is kept for this call + * The call gets a context of its own: its result is kept for this call * alone, as JSON reads it back, so two calls that overlap never see each * other's result, and none reaches stdout, the MCP stdio channel. Its text for * the person goes to the server's stderr, which clients typically log @@ -40,7 +40,7 @@ const serverStderr = (text: string): void => { process.stderr.write(text); }; * shape instead. * * What the command's spinners say goes to `onProgress` while it runs, and - * nothing once it is over: each call has its own progress (2F), so two calls + * nothing once it is over: each call has its own progress, so two calls * at once never report each other's. * * Returns the result as a JSON object ({} when the command wrote none). diff --git a/src/lib/sdk-noise.ts b/src/lib/sdk-noise.ts index 69c366b1..9272a941 100644 --- a/src/lib/sdk-noise.ts +++ b/src/lib/sdk-noise.ts @@ -12,7 +12,7 @@ // RPC-CORE lines on console.warn and console.error (one per failed // submit), are kept off the terminal. // -// Which call a warning belongs to (2F, S5): each call runs inside its own +// Which call a warning belongs to: each call runs inside its own // AsyncLocalStorage store, the one ambient per-call storage the process-safety // check allows, so a warning raised while it runs carries its identity, and // the host's router hands it to that call alone (lib/sdk-warnings.ts). diff --git a/src/lib/sdk-warnings.ts b/src/lib/sdk-warnings.ts index eb20be02..721030da 100644 --- a/src/lib/sdk-warnings.ts +++ b/src/lib/sdk-warnings.ts @@ -5,7 +5,7 @@ // progress ("…, retrying") or only to keep them off the terminal; it never // touches the process itself. // -// Each call's warnings are its own (2F, S5). The host keeps one router; each +// Each call's warnings are its own. The host keeps one router; each // call it runs is opened on it, and the shell tags the noise raised while a // call runs with that call's identity. A warning with an identity goes to // that call's newest listener, and to no other call. One without (raised diff --git a/src/lib/settings.ts b/src/lib/settings.ts index 7727b3bc..292658ee 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -1,10 +1,10 @@ // What the environment says, as settings libraries read. The environment -// variables are the shell's public contract (spec §5.4): the shell gives the +// variables are the shell's public contract: the shell gives the // libraries a source of settings, read from them as each is needed, and a // consumer gives its own. A library never reads the environment itself; with // no source, every setting is unset. -/** The environment variables of spec §5.4 that become settings: their names, in one place. */ +/** The environment variables that become settings: their names, in one place. */ export const PASSPHRASE_ENV = 'MN_PASSPHRASE'; export const SEED_ENV = 'MN_SEED'; export const NO_LOCAL_DETECT_ENV = 'MN_NO_LOCAL_DETECT'; @@ -33,7 +33,7 @@ export interface Settings { sharedBlockfrostProjectId: string | undefined; } -/** The settings the variables of §5.4 in `env` give. */ +/** The settings the environment variables in `env` give. */ export function settingsFromEnvironment(env: Record): Settings { return { passphrase: env[PASSPHRASE_ENV], diff --git a/src/lib/state-root.ts b/src/lib/state-root.ts index 9dc74369..d4a8c102 100644 --- a/src/lib/state-root.ts +++ b/src/lib/state-root.ts @@ -1,5 +1,5 @@ // Where mn keeps its state, as the host says: the shell's is ~/.midnight, a -// consumer's is its own (spec §7). Each owner builds its paths under this +// consumer's is its own. Each owner builds its paths under this // root; no library computes a path from the home directory itself. The source // is read as each path is built, so a host that changes HOME mid-run (the test // run does) is followed. With no source, a library refuses instead of guessing. diff --git a/src/lib/verbose.ts b/src/lib/verbose.ts index c3b8adba..1b599220 100644 --- a/src/lib/verbose.ts +++ b/src/lib/verbose.ts @@ -1,6 +1,6 @@ // Verbose diagnostics: the timestamped line a call shows when it runs with // --verbose / -v. Whether a call is verbose, and where its lines go, is the -// call's own (its context's diagnostics, 2F): a library that has diagnostics +// call's own (its context's diagnostics): a library that has diagnostics // to give is handed the call's `line` as a VerboseLog, never a switch. import { dim } from '../ui/colors.ts'; diff --git a/src/lib/wallet-cache.ts b/src/lib/wallet-cache.ts index 90f80ba4..df51342c 100644 --- a/src/lib/wallet-cache.ts +++ b/src/lib/wallet-cache.ts @@ -22,7 +22,7 @@ interface CacheFile { * Genesis block hash of the chain this cache was built against. * Used to detect remote-testnet resets: a mismatch means the cache * refers to a now-defunct chain and must be wiped. Optional for - * back-compat with pre-S1 cache files. + * back-compat with cache files written before it existed. */ chainId?: string; timestamp: string; @@ -172,7 +172,7 @@ export function validateWalletCacheChainId( const path = join(dir, file); try { const parsed: CacheFile = JSON.parse(readFileSync(path, 'utf-8')); - // Legacy caches (pre-S1) have no chainId — leave alone for back-compat; + // Legacy caches have no chainId — leave alone for back-compat; // the next save writes the field. if (!parsed.chainId) continue; if (parsed.chainId !== currentChainId) { diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 90c6582f..f3639d48 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -1,5 +1,5 @@ // Midnight Wallet CLI — MCP Server -// Exposes all CLI commands as MCP tools via stdio transport +// Exposes the installed commands' MCP tools via stdio transport // Launch: midnight-wallet-mcp (or: node dist/mcp-server.js) import { Server } from '@modelcontextprotocol/sdk/server/index.js'; @@ -36,7 +36,7 @@ import { skillCore, skillFull } from './lib/mcp/skills.ts'; // Fetch on demand (errors, multi-step flows, concept questions). // The original `midnight-wallet://skill` URI stays as a deprecated alias for // /full so existing MCP clients keep working. Both are assembled from the -// installed packages' guidance at each read (2G). +// installed packages' guidance at each read. const SKILL_CORE_URI = 'midnight-wallet://skill/core'; const SKILL_FULL_URI = 'midnight-wallet://skill/full'; const SKILL_LEGACY_URI = 'midnight-wallet://skill'; @@ -97,7 +97,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { const call = toolCall(request.params._meta?.progressToken, extra); // A parameter outside the tool's schema is refused before anything runs or - // a token is given (Y29, 2E). An unknown tool is reported by executeTool. + // a token is given. An unknown tool is reported by executeTool. const tool = findTool(installedCommands, name); const schema = name === CONFIRM_TOOL.name ? CONFIRM_TOOL : tool; if (schema !== undefined) { diff --git a/src/ui/spinner.ts b/src/ui/spinner.ts index c0b4131b..88c2ddda 100644 --- a/src/ui/spinner.ts +++ b/src/ui/spinner.ts @@ -19,7 +19,7 @@ export interface Spinner { /** * Where what a call's spinners say goes besides the terminal: for a call the - * MCP server runs, its progress notifications. Each call has its own (2F); a + * MCP server runs, its progress notifications. Each call has its own; a * spinner made without one reports nowhere. */ export type ProgressReport = (message: string) => void; diff --git a/src/wallet.ts b/src/wallet.ts index f7002ee1..d7f26c16 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -55,7 +55,6 @@ const command = args.command ?? 'help'; const needsWalletSdk = commandNeedsWalletSdk(installedCommands, command); if (needsWalletSdk) await ensureHeapForSync(); -// Auto-migrate old ~/.midnight/wallet.json → wallets/default.json (silent, one-time) // Endpoint URLs can carry a Blockfrost project id: nothing mn or its libraries print shows it. hideProjectIdsInOutput(); @@ -66,6 +65,7 @@ const host = installCliHost(); // Libraries ask their questions (passphrase, approvals) at the terminal. setPrompter(createTerminalPrompter()); +// Auto-migrate old ~/.midnight/wallet.json → wallets/default.json (silent, one-time) migrateOldWallet(); // Global AbortController for clean shutdown on SIGINT/SIGTERM @@ -93,7 +93,7 @@ async function run(): Promise { output: processOutput, sdkWarnings: host.sdkWarnings, loadPayer: async () => (await import('./lib/serve-payer.ts')).servePayer, - // wallet protect also seals grant's accounts, through the protector grant provides (D24). + // wallet protect also seals grant's accounts, through the protector grant provides. loadProtectors: async () => [(await import('./lib/grant/account-protector.ts')).accountProtector], }); } From 92163c2dbb25fc1e9cff9e1d8b69d87b8b540257 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:52:25 -0800 Subject: [PATCH 07/88] Tests: every tool that acts needs its token, and does nothing before Only two of the nine confirmed tools were run through the real server, and the registry test checked a type, so dropping a confirmation from transfer, contract or grant left the suite green. Each confirmed tool now answers its first call with a token and its exact description, leaving the home as it was, and the registry pins the set of confirmed tools. --- src/__tests__/command-registry.test.ts | 9 +++ src/__tests__/mcp-server-confirmation.test.ts | 69 +++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 9fd588cd..e75fedc0 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -282,6 +282,15 @@ describe('the MCP tools, generated from the registry', () => { for (const tool of registry.tools.filter((t) => t.confirmation !== undefined)) expect(tool.confirmation!.check, tool.name).toBeTypeOf('function'); }); + it('asks for confirmation on exactly the tools that move funds, change an account or delete a seed', () => { + // Taking a tool off this list lets an agent run it without the user's confirmation. + expect(registry.tools.filter((t) => t.confirmation !== undefined).map((t) => t.name).sort()).toStrictEqual([ + 'midnight_contract_call', 'midnight_contract_deploy', + 'midnight_grant_deploy', 'midnight_grant_deposit', 'midnight_grant_issue', 'midnight_grant_revoke', 'midnight_grant_revoke_all', + 'midnight_transfer', 'midnight_wallet_remove', + ]); + }); + it('describes removing a wallet as deleting its file and seed', () => { const remove = registry.tools.find((t) => t.name === NEWLY_CONFIRMED)!; expect(confirmationText(remove, { name: 'bob' })).toBe('Remove wallet bob: its file, and the seed in it, is deleted from this machine'); diff --git a/src/__tests__/mcp-server-confirmation.test.ts b/src/__tests__/mcp-server-confirmation.test.ts index c772c223..32bc8c36 100644 --- a/src/__tests__/mcp-server-confirmation.test.ts +++ b/src/__tests__/mcp-server-confirmation.test.ts @@ -11,6 +11,7 @@ import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { freshGrantee, grantRequestFor, grantRequestLink } from '@kuiralabs/midnight-account-chain/agent'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); const TSX = path.join(REPO, 'node_modules', '.bin', 'tsx'); @@ -22,6 +23,7 @@ const OWNER_RECORD = { contractAddress: ACCOUNT, deviceArm: 'k1', deviceSk: '4f' let home: string; let recordsDir: string; +let dappDir: string; let client: Client; beforeAll(async () => { @@ -29,11 +31,21 @@ beforeAll(async () => { const env = { ...process.env, HOME: home, NO_COLOR: '1', MN_PASSPHRASE: 'correct horse battery staple' } as Record; execFileSync(TSX, [path.join(REPO, 'src', 'wallet.ts'), 'wallet', 'generate', 'alice', '--json'], { env, stdio: 'ignore' }); execFileSync(TSX, [path.join(REPO, 'src', 'wallet.ts'), 'wallet', 'generate', 'bob', '--json'], { env, stdio: 'ignore' }); + execFileSync(TSX, [path.join(REPO, 'src', 'wallet.ts'), 'wallet', 'generate', 'carol', '--json'], { env, stdio: 'ignore' }); execFileSync(TSX, [path.join(REPO, 'src', 'wallet.ts'), 'wallet', 'use', 'alice'], { env, stdio: 'ignore' }); // An account on record for alice. recordsDir = path.join(home, '.midnight', 'accounts', 'undeployed', 'alice'); fs.mkdirSync(recordsDir, { recursive: true, mode: 0o700 }); fs.writeFileSync(path.join(recordsDir, 'owner.json'), JSON.stringify(OWNER_RECORD), { mode: 0o600 }); + // A compiled contract, as compactc leaves it. + dappDir = path.join(home, 'dapp'); + const compiler = path.join(dappDir, 'managed', 'counter', 'compiler'); + fs.mkdirSync(compiler, { recursive: true }); + fs.writeFileSync(path.join(compiler, 'contract-info.json'), JSON.stringify({ + 'compiler-version': '0.35.0', 'language-version': '0.27.0', 'runtime-version': '0.20.0', + circuits: [{ name: 'increment', pure: false, proof: true, arguments: [], 'result-type': { 'type-name': 'Tuple', types: [] } }], + witnesses: [], + })); client = new Client({ name: 'mn-test', version: '0' }); await client.connect(new StdioClientTransport({ command: TSX, args: [path.join(REPO, 'src', 'mcp-server.ts')], env, stderr: 'ignore' })); @@ -49,6 +61,63 @@ const call = async (name: string, args: Record) => { return JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record; }; +/** Every file under the home, with its contents: what a call that does nothing leaves as it was. */ +function homeState(): Record { + const state: Record = {}; + const walk = (dir: string): void => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walk(full); + else state[path.relative(home, full)] = fs.readFileSync(full, 'base64'); + } + }; + walk(home); + return state; +} + +const ARTEFACT_CACHE_COMPILER_FILE = /^\.midnight\/account-artifacts\/[0-9a-f]{16}\/compiler\/[^/]+$/; +const withoutArtefactCache = (state: Record): Record => + Object.fromEntries(Object.entries(state).filter(([file]) => !ARTEFACT_CACHE_COMPILER_FILE.test(file))); + +describe('every tool that acts answers with a token, and does nothing until it is confirmed', () => { + const ADDRESS = 'ab'.repeat(32); + // A grant request as an agent sends it, for alice's account. + const link = (): string => grantRequestLink(grantRequestFor( + { account: ACCOUNT, clientId: 'rdns:org.example.agent', grantee: freshGrantee('k1'), readSecret: new Uint8Array(32).fill(7) }, + 3, new Uint8Array(32).fill(0x9a), 2, + )); + const cases: Array<[string, () => Record, () => string | RegExp]> = [ + ['midnight_transfer', () => ({ to: 'carol', amount: '5', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => 'Send 5 NIGHT from alice to carol on undeployed'], + ['midnight_contract_deploy', () => ({ path: dappDir, wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Deploy contract from ${dappDir} as alice on undeployed`], + ['midnight_contract_call', () => ({ path: dappDir, address: ADDRESS, circuit: 'increment', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Call circuit increment on contract ${ADDRESS} as alice on undeployed`], + ['midnight_grant_deploy', () => ({ wallet: 'carol', network: 'undeployed', ...ENDPOINTS }), () => "Deploy an account for carol on undeployed; its owner key is made on this machine and kept encrypted under mn's passphrase"], + ['midnight_grant_deposit', () => ({ amount: '2', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Deposit 2 shielded NIGHT (2000000 in the smallest unit) from wallet alice into its account ${ACCOUNT} on undeployed`], + ['midnight_grant_issue', () => ({ link: link(), wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => new RegExp(`^Issue a grant on alice's account on undeployed, letting an agent spend from it within these terms .*${ACCOUNT}`)], + ['midnight_grant_revoke', () => ({ grant: '3', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => "Revoke grant 3 on alice's account on undeployed"], + ['midnight_grant_revoke_all', () => ({ wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => "Revoke every grant on alice's account on undeployed"], + ['midnight_wallet_remove', () => ({ name: 'carol' }), () => 'Remove wallet carol: its file, and the seed in it, is deleted from this machine'], + ]; + + it.each(cases)('%s', async (tool, params, description) => { + const before = withoutArtefactCache(homeState()); + const pending = await call(tool, params()); + + expect(pending.error, String(pending.message)).toBeUndefined(); + expect(pending.pending).toBe(true); + expect(pending.tool).toBe(tool); + expect(pending.token).toEqual(expect.any(String)); + const expected = description(); + if (typeof expected === 'string') expect(pending.description).toBe(expected); + else expect(pending.description).toMatch(expected); + // The one thing a check may leave: the account's artefact cache, set up when an + // issue's preview opens the account, holding a copy of the installed contract's + // compiler files (no network, no keys). + const after = withoutArtefactCache(homeState()); + expect(Object.keys(after).filter((file) => !(file in before)), 'files the call wrote').toEqual([]); + expect(after).toStrictEqual(before); + }, 60_000); +}); + describe('midnight_grant_deposit', () => { it('answers with a token whose description names the amount in both units and the account, and deposits nothing', async () => { const pending = await call('midnight_grant_deposit', { amount: '1.5', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }); From 54b1479ab2f650a5088b0754f2ce0d3f5f91f970 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:53:17 -0800 Subject: [PATCH 08/88] Tests: the unknown-flag refusal through the real shell The refusal was tested as a function only. These run the CLI's entry point: an unknown flag is exit 2 with INVALID_ARGS before the command runs, known flags reach the command, and --help skips the refusal. --- src/__tests__/shell-unknown-flag.test.ts | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/__tests__/shell-unknown-flag.test.ts diff --git a/src/__tests__/shell-unknown-flag.test.ts b/src/__tests__/shell-unknown-flag.test.ts new file mode 100644 index 00000000..a8192fd9 --- /dev/null +++ b/src/__tests__/shell-unknown-flag.test.ts @@ -0,0 +1,57 @@ +// The shell refuses a flag the command doesn't accept before the command runs, +// and shows help instead when help is asked for. Run as the CLI is: this +// checkout's entry point in its own process, with a temporary home that holds +// no wallet, so a command that ran would fail with WALLET_NOT_FOUND (exit 3). + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, realpathSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const entryPoint = resolve(import.meta.dirname, '../wallet.ts'); +const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href; + +let home: string; + +beforeAll(() => { home = realpathSync(mkdtempSync(join(tmpdir(), 'mn-unknown-flag-'))); }); +afterAll(() => { rmSync(home, { recursive: true, force: true }); }); + +function mn(...args: string[]) { + const run = spawnSync(process.execPath, ['--import', tsxLoader, entryPoint, ...args], { + env: { ...process.env, HOME: home, NO_COLOR: '1' }, + encoding: 'utf8', + timeout: 30_000, + }); + return { status: run.status, stdout: run.stdout, stderr: run.stderr }; +} + +describe('the unknown-flag refusal, through the shell', () => { + it('refuses an unknown flag with exit 2 and INVALID_ARGS, before the command runs', () => { + const run = mn('info', '--bogus', '--json'); + expect(run.status).toBe(2); + expect(JSON.parse(run.stdout)).toMatchObject({ error: true, code: 'INVALID_ARGS', message: expect.stringContaining('--bogus') }); + }); + + it('names every unknown flag at a terminal, with exit 2', () => { + const run = mn('info', '--bogus', '--other', 'x'); + expect(run.status).toBe(2); + expect(run.stderr).toContain('Unknown flags for "midnight info": --bogus, --other'); + }); + + it('runs the command when its flags are known: here it finds no wallet', () => { + const run = mn('info', '--network', 'undeployed', '--json'); + expect(run.status).toBe(3); + expect(JSON.parse(run.stdout)).toMatchObject({ error: true, code: 'WALLET_NOT_FOUND' }); + }); + + it('shows help instead when help is asked for, whatever else is on the line', () => { + // Today that is the general help, not the command's own. + const run = mn('info', '--bogus', '--help'); + expect(run.status).toBe(0); + expect(run.stdout + run.stderr).toContain('Commands:'); + expect(run.stdout + run.stderr).not.toContain('Unknown flag'); + }); +}); From 5d7adafcc958087629ad879136399e876bb62b24 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 15:54:49 -0800 Subject: [PATCH 09/88] MCP runner: a call's SDK warnings are required, not a private fallback captureCommand fell back to a router of its own when no SDK warnings were passed, so a host that stopped passing its own would lose every SDK warning of its calls with nothing failing. The warnings are now a required part of the run; tests that run a command outside a host pass a router of its own explicitly. --- src/__tests__/helpers/own-call.ts | 9 ++++ src/__tests__/localnet-cancellation.test.ts | 3 +- src/__tests__/mcp-registry-tools.test.ts | 9 ++-- src/__tests__/run-command.test.ts | 53 +++++++++++---------- src/__tests__/verbose-per-call.test.ts | 9 ++-- src/lib/run-command.ts | 12 +++-- 6 files changed, 56 insertions(+), 39 deletions(-) create mode 100644 src/__tests__/helpers/own-call.ts diff --git a/src/__tests__/helpers/own-call.ts b/src/__tests__/helpers/own-call.ts new file mode 100644 index 00000000..7d8abdbb --- /dev/null +++ b/src/__tests__/helpers/own-call.ts @@ -0,0 +1,9 @@ +// A command run with SDK warnings of its own, for tests that run one command +// outside any host: no host's filters report to it. + +import type { CommandRun } from '../../lib/run-command.ts'; +import { createSdkWarningRouter, sdkWarningCallsOn } from '../../lib/sdk-warnings.ts'; + +export function ownCall(run: Omit = {}): CommandRun { + return { ...run, sdkWarnings: sdkWarningCallsOn(createSdkWarningRouter()) }; +} diff --git a/src/__tests__/localnet-cancellation.test.ts b/src/__tests__/localnet-cancellation.test.ts index 9c1b9dbf..93079f36 100644 --- a/src/__tests__/localnet-cancellation.test.ts +++ b/src/__tests__/localnet-cancellation.test.ts @@ -18,6 +18,7 @@ import type { ExecRun, ExecRunner } from '../lib/exec-program.ts'; import { captureCommand } from '../lib/run-command.ts'; import { parseArgs } from '../lib/argv.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { ownCall } from './helpers/own-call.ts'; /** One run the stand-in was given. */ interface Run { @@ -79,7 +80,7 @@ afterEach(() => { /** Runs `mn localnet --json` as the MCP server does, with the stand-in runner and the call's signal. */ function localnet(subcommand: string, exec: ExecRunner, signal: AbortSignal): Promise> { - return captureCommand((args, ctx) => runLocalnet(args, ctx, exec), parseArgs(['localnet', subcommand, '--json']), { signal }); + return captureCommand((args, ctx) => runLocalnet(args, ctx, exec), parseArgs(['localnet', subcommand, '--json']), ownCall({ signal })); } describe('localnet commands, cancelled while Docker runs', () => { diff --git a/src/__tests__/mcp-registry-tools.test.ts b/src/__tests__/mcp-registry-tools.test.ts index c2d95b27..fcd03a35 100644 --- a/src/__tests__/mcp-registry-tools.test.ts +++ b/src/__tests__/mcp-registry-tools.test.ts @@ -7,6 +7,7 @@ import { createCommandRegistry, type CommandDefinition, type ToolDefinition } fr import { CONFIRM_TOOL, confirmationFor, findTool, listedTools, runTool } from '../lib/mcp/registry-tools.ts'; import type { CallContext } from '../lib/call-context.ts'; import { MINIMAL_FLAG, type ParsedArgs } from '../lib/argv.ts'; +import { ownCall } from './helpers/own-call.ts'; const received: ParsedArgs[] = []; const command = (tools: ToolDefinition[]): CommandDefinition => ({ @@ -59,20 +60,20 @@ describe('the MCP server\'s tools from a registry', () => { it('runs a tool\'s command with the argv its parameters map to, in agent mode, and returns its result', async () => { received.length = 0; - const result = await runTool(findTool(registry, 'thing_make')!, { label: 'cup', size: '3' }, {}); + const result = await runTool(findTool(registry, 'thing_make')!, { label: 'cup', size: '3' }, ownCall()); expect(result).toStrictEqual({ subcommand: 'make', size: '3', go: true }); expect(received).toStrictEqual([{ command: 'thing', subcommand: 'make', positionals: ['cup'], flags: { json: true, size: '3', go: true, [MINIMAL_FLAG]: true } }]); }); it('confirms the text a check finds, after running what the check asks, and lets a check refuse', async () => { received.length = 0; - expect(await confirmationFor(findTool(registry, 'thing_make')!, { label: 'cup', size: '3' }, {})).toBe('Make cup at size 3'); + expect(await confirmationFor(findTool(registry, 'thing_make')!, { label: 'cup', size: '3' }, ownCall())).toBe('Make cup at size 3'); // The check ran the command once, without the flag the tool fixes. expect(received.map((args) => [args.subcommand, args.flags.go])).toStrictEqual([['show', undefined]]); - await expect(confirmationFor(findTool(registry, 'thing_make')!, { label: 'bad' }, {})).rejects.toThrow('not that one'); + await expect(confirmationFor(findTool(registry, 'thing_make')!, { label: 'bad' }, ownCall())).rejects.toThrow('not that one'); }); it('confirms the definition\'s text when there is no check', async () => { - expect(await confirmationFor(findTool(registry, 'thing_plain')!, {}, {})).toBe('Plain thing'); + expect(await confirmationFor(findTool(registry, 'thing_plain')!, {}, ownCall())).toBe('Plain thing'); }); }); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index 1e5842f3..cca7a34b 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -18,6 +18,7 @@ import inspectCostCommand from '../commands/inspect-cost.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveAllAddresses } from '../lib/derive-address.ts'; import { localIndexerFlags } from './helpers/local-indexer.ts'; +import { ownCall } from './helpers/own-call.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-run-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; @@ -53,20 +54,20 @@ afterEach(() => { describe('captureCommand', () => { it('fails a command that returns a non-zero exit code, with the result it wrote, and passes one that returns 0', async () => { const failing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'fail' }); return { exitCode: 1 }; }; - const err = await captureCommand(failing, parseArgs(['test', 'run'])).catch((e: unknown) => e); + const err = await captureCommand(failing, parseArgs(['test', 'run']), ownCall()).catch((e: unknown) => e); expect(err).toBeInstanceOf(CommandFailedError); expect((err as CommandFailedError).exitCode).toBe(1); expect((err as CommandFailedError).result).toStrictEqual({ overall: 'fail' }); expect(classifyError(err as Error).exitCode).toBe(1); const passing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'pass' }); return { exitCode: 0 }; }; - expect(await captureCommand(passing, parseArgs(['test', 'run']))).toStrictEqual({ overall: 'pass' }); + expect(await captureCommand(passing, parseArgs(['test', 'run']), ownCall())).toStrictEqual({ overall: 'pass' }); }); it('captures JSON output from generate command', async () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const args = parseArgs(['generate', '--network', 'undeployed', '--output', walletFile]); - const result = await captureCommand(generateCommand, args); + const result = await captureCommand(generateCommand, args, ownCall()); expect(result.addresses).toBeDefined(); const addrs = result.addresses as Record; @@ -80,7 +81,7 @@ describe('captureCommand', () => { saveWalletConfig(TEST_CONFIG, walletFile); const args = parseArgs(['info', '--wallet', walletFile, '--network', 'undeployed']); - const result = await captureCommand(infoCommand, args); + const result = await captureCommand(infoCommand, args, ownCall()); expect(result.addresses).toBeDefined(); expect(result.activeNetwork).toBe('undeployed'); @@ -90,7 +91,7 @@ describe('captureCommand', () => { it('captures JSON output from address command', async () => { const args = parseArgs(['address', '--seed', TEST_SEED, '--network', 'undeployed']); - const result = await captureCommand(addressCommand, args); + const result = await captureCommand(addressCommand, args, ownCall()); expect((result.address as string).startsWith('mn_addr_undeployed1')).toBe(true); expect(result.network).toBe('undeployed'); @@ -99,7 +100,7 @@ describe('captureCommand', () => { it('captures JSON output from genesis-address command', async () => { const args = parseArgs(['genesis-address', '--network', 'undeployed']); - const result = await captureCommand(genesisAddressCommand, args); + const result = await captureCommand(genesisAddressCommand, args, ownCall()); expect((result.address as string).startsWith('mn_addr_undeployed1')).toBe(true); expect(result.network).toBe('undeployed'); @@ -108,7 +109,7 @@ describe('captureCommand', () => { it('captures JSON output from inspect-cost command', async () => { const local = await localIndexerFlags(); const args = parseArgs(['inspect-cost', ...local.flags]); - const result = await captureCommand(inspectCostCommand, args).finally(local.close); + const result = await captureCommand(inspectCostCommand, args, ownCall()).finally(local.close); expect(result.readTime).toBeDefined(); expect(result.computeTime).toBeDefined(); @@ -119,7 +120,7 @@ describe('captureCommand', () => { it('does not leak to real stdout or stderr', async () => { const args = parseArgs(['genesis-address', '--network', 'undeployed']); - await captureCommand(genesisAddressCommand, args); + await captureCommand(genesisAddressCommand, args, ownCall()); // captureOutput intercepts real stdout/stderr — if captureCommand leaked, // we'd see output here @@ -129,12 +130,12 @@ describe('captureCommand', () => { it('throws original error when handler fails', async () => { const args = parseArgs(['info', '--wallet', path.join(TEST_DIR, 'nonexistent.json')]); - await expect(captureCommand(infoCommand, args)).rejects.toThrow('Wallet file not found'); + await expect(captureCommand(infoCommand, args, ownCall())).rejects.toThrow('Wallet file not found'); }); it('restores stdout/stderr even when handler throws', async () => { const args = parseArgs(['info', '--wallet', path.join(TEST_DIR, 'nonexistent.json')]); - try { await captureCommand(infoCommand, args); } catch {} + try { await captureCommand(infoCommand, args, ownCall()); } catch {} // Verify stdout/stderr are restored by writing to them io.clearStdout(); @@ -153,13 +154,13 @@ describe('captureCommand', () => { it('injects _minimal: true by default', async () => { const sink: { args?: ParsedArgs } = {}; - await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: {} }); + await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: {} }, ownCall()); expect(sink.args?.flags._minimal).toBe(true); }); it('also sets json: true', async () => { const sink: { args?: ParsedArgs } = {}; - await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: {} }); + await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: {} }, ownCall()); expect(sink.args?.flags.json).toBe(true); }); @@ -167,7 +168,7 @@ describe('captureCommand', () => { const sink: { args?: ParsedArgs } = {}; // Tool handler may want to opt out (e.g. when an agent passes full:true, // it sets _full:true; the wallet-list handler reads both flags). - await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: { _minimal: true, _full: true } }); + await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: { _minimal: true, _full: true } }, ownCall()); expect(sink.args?.flags._minimal).toBe(true); expect(sink.args?.flags._full).toBe(true); }); @@ -186,7 +187,7 @@ describe('captureCommand', () => { shown.update('Syncing transactions... 40%'); shown.log('fetching keys/deposit_shielded.prover (11 MB), once, from github.com'); shown.stop('Synced 3 transactions'); - }, noArgs(), { onProgress: (message) => said.push(message) }); + }, noArgs(), ownCall({ onProgress: (message) => said.push(message) })); expect(said).toEqual([ 'Starting mn serve...', 'mn serve ready (port 9932)', @@ -203,7 +204,7 @@ describe('captureCommand', () => { await expect(captureCommand(async (_args, ctx) => { left = ctx.progress.silent(); throw new Error('refused'); - }, noArgs(), { onProgress: (message) => said.push(message) })).rejects.toThrow('refused'); + }, noArgs(), ownCall({ onProgress: (message) => said.push(message) }))).rejects.toThrow('refused'); left?.update('said after the run'); expect(said).toEqual([]); }); @@ -215,19 +216,19 @@ describe('captureCommand', () => { expect(ctx.progress.active()).toBe(spinner); spinner.stop('Wallet synced'); expect(ctx.progress.active()).toBeNull(); - }, noArgs()); + }, noArgs(), ownCall()); }); it('hands the command the run\'s signal', async () => { const controller = new AbortController(); let seen: AbortSignal | undefined; - await captureCommand(async (_args, ctx) => { seen = ctx.signal; }, noArgs(), { signal: controller.signal }); + await captureCommand(async (_args, ctx) => { seen = ctx.signal; }, noArgs(), ownCall({ signal: controller.signal })); expect(seen).toBe(controller.signal); }); it('hands every command a signal, one never cancelled when the run gives none', async () => { let seen: AbortSignal | undefined; - await captureCommand(async (_args, ctx) => { seen = ctx.signal; }, noArgs()); + await captureCommand(async (_args, ctx) => { seen = ctx.signal; }, noArgs(), ownCall()); expect(seen).toBeInstanceOf(AbortSignal); expect(seen?.aborted).toBe(false); }); @@ -236,7 +237,7 @@ describe('captureCommand', () => { const controller = new AbortController(); controller.abort(); let ran = false; - const err = await captureCommand(async () => { ran = true; }, noArgs(), { signal: controller.signal }).catch((e: unknown) => e); + const err = await captureCommand(async () => { ran = true; }, noArgs(), ownCall({ signal: controller.signal })).catch((e: unknown) => e); expect(err).toBeInstanceOf(CancelledError); expect(classifyError(err as Error).errorCode).toBe('CANCELLED'); expect(ran).toBe(false); @@ -258,8 +259,8 @@ describe('captureCommand', () => { it('each keeps its own result when they finish in the opposite order they started, and none reaches stdout', async () => { const first = gate(); const second = gate(); - const a = captureCommand(async (_args, ctx) => { await first.opened; ctx.output.result({ call: 'a' }); }, noArgs()); - const b = captureCommand(async (_args, ctx) => { await second.opened; ctx.output.result({ call: 'b' }); }, noArgs()); + const a = captureCommand(async (_args, ctx) => { await first.opened; ctx.output.result({ call: 'a' }); }, noArgs(), ownCall()); + const b = captureCommand(async (_args, ctx) => { await second.opened; ctx.output.result({ call: 'b' }); }, noArgs(), ownCall()); second.open(); expect(await b).toEqual({ call: 'b' }); first.open(); @@ -284,13 +285,13 @@ describe('captureCommand', () => { spinner.update('a: while b runs'); activeInA = ctx.progress.active(); spinner.stop('a: done'); - }, noArgs(), { onProgress: (message) => saidA.push(message) }); + }, noArgs(), ownCall({ onProgress: (message) => saidA.push(message) })); const b = captureCommand(async (_args, ctx) => { const spinner = ctx.progress.start('b: started'); first.open(); await second.opened; spinner.stop('b: done'); - }, noArgs(), { onProgress: (message) => saidB.push(message) }); + }, noArgs(), ownCall({ onProgress: (message) => saidB.push(message) })); await new Promise((resolve) => setTimeout(resolve, 10)); second.open(); await Promise.all([a, b]); @@ -305,7 +306,7 @@ describe('captureCommand', () => { const data: Record = { balance: '1' }; ctx.output.result(data); data.balance = '2'; - }, noArgs()); + }, noArgs(), ownCall()); expect(result).toEqual({ balance: '1' }); }); @@ -313,7 +314,7 @@ describe('captureCommand', () => { await expect(captureCommand(async (_args, ctx) => { ctx.output.result({ call: 'first' }); ctx.output.result({ call: 'second' }); - }, noArgs())).rejects.toThrow(SecondResultError); + }, noArgs(), ownCall())).rejects.toThrow(SecondResultError); }); it('sends a command\'s text for the person to the server\'s stderr, never stdout', async () => { @@ -321,7 +322,7 @@ describe('captureCommand', () => { ctx.output.stdout('shown\n'); ctx.output.stderr('chrome\n'); ctx.output.result({ ok: true }); - }, noArgs()); + }, noArgs(), ownCall()); expect(io.stdout()).toBe(''); expect(io.stderr()).toBe('shown\nchrome\n'); }); diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 381c0bb4..2eab2f0a 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -17,6 +17,7 @@ import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; import type { NetworkConfig } from '../lib/network.ts'; import balanceCommand from '../commands/balance.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { ownCall } from './helpers/own-call.ts'; // Nothing listens here: each call fails at its first connection, after its first diagnostic. const UNREACHABLE = ['--indexer-ws', 'ws://127.0.0.1:1/api/v4/graphql/ws', '--node', 'ws://127.0.0.1:1', '--proof-server', 'http://127.0.0.1:1']; @@ -47,8 +48,8 @@ afterEach(() => { describe('verbose, per call', () => { it('two balance calls at once, one --verbose: only the verbose one writes diagnostic lines', async () => { - const verboseCall = captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE])); - const quietCall = captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE])); + const verboseCall = captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall()); + const quietCall = captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall()); const outcomes = await Promise.allSettled([verboseCall, quietCall]); // Neither reaches an indexer; both fail, each with its own error. expect(outcomes.map((o) => o.status)).toEqual(['rejected', 'rejected']); @@ -57,9 +58,9 @@ describe('verbose, per call', () => { }); it('a call after a verbose one is quiet', async () => { - await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE])).catch(() => {}); + await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall()).catch(() => {}); notices = []; - await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE])).catch(() => {}); + await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall()).catch(() => {}); expect(notices.filter((line) => /\] \w+: /.test(line))).toEqual([]); }); diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index 9d085d81..830effe9 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -4,7 +4,7 @@ import { type ParsedArgs, MINIMAL_FLAG } from './argv.ts'; import type { Payer } from './payer.ts'; import { createCallContext, runHandler, type CommandHandler, type OutputSink } from './call-context.ts'; -import { createSdkWarningRouter, sdkWarningCallsOn, type SdkWarningCalls } from './sdk-warnings.ts'; +import type { SdkWarningCalls } from './sdk-warnings.ts'; import { CommandFailedError } from './errors.ts'; export interface CommandRun { @@ -14,8 +14,12 @@ export interface CommandRun { onProgress?: (message: string) => void; /** What a command that submits a transaction pays with. */ payer?: Payer; - /** The host's calls, which the command runs in, with its own SDK warnings. None: a call of its own, which no host's filters report to. */ - sdkWarnings?: SdkWarningCalls; + /** + * The calls the command runs in, which give it its own SDK warnings: the + * host's, so the host's filters report the SDK's warnings to this call. + * Required, so a host can't leave its calls without them unnoticed. + */ + sdkWarnings: SdkWarningCalls; } /** The server's stderr: where a call's text for the person goes, never the protocol channel on stdout. */ @@ -50,7 +54,7 @@ const serverStderr = (text: string): void => { process.stderr.write(text); }; export async function captureCommand( handler: CommandHandler, args: ParsedArgs, - { signal, onProgress, payer, sdkWarnings = sdkWarningCallsOn(createSdkWarningRouter()) }: CommandRun = {}, + { signal, onProgress, payer, sdkWarnings }: CommandRun, ): Promise> { let result: Record = {}; const output: OutputSink = { From d031a86c89fd26dbf668b0e4d4ec93a420c6823d Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 16:01:23 -0800 Subject: [PATCH 10/88] contract state stops when cancelled; cancellation tested on the network A cancelled contract state fell back to the raw-state query instead of stopping, and that query, which takes no signal, waited for ever on an indexer that never answered. A cancelled call now ends there, and the fallback stops waiting when the call is cancelled. New tests cancel transfer (both kinds), airdrop, dust register and status, contract deploy, call and state, grant deposit and serve while their first network read hangs, and expect CANCELLED well inside the time limits they would otherwise wait out. --- src/__tests__/network-cancellation.test.ts | 122 +++++++++++++++++++++ src/__tests__/sleep.test.ts | 27 +++++ src/commands/contract.ts | 9 +- src/lib/sleep.ts | 18 +++ 4 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 src/__tests__/network-cancellation.test.ts create mode 100644 src/__tests__/sleep.test.ts diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts new file mode 100644 index 00000000..d9ddbc0e --- /dev/null +++ b/src/__tests__/network-cancellation.test.ts @@ -0,0 +1,122 @@ +// The commands that wait on the network stop when their call is cancelled +// while they wait, instead of waiting out their own time limits. Every +// endpoint is a stand-in run by the test that takes each request and never +// answers; the call is cancelled as the first request arrives, and must answer +// CANCELLED well inside the shortest time limit it would otherwise wait out +// (5 s). Nothing here reaches a chain. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { createServer as createTcpServer, type AddressInfo, type Socket } from 'node:net'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { parseArgs } from '../lib/argv.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { establishPassphrase } from '../lib/passphrase.ts'; +import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; +import { servePayerAt } from '../lib/serve-payer.ts'; +import type { CommandHandler } from '../lib/call-context.ts'; +import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { cliCall } from './helpers/cli-call.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const ACCOUNT = '5e'.repeat(32); + +let home: string; +let io: CapturedOutput; +let server: Server; +let sockets: Socket[]; +let onFirstRequest: () => void; +let requests: number; +let freePort: number; +const originalHome = process.env.HOME; +const originalPassphrase = process.env.MN_PASSPHRASE; + +beforeEach(async () => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-network-cancel-'))); + process.env.HOME = home; + process.env.MN_PASSPHRASE = PASSPHRASE; + establishPassphrase(stateRootIn(home), PASSPHRASE); + createWallet('alice', walletSecretFrom(), PASSPHRASE); + createWallet('bob', walletSecretFrom(), PASSPHRASE); + io = captureOutput(); + // Every endpoint: takes HTTP requests and WebSocket upgrades, and answers none. + requests = 0; + sockets = []; + onFirstRequest = () => {}; + const took = (): void => { requests += 1; if (requests === 1) onFirstRequest(); }; + server = createServer(() => took()); + server.on('upgrade', (_req, socket: Socket) => { sockets.push(socket); took(); }); + server.on('connection', (socket) => sockets.push(socket)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + // A port nothing listens on, for serve to take. + const probe = createTcpServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + freePort = (probe.address() as AddressInfo).port; + await new Promise((resolve) => probe.close(() => resolve())); +}); + +afterEach(async () => { + io.restore(); + for (const socket of sockets) socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + process.env.HOME = originalHome; + if (originalPassphrase === undefined) delete process.env.MN_PASSPHRASE; + else process.env.MN_PASSPHRASE = originalPassphrase; + fs.rmSync(home, { recursive: true, force: true }); +}); + +const endpoints = (): string[] => { + const { port } = server.address() as AddressInfo; + return ['--network', 'undeployed', '--node', `ws://127.0.0.1:${port}`, '--indexer-ws', `ws://127.0.0.1:${port}/api/v4/graphql/ws`, '--proof-server', `http://127.0.0.1:${port}`]; +}; + +function dapp(): string { + const dir = path.join(home, 'dapp'); + const compiler = path.join(dir, 'managed', 'counter', 'compiler'); + fs.mkdirSync(compiler, { recursive: true }); + fs.writeFileSync(path.join(compiler, 'contract-info.json'), JSON.stringify({ + 'compiler-version': '0.35.0', 'language-version': '0.27.0', 'runtime-version': '0.20.0', + circuits: [{ name: 'increment', pure: false, proof: true, arguments: [], 'result-type': { 'type-name': 'Tuple', types: [] } }], + witnesses: [], + })); + return dir; +} + +function accountForAlice(): void { + const records = path.join(stateRootIn(home), 'accounts', 'undeployed', 'alice'); + fs.mkdirSync(records, { recursive: true, mode: 0o700 }); + fs.writeFileSync(path.join(records, 'owner.json'), JSON.stringify({ contractAddress: ACCOUNT, deviceArm: 'k1', deviceSk: '4f'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }), { mode: 0o600 }); +} + +const cases: Array<[string, () => string[]]> = [ + ['transfer', () => ['transfer', 'bob', '1', '--wallet', 'alice', '--json']], + ['shielded transfer', () => ['transfer', 'bob', '1', '--shielded', '--wallet', 'alice', '--json']], + ['airdrop', () => ['airdrop', '10', '--wallet', 'alice', '--json']], + ['dust register', () => ['dust', 'register', '--wallet', 'alice', '--json']], + ['dust status', () => ['dust', 'status', '--wallet', 'alice', '--json']], + ['contract deploy', () => ['contract', 'deploy', '--path', dapp(), '--wallet', 'alice', '--json']], + ['contract call', () => ['contract', 'call', '--circuit', 'increment', '--address', 'ab'.repeat(32), '--path', dapp(), '--wallet', 'alice', '--json']], + ['contract state', () => ['contract', 'state', '--address', 'ab'.repeat(32), '--path', dapp(), '--json']], + ['grant deposit', () => { accountForAlice(); return ['grant', 'deposit', '1', '--wallet', 'alice', '--json']; }], + ['serve', () => ['serve', '--wallet', 'alice', '--port', String(freePort), '--json']], +]; + +describe('cancelled while the network has not answered', () => { + it.each(cases)('%s: CANCELLED, well before its own time limit', async (_name, argv) => { + const args = parseArgs([...argv(), ...endpoints()]); + const { default: handler } = await installedCommands.find(args.command!)!.load(); + const call = new AbortController(); + let cancelledAt = 0; + onFirstRequest = () => { cancelledAt = Date.now(); call.abort(); }; + + const outcome = await cliCall(handler as CommandHandler, args, { signal: call.signal, payer: servePayerAt(0) }).then(() => 'finished', (err: unknown) => err); + + expect(requests, `it reached the network: ${String(outcome instanceof Error ? outcome.message : outcome)}`).toBeGreaterThan(0); + expect(outcome).toMatchObject({ code: 'CANCELLED' }); + expect(Date.now() - cancelledAt).toBeLessThan(4_000); + expect(io.stdout()).toBe(''); + }, 30_000); +}); diff --git a/src/__tests__/sleep.test.ts b/src/__tests__/sleep.test.ts new file mode 100644 index 00000000..9db324cf --- /dev/null +++ b/src/__tests__/sleep.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; +import { untilCancelled } from '../lib/sleep.ts'; +import { CancelledError } from '../lib/errors.ts'; + +describe('untilCancelled', () => { + it('gives what the work gives, and its error', async () => { + await expect(untilCancelled(Promise.resolve(7), new AbortController().signal)).resolves.toBe(7); + await expect(untilCancelled(Promise.reject(new Error('no')), new AbortController().signal)).rejects.toThrow('no'); + }); + + it('stops waiting with CancelledError when the signal aborts before the work ends', async () => { + const controller = new AbortController(); + const waiting = untilCancelled(new Promise(() => {}), controller.signal); + controller.abort(); + await expect(waiting).rejects.toBeInstanceOf(CancelledError); + }); + + it('refuses at once when the signal has already aborted', async () => { + const controller = new AbortController(); + controller.abort(); + await expect(untilCancelled(Promise.resolve(1), controller.signal)).rejects.toBeInstanceOf(CancelledError); + }); + + it('waits for the work when there is no signal', async () => { + await expect(untilCancelled(Promise.resolve('done'))).resolves.toBe('done'); + }); +}); diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 7b1d1975..caaf3216 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -2,7 +2,8 @@ import { resolve } from 'node:path'; import { type ParsedArgs, getFlag, hasFlag, requireFlag } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; +import { CancelledError, UsageError, throwIfCancelled } from '../lib/errors.ts'; +import { untilCancelled } from '../lib/sleep.ts'; import type { CallContext, CallOutput } from '../lib/call-context.ts'; import { header, keyValue } from '../ui/format.ts'; import { bold, dim, teal, yellow, green } from '../ui/colors.ts'; @@ -286,12 +287,16 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { ctx.output.stderr('\n'); } } catch (err) { + // A cancelled call stops here; it doesn't fall back to the raw state. + if (err instanceof CancelledError) throw err; + throwIfCancelled(ctx.signal); // If runner fails (no compiled contract in cwd), fall back to raw state spinner.stop(yellow('⚠') + ' Parsed state unavailable, showing raw'); const { buildStateProvider } = await import('../lib/contract/providers.ts'); const publicDataProvider = buildStateProvider(networkConfig); - const contractState = await publicDataProvider.queryContractState(address); + // The provider's query takes no signal: the call stops waiting for it when cancelled. + const contractState = await untilCancelled(publicDataProvider.queryContractState(address), ctx.signal); if (!contractState) { throw new Error(`No contract found at address ${address} on ${network}`); diff --git a/src/lib/sleep.ts b/src/lib/sleep.ts index 3579b39d..4e0ad2d7 100644 --- a/src/lib/sleep.ts +++ b/src/lib/sleep.ts @@ -11,3 +11,21 @@ export function sleep(ms: number, signal?: AbortSignal): Promise { signal?.addEventListener('abort', onAbort, { once: true }); }); } + +/** + * What `work` gives, unless `signal` aborts first (or already has): then + * CancelledError at once. For work that takes no signal of its own; it still + * runs to its end, but nobody waits for it. + */ +export function untilCancelled(work: Promise, signal?: AbortSignal): Promise { + if (signal === undefined) return work; + if (signal.aborted) return Promise.reject(new CancelledError()); + return new Promise((resolve, reject) => { + const onAbort = (): void => reject(new CancelledError()); + signal.addEventListener('abort', onAbort, { once: true }); + work.then( + (value) => { signal.removeEventListener('abort', onAbort); resolve(value); }, + (err: unknown) => { signal.removeEventListener('abort', onAbort); reject(err); }, + ); + }); +} From cd2d4b05ba7de89c3806f2c2ae524db3a3d86b29 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 16:03:02 -0800 Subject: [PATCH 11/88] Tests: what a command writes with --json against what its help names Nothing compared a command's --json fields with the ones its definition declares. For the commands that need no network, every field written must now be one help names. wallet and generate write fields their help predates; those are listed in the test, exactly, until help is corrected, so the drift can't grow unnoticed. --- src/__tests__/json-fields.test.ts | 70 +++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/__tests__/json-fields.test.ts diff --git a/src/__tests__/json-fields.test.ts b/src/__tests__/json-fields.test.ts new file mode 100644 index 00000000..a54009b7 --- /dev/null +++ b/src/__tests__/json-fields.test.ts @@ -0,0 +1,70 @@ +// What a command writes with --json is what its definition says it writes: +// every top-level field of its result is one its help's JSON fields name, so +// `help --json` and the agent manual describe what agents really get. Run for +// the commands that need no network, with a temporary home. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { parseArgs } from '../lib/argv.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { captureCommand } from '../lib/run-command.ts'; +import type { CommandHandler } from '../lib/call-context.ts'; +import { ownCall } from './helpers/own-call.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +let home: string; +const originalHome = process.env.HOME; +const originalPassphrase = process.env.MN_PASSPHRASE; + +beforeAll(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-json-fields-'))); + process.env.HOME = home; + process.env.MN_PASSPHRASE = PASSPHRASE; +}); + +afterAll(() => { + process.env.HOME = originalHome; + if (originalPassphrase === undefined) delete process.env.MN_PASSPHRASE; + else process.env.MN_PASSPHRASE = originalPassphrase; + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** Runs the command as an agent asking for the full shape would, and returns its result. */ +async function run(...argv: string[]): Promise> { + const args = parseArgs([...argv, '--json']); + args.flags._full = true; + const { default: handler } = await installedCommands.find(args.command!)!.load(); + return captureCommand(handler as CommandHandler, args, ownCall()); +} + +// In order: a later run reads what an earlier one wrote. Each run lists the +// fields it writes that its help doesn't name yet: wallet's and generate's help +// predate what they write, and correcting help is a change to what users and +// agents read, waiting on the owner's approval. A field missing from help that +// isn't listed here fails, and so does a listed one once help names it. +const runs: ReadonlyArray = [ + [['wallet', 'generate', 'alice'], ['addresses', 'shieldedAddresses', 'activeAddress', 'activeNetwork', 'seed', 'file', 'createdAt', 'mnemonic']], + [['wallet', 'generate', 'bob'], ['addresses', 'shieldedAddresses', 'activeAddress', 'activeNetwork', 'seed', 'file', 'createdAt', 'mnemonic']], + [['wallet', 'use', 'alice'], ['wallet']], + [['wallet', 'list'], ['activeNetwork']], + [['wallet', 'info', 'bob'], ['addresses', 'activeAddress', 'activeNetwork', 'createdAt', 'file', 'shieldedAddresses']], + [['info'], []], + [['address', '--seed', 'aa'.repeat(32), '--network', 'undeployed'], []], + [['genesis-address', '--network', 'undeployed'], []], + [['config', 'set', 'network', 'preview'], []], + [['config', 'get', 'network'], []], + [['config', 'unset', 'network'], []], + [['cache', 'clear'], []], + [['generate', '--output', 'legacy.json'], ['addresses', 'activeAddress', 'activeNetwork']], +]; + +describe('every field a command writes with --json is one its definition names', () => { + it.each(runs.map(([argv, notYetInHelp]) => [argv.join(' '), argv, notYetInHelp] as const))('%s', async (_name, argv, notYetInHelp) => { + const declared = Object.keys(installedCommands.find(argv[0]!)!.help?.jsonFields ?? {}); + const written = Object.keys(await run(...argv.map((a) => (a === 'legacy.json' ? path.join(home, a) : a)))); + expect(written.length).toBeGreaterThan(0); + expect(written.filter((field) => !declared.includes(field)).sort()).toStrictEqual([...notYetInHelp].sort()); + }); +}); From d3840c49121b1dc979709c419e12561d4e2e44e2 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 16:03:30 -0800 Subject: [PATCH 12/88] Tests: the quiet call after a verbose one is shown to get as far It swallowed both calls' errors, so it passed if the quiet call failed before the point where a verbose call writes its first diagnostic. Both calls' failures are now checked, and the verbose one's diagnostic. --- src/__tests__/verbose-per-call.test.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 2eab2f0a..4261780b 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -58,9 +58,14 @@ describe('verbose, per call', () => { }); it('a call after a verbose one is quiet', async () => { - await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall()).catch(() => {}); + const verbose = await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall()).then(() => null, (err: unknown) => err); + // It got as far as its first diagnostic, and failed connecting. + expect(notices.some((line) => line.includes(`balance: address=${VERBOSE_ADDRESS}`))).toBe(true); notices = []; - await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall()).catch(() => {}); + const quiet = await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall()).then(() => null, (err: unknown) => err); + // It got as far too, failing the same way, past where the verbose one wrote its diagnostic. + expect(quiet).toBeInstanceOf(Error); + expect((quiet as Error).message).toBe((verbose as Error).message.replace(VERBOSE_ADDRESS, QUIET_ADDRESS)); expect(notices.filter((line) => /\] \w+: /.test(line))).toEqual([]); }); From 446b87ad719b86dc2740538fa869c009a7c29e6a Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:46:34 -0800 Subject: [PATCH 13/88] MCP: on/off parameters are booleans, checked; generate with force is confirmed Over MCP, wallet_generate with force replaced a wallet's seed with no confirmation, and force "false" counted as force: any value but false set the flag. airdrop's shielded and dust status's no-cache were strings the same way, so "false" switched them on. - force, shielded and no-cache are booleans in their tools' schemas, and the server refuses a parameter whose value isn't its schema's type (INVALID_ARGS): a boolean must be true or false, a string a string or a number, a listed value one of the list. - A tool's confirmation may say which calls need it (when). Generate asks only with force: true; the text says whether a wallet is replaced. - trueStrings goes: no tool reads a switch as a string any more. - Deleted, approved: toolPassThroughFlags (superseded by the schema), help.ts's unused INDEXER_GRAPHQL_WS_PATH import, and OutputSink, which was CallOutput again. - Guidance tells agents shielded: true. --- docs/SKILL.md | 2 +- src/__tests__/command-registry.test.ts | 37 +++++++++------ src/__tests__/mcp-server-confirmation.test.ts | 40 +++++++++++++++++ .../mcp-server-unknown-parameter.test.ts | 35 +++++++++++++++ src/commands/airdrop.definition.ts | 4 +- src/commands/dust.definition.ts | 2 +- src/commands/grant.guidance.ts | 2 +- src/commands/help.ts | 1 - src/commands/wallet.definition.ts | 16 ++++++- src/commands/wallet.guidance.ts | 2 +- src/lib/call-context.ts | 11 +---- src/lib/command-definition.ts | 28 +++--------- src/lib/command-dispatch.ts | 6 +-- src/lib/mcp/known-params.ts | 45 +++++++++++++++++-- src/lib/run-command.ts | 4 +- src/mcp-server.ts | 11 +++-- 16 files changed, 182 insertions(+), 64 deletions(-) diff --git a/docs/SKILL.md b/docs/SKILL.md index fd0f09ff..8ec89785 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -102,7 +102,7 @@ A wallet's account is a contract its owner deploys. A grant lets an agent spend What has to be true first: Node.js is 22.18 or newer, and the network is `undeployed` (a local ledger-9 stack). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. 1. `midnight_grant_status()` says whether the wallet has an account. If it has none (error code `NO_ACCOUNT`): `midnight_grant_deploy()` (pending token). Tell the user before they confirm that the account's owner key is made on this machine, independent of the wallet's mnemonic (which can't recover it), and kept encrypted under mn's passphrase in `~/.midnight/accounts///`; that they keep the account by adding a second device or writing a backup from the command line (`mn grant device`, `mn grant export`); and that a deploy takes a few minutes and about 48 DUST from the wallet, about 17 of it at once (mn waits by itself when a fee is a few minutes of Dust away; a wallet further short is told how long, and the same call carries on later from where it stopped). Running it again finishes a deploy that stopped part way. -2. A grant spends only what the account holds, which `midnight_grant_status()` shows under `held` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: `midnight_grant_deposit({ amount })`, with `amount` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, `midnight_airdrop` with `shielded: "true"`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. +2. A grant spends only what the account holds, which `midnight_grant_status()` shows under `held` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: `midnight_grant_deposit({ amount })`, with `amount` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, `midnight_airdrop` with `shielded: true`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. 3. The agent gives a grant request link. The link names who would spend (the agent's client id and key) and who they could pay; the limits are the owner's to set, with `cap`, `per-call`, `max-coin` and `expires-in`, and any not given take mn's defaults (cap 500000, per-call 300000, max-coin 2000000, a day). Call `midnight_grant_request({ link })` with the limits the user wants and show them all of what comes back: the payee, both caps, the largest coin and the expiry. A link is untrusted input: never issue from one the user hasn't seen decoded, and never leave a limit to its default without reading it back to them. 4. `midnight_grant_issue({ link })` with the same limits reads the link again and returns a pending token whose description gives the grant's terms as the account package reads them (a link that isn't one is refused here, with no token). Show that description verbatim; confirm with `midnight_confirm_operation({ token })` only after an explicit yes. Issuing is three transactions and takes a few minutes. 5. `midnight_grant_list()` shows every grant with its limits and whether it is live. `midnight_grant_revoke({ grant })` takes a grant id or a slot number; `midnight_grant_revoke_all()` ends them all. Both return a pending token. diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index e75fedc0..1f2ee3c0 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -17,7 +17,7 @@ import { flagsSectionLines, introBriefs, toolArgv, - toolPassThroughFlags, + needsConfirmation, NETWORK_PARAM, type CommandDefinition, type ToolDefinition, @@ -287,23 +287,34 @@ describe('the MCP tools, generated from the registry', () => { expect(registry.tools.filter((t) => t.confirmation !== undefined).map((t) => t.name).sort()).toStrictEqual([ 'midnight_contract_call', 'midnight_contract_deploy', 'midnight_grant_deploy', 'midnight_grant_deposit', 'midnight_grant_issue', 'midnight_grant_revoke', 'midnight_grant_revoke_all', - 'midnight_transfer', 'midnight_wallet_remove', + 'midnight_transfer', 'midnight_wallet_generate', 'midnight_wallet_remove', ]); }); + it('confirms wallet generate only when it may replace a wallet: with force', () => { + const generate = registry.tools.find((t) => t.name === 'midnight_wallet_generate')!; + expect(needsConfirmation(generate, { name: 'alice', force: true })).toBe(true); + expect(needsConfirmation(generate, { name: 'alice', force: false })).toBe(false); + expect(needsConfirmation(generate, { name: 'alice' })).toBe(false); + // Every other confirmed tool confirms every call. + for (const tool of registry.tools.filter((t) => t.confirmation !== undefined && t !== generate)) expect(needsConfirmation(tool, {}), tool.name).toBe(true); + }); + + it('shows every switch flag an agent may pass as a boolean, so "false" can never switch it on', () => { + for (const tool of registry.tools) { + const flags = [...tool.command.flags, ...registry.globalFlags]; + for (const [name, schema] of Object.entries(tool.inputSchema.properties)) { + const flag = flags.find((f) => f.name === name); + if (flag !== undefined && !flag.takesValue) expect(schema.type, `${tool.name} ${name}`).toBe('boolean'); + } + } + }); + it('describes removing a wallet as deleting its file and seed', () => { const remove = registry.tools.find((t) => t.name === NEWLY_CONFIRMED)!; expect(confirmationText(remove, { name: 'bob' })).toBe('Remove wallet bob: its file, and the seed in it, is deleted from this machine'); }); - it('lets a tool pass on its command\'s flags beyond its schema only when its argv passes the rest on (the old pass-through rule, superseded by the schema)', () => { - expect(toolPassThroughFlags(registry, 'midnight_transfer')).toStrictEqual([ - ...registry.find('transfer')!.flags.map((f) => f.name), 'help', 'h', 'json', 'version', 'v', - ]); - expect(toolPassThroughFlags(registry, 'midnight_config_get')).toStrictEqual([]); - expect(toolPassThroughFlags(registry, 'midnight_confirm_operation')).toStrictEqual([]); - }); - it('maps only parameters its schema has onto argv', () => { for (const tool of registry.tools) { const params = Object.keys(tool.inputSchema.properties); @@ -323,7 +334,7 @@ describe('the MCP tools, generated from the registry', () => { const args = (command: string, subcommand: string | undefined, positionals: string[], flags: Record): ParsedArgs => ({ command, subcommand, positionals, flags: { json: true, ...flags } }); const ARGV_BEFORE_REGISTRY: [tool: string, params: Record, argv: ParsedArgs][] = [ - ['midnight_wallet_generate', { name: 'alice', network: 'preprod', seed: 'ab', force: 'true' }, args('wallet', 'generate', ['alice'], { network: 'preprod', seed: 'ab', force: true })], + ['midnight_wallet_generate', { name: 'alice', network: 'preprod', seed: 'ab', force: true }, args('wallet', 'generate', ['alice'], { network: 'preprod', seed: 'ab', force: true })], ['midnight_wallet_generate', { name: 'alice', mnemonic: 'w o r d s', force: true }, args('wallet', 'generate', ['alice'], { mnemonic: 'w o r d s', force: true })], ['midnight_wallet_list', {}, args('wallet', 'list', [], {})], ['midnight_wallet_list', { full: true }, args('wallet', 'list', [], { [FULL_FLAG]: true })], @@ -340,11 +351,11 @@ describe('the MCP tools, generated from the registry', () => { ['midnight_genesis_address', { network: 'undeployed' }, args('genesis-address', undefined, [], { network: 'undeployed' })], ['midnight_inspect_cost', {}, args('inspect-cost', undefined, [], {})], ['midnight_inspect_cost', { network: 'preprod' }, args('inspect-cost', undefined, [], { network: 'preprod' })], - ['midnight_airdrop', { amount: '10', wallet: 'bob', shielded: 'true' }, args('airdrop', '10', [], { wallet: 'bob', shielded: 'true' })], + ['midnight_airdrop', { amount: '10', wallet: 'bob', shielded: true }, args('airdrop', '10', [], { wallet: 'bob', shielded: true })], ['midnight_transfer', { to: 'bob', amount: '1', wallet: 'alice', network: 'undeployed' }, args('transfer', 'bob', ['1'], { wallet: 'alice', network: 'undeployed' })], ['midnight_transfer', { to: 'bob' }, args('transfer', 'bob', [], {})], ['midnight_dust_register', { wallet: 'alice' }, args('dust', 'register', [], { wallet: 'alice' })], - ['midnight_dust_status', { 'no-cache': 'true', node: 'ws://n', full: true }, args('dust', 'status', [], { 'no-cache': 'true', node: 'ws://n', [FULL_FLAG]: true })], + ['midnight_dust_status', { 'no-cache': true, node: 'ws://n', full: true }, args('dust', 'status', [], { 'no-cache': true, node: 'ws://n', [FULL_FLAG]: true })], ['midnight_config_get', { key: 'node', network: 'preview' }, args('config', 'get', ['node'], { network: 'preview' })], ['midnight_config_get', { key: 'network', network: '' }, args('config', 'get', ['network'], {})], ['midnight_config_set', { key: 'node', value: 'ws://n', network: 'preview' }, args('config', 'set', ['node', 'ws://n'], { network: 'preview' })], diff --git a/src/__tests__/mcp-server-confirmation.test.ts b/src/__tests__/mcp-server-confirmation.test.ts index 32bc8c36..dc5d457d 100644 --- a/src/__tests__/mcp-server-confirmation.test.ts +++ b/src/__tests__/mcp-server-confirmation.test.ts @@ -138,6 +138,46 @@ describe('midnight_grant_deposit', () => { }, 60_000); }); +describe('midnight_wallet_generate with force', () => { + const walletFile = (name: string) => path.join(home, '.midnight', 'wallets', `${name}.json`); + + it('answers with a token naming what is deleted, and replaces nothing', async () => { + const before = fs.readFileSync(walletFile('carol'), 'utf8'); + const pending = await call('midnight_wallet_generate', { name: 'carol', force: true }); + + expect(pending.pending).toBe(true); + expect(pending.tool).toBe('midnight_wallet_generate'); + expect(pending.description).toBe('Replace wallet carol: its file, and the seed in it, is deleted from this machine and a new wallet written in its place'); + expect(fs.readFileSync(walletFile('carol'), 'utf8')).toBe(before); + }); + + it('says nothing is replaced when no wallet has the name', async () => { + const pending = await call('midnight_wallet_generate', { name: 'dave', force: true }); + + expect(pending.description).toBe('Create wallet dave (no wallet of that name exists, so nothing is replaced)'); + expect(fs.existsSync(walletFile('dave'))).toBe(false); + }); + + it('replaces the wallet once the token is confirmed', async () => { + const before = JSON.parse(fs.readFileSync(walletFile('carol'), 'utf8')) as { addresses: Record }; + const pending = await call('midnight_wallet_generate', { name: 'carol', force: true }); + const done = await call('midnight_confirm_operation', { token: pending.token }); + + expect(done.error, String(done.message)).toBeUndefined(); + const after = JSON.parse(fs.readFileSync(walletFile('carol'), 'utf8')) as { addresses: Record }; + expect(after.addresses.undeployed).not.toBe(before.addresses.undeployed); + // Generating makes the new wallet active; alice stays the active one for the tests after. + await call('midnight_wallet_use', { name: 'alice' }); + }, 60_000); + + it('runs at once without force, and refuses a wallet that exists', async () => { + const refused = await call('midnight_wallet_generate', { name: 'bob' }); + + expect(refused.pending).toBeUndefined(); + expect(String(refused.message)).toContain('Wallet "bob" already exists'); + }); +}); + describe('midnight_wallet_remove', () => { const walletFile = (name: string) => path.join(home, '.midnight', 'wallets', `${name}.json`); diff --git a/src/__tests__/mcp-server-unknown-parameter.test.ts b/src/__tests__/mcp-server-unknown-parameter.test.ts index e178f849..1075b7bf 100644 --- a/src/__tests__/mcp-server-unknown-parameter.test.ts +++ b/src/__tests__/mcp-server-unknown-parameter.test.ts @@ -126,3 +126,38 @@ describe('a tool parameter outside the tool\'s schema', () => { expect(body).toMatchObject({ action: 'get', key: 'network' }); }, 60_000); }); + +describe('a tool parameter of the wrong type', () => { + it('refuses "false" for an on/off parameter, which used to switch it on, and the tool does not run', async () => { + const { isError, body } = await call('midnight_airdrop', { amount: '10', shielded: 'false', network: 'undeployed', ...CLOSED }); + expect(isError).toBe(true); + expect(body).toStrictEqual({ + error: true, + code: 'INVALID_ARGS', + message: 'Invalid parameter for midnight_airdrop: shielded must be true or false, not "false"', + _serverVersion: expect.any(String), + }); + }, 60_000); + + it('refuses force as a string before a token is given', async () => { + const { body } = await call('midnight_wallet_generate', { name: 'alice', force: 'true' }); + expect(body).toMatchObject({ error: true, code: 'INVALID_ARGS', message: 'Invalid parameter for midnight_wallet_generate: force must be true or false, not "true"' }); + expect(body.token).toBeUndefined(); + expect(fs.existsSync(path.join(home, '.midnight', 'wallets', 'alice.json'))).toBe(false); + }, 60_000); + + it('names every mistyped parameter: a value outside its list, and an object for a string', async () => { + const { body } = await call('midnight_address', { seed: '01'.repeat(32), network: 'mainnet', index: { n: 1 } }); + expect(body).toMatchObject({ + error: true, + code: 'INVALID_ARGS', + message: 'Invalid parameters for midnight_address: network must be one of preprod, preview, undeployed, not "mainnet"; index must be a string, not {"n":1}', + }); + }, 60_000); + + it('takes a number for a string parameter as its digits', async () => { + const { isError, body } = await call('midnight_address', { seed: '01'.repeat(32), network: 'undeployed', index: 2 }); + expect(isError).toBe(false); + expect(body).toMatchObject({ network: 'undeployed', index: 2 }); + }, 60_000); +}); diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index 30364ea7..1dcf13b5 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -21,7 +21,7 @@ export const airdropDefinition: CommandDefinition = { name: 'shielded', takesValue: false, help: ['--shielded Airdrop shielded NIGHT (from genesis shielded balance)'], - agent: { type: 'string', description: 'Set to "true" for shielded airdrop' }, + agent: { type: 'boolean', description: 'Airdrop shielded NIGHT (from the genesis shielded balance)' }, }, { name: 'verbose', @@ -74,7 +74,7 @@ export const airdropDefinition: CommandDefinition = { tools: [ { name: 'midnight_airdrop', - description: 'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: "true"` to fund a shielded balance.', + description: 'Fund from genesis (undeployed). `wallet` accepts a wallet name, a wallet JSON path, or a raw bech32m address (mn_addr_… or mn_shield-addr_…). Add `shielded: true` to fund a shielded balance.', annotations: { destructiveHint: true, openWorldHint: true }, params: [ { name: 'amount', schema: { type: 'string', description: 'NIGHT' } }, diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index 68ae85d0..f881c71e 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -117,7 +117,7 @@ export const dustDefinition: CommandDefinition = { { flag: 'proof-server', schema: { type: 'string' } }, { flag: 'node', schema: { type: 'string' } }, { flag: 'indexer-ws', schema: { type: 'string' } }, - { flag: 'no-cache', schema: { type: 'string' } }, + { flag: 'no-cache' }, { name: 'full', schema: { diff --git a/src/commands/grant.guidance.ts b/src/commands/grant.guidance.ts index 2da4bd23..e895ac57 100644 --- a/src/commands/grant.guidance.ts +++ b/src/commands/grant.guidance.ts @@ -152,7 +152,7 @@ A wallet's account is a contract its owner deploys. A grant lets an agent spend What has to be true first: Node.js is 22.18 or newer, and the network is \`undeployed\` (a local ledger-9 stack). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. 1. \`midnight_grant_status()\` says whether the wallet has an account. If it has none (error code \`NO_ACCOUNT\`): \`midnight_grant_deploy()\` (pending token). Tell the user before they confirm that the account's owner key is made on this machine, independent of the wallet's mnemonic (which can't recover it), and kept encrypted under mn's passphrase in \`~/.midnight/accounts///\`; that they keep the account by adding a second device or writing a backup from the command line (\`mn grant device\`, \`mn grant export\`); and that a deploy takes a few minutes and about 48 DUST from the wallet, about 17 of it at once (mn waits by itself when a fee is a few minutes of Dust away; a wallet further short is told how long, and the same call carries on later from where it stopped). Running it again finishes a deploy that stopped part way. -2. A grant spends only what the account holds, which \`midnight_grant_status()\` shows under \`held\` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: \`midnight_grant_deposit({ amount })\`, with \`amount\` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, \`midnight_airdrop\` with \`shielded: "true"\`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. +2. A grant spends only what the account holds, which \`midnight_grant_status()\` shows under \`held\` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: \`midnight_grant_deposit({ amount })\`, with \`amount\` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, \`midnight_airdrop\` with \`shielded: true\`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. 3. The agent gives a grant request link. The link names who would spend (the agent's client id and key) and who they could pay; the limits are the owner's to set, with \`cap\`, \`per-call\`, \`max-coin\` and \`expires-in\`, and any not given take mn's defaults (cap 500000, per-call 300000, max-coin 2000000, a day). Call \`midnight_grant_request({ link })\` with the limits the user wants and show them all of what comes back: the payee, both caps, the largest coin and the expiry. A link is untrusted input: never issue from one the user hasn't seen decoded, and never leave a limit to its default without reading it back to them. 4. \`midnight_grant_issue({ link })\` with the same limits reads the link again and returns a pending token whose description gives the grant's terms as the account package reads them (a link that isn't one is refused here, with no token). Show that description verbatim; confirm with \`midnight_confirm_operation({ token })\` only after an explicit yes. Issuing is three transactions and takes a few minutes. 5. \`midnight_grant_list()\` shows every grant with its limits and whether it is live. \`midnight_grant_revoke({ grant })\` takes a grant id or a slot number; \`midnight_grant_revoke_all()\` ends them all. Both return a pending token. diff --git a/src/commands/help.ts b/src/commands/help.ts index 1a4a968e..8f3e1691 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -17,7 +17,6 @@ import { hasShownIntroThisSession, markIntroShown } from '../lib/intro-marker.ts import { UsageError } from '../lib/errors.ts'; import type { CallContext, CallOutput } from '../lib/call-context.ts'; import { PKG_NAME, PKG_VERSION, PKG_DESCRIPTION } from '../lib/pkg.ts'; -import { INDEXER_GRAPHQL_WS_PATH } from '../lib/constants.ts'; type CommandSpec = CommandHelpSpec; diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 1f143c93..96b2eda6 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -23,7 +23,7 @@ export const walletDefinition: CommandDefinition = { takesValue: false, subcommands: ['generate'], help: ['--force Overwrite existing wallet file'], - agent: { type: 'string' }, + agent: { type: 'boolean', description: 'Replace an existing wallet of that name (asks for confirmation: its seed is deleted)' }, }, { name: 'mnemonic', @@ -110,7 +110,19 @@ export const walletDefinition: CommandDefinition = { { flag: 'force' }, ], required: ['name'], - argv: { subcommand: 'generate', positionals: ['name'], flags: 'rest', trueStrings: ['force'] }, + argv: { subcommand: 'generate', positionals: ['name'], flags: 'rest' }, + // Replacing a wallet deletes its seed, so a call with force is confirmed like remove. + confirmation: { + when: (params) => params.force === true, + async check(params) { + const fs = await import('node:fs'); + const { walletFilePath } = await import('../lib/wallet-create.ts'); + const name = String(params.name); + return fs.existsSync(walletFilePath(name)) + ? `Replace wallet ${name}: its file, and the seed in it, is deleted from this machine and a new wallet written in its place` + : `Create wallet ${name} (no wallet of that name exists, so nothing is replaced)`; + }, + }, order: 1, }, { diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index 35ffdb98..15018469 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -119,7 +119,7 @@ starts with mn_addr_ or mn_shield-addr_, it's used as an address directly. 10. midnight_dust_status → Check remaining dust Shielded workflow: - 1. midnight_airdrop → Fund shielded (amount: "100", shielded: "true") + 1. midnight_airdrop → Fund shielded (amount: "100", shielded: true) 2. midnight_balance → Shows both unshielded + shielded 3. midnight_transfer → Returns pending token for shielded send 4. (show + consent) → midnight_confirm_operation diff --git a/src/lib/call-context.ts b/src/lib/call-context.ts index 79e58754..beb13c2f 100644 --- a/src/lib/call-context.ts +++ b/src/lib/call-context.ts @@ -34,13 +34,6 @@ export interface CallOutput { stderr(text: string): void; } -/** Where a runner sends what a call's output is given. */ -export interface OutputSink { - result(data: Readonly>): void; - stdout(text: string): void; - stderr(text: string): void; -} - /** A call's progress: the spinners of its steps, what they say to the caller, and which one runs now. Its own per call. */ export type CallProgress = Progress; @@ -96,7 +89,7 @@ export class SecondResultError extends Error { } /** A call's output over `sink`: one result at most, each piece passed on as it comes. */ -export function callOutput(sink: OutputSink): CallOutput { +export function callOutput(sink: CallOutput): CallOutput { let hasResult = false; return { result(data) { @@ -128,7 +121,7 @@ export function hostCallConfig(): CallConfig { export interface CallParts { readonly args: ParsedArgs; readonly signal: AbortSignal; - readonly output: OutputSink; + readonly output: CallOutput; /** Where what the call's spinners say goes besides the terminal (the MCP server's progress notifications); none for the CLI. */ readonly onProgress?: ProgressReport; /** Where the call's SDK warnings go, from the router of the host that runs it; none: a call of its own, which no host's filters report to. */ diff --git a/src/lib/command-definition.ts b/src/lib/command-definition.ts index 89ceb708..353af7a9 100644 --- a/src/lib/command-definition.ts +++ b/src/lib/command-definition.ts @@ -132,8 +132,6 @@ export interface ToolArgv { * when given a truthy value, and the schema shows only those. */ readonly flags: 'rest' | readonly string[]; - /** Flags whose string value "true" becomes a bare flag. */ - readonly trueStrings?: readonly string[]; /** Flags always set. */ readonly fixedFlags?: Readonly>; /** Flag values used when the parameter is not given (or empty). */ @@ -150,6 +148,8 @@ export interface ToolCheckCall { /** A tool behind the two-step confirmation. */ export interface ToolConfirmation { + /** Whether this call needs confirming; absent: every call does. */ + readonly when?: (params: Readonly>) => boolean; /** The text the user confirms, from the tool's parameters; absent: the check works it out. */ readonly describe?: (params: Readonly>) => string; /** @@ -385,8 +385,6 @@ export function toolArgv(tool: RegisteredTool, params: Readonly c.mcp?.tools.some((tool) => tool.name === toolName)); - const tool = command?.mcp?.tools.find((t) => t.name === toolName); - if (command === undefined || tool?.argv.flags !== 'rest') return []; - return [...command.flags, ...registry.globalFlags].map((flag) => flag.name); -} - /** The Flags section of `help `, line by line, as shown. */ export function flagsSectionLines(command: CommandDefinition): string[] { return (command.help?.flags ?? []).flatMap((entry) => @@ -531,6 +512,11 @@ export function confirmationTarget(params: Readonly>): { }; } +/** The call needs the user's confirmation before it runs: the tool is confirmed, and its `when` doesn't exempt these parameters. */ +export function needsConfirmation(tool: ToolDefinition, params: Readonly>): boolean { + return tool.confirmation !== undefined && (tool.confirmation.when?.(params) ?? true); +} + /** The text a user confirms for a tool's call when its check gives none. */ export function confirmationText(tool: ToolDefinition, params: Readonly>): string { return tool.confirmation?.describe?.(params) ?? `Execute ${tool.name} with ${JSON.stringify(params)}`; diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index 38d4fcfb..0b486b1b 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -4,7 +4,7 @@ // given and where a notice goes, and decides the heap and the exit. import type { ParsedArgs } from './argv.ts'; -import { createCallContext, runHandler, type CallContext, type CommandOutcome, type OutputSink } from './call-context.ts'; +import { createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput } from './call-context.ts'; import type { CommandDefinition, CommandRegistry } from './command-definition.ts'; import { UsageError } from './errors.ts'; import { writeJsonResult } from './json-output.ts'; @@ -16,7 +16,7 @@ import type { WalletProtector } from './wallet-protector.ts'; export interface ShellProvisions { readonly signal: AbortSignal; /** Where the call's output goes; a definition's notice goes to its stderr, before the handler loads. */ - readonly output: OutputSink; + readonly output: CallOutput; /** The host's calls: each call runs in one, with its own SDK warnings. */ readonly sdkWarnings: SdkWarningCalls; readonly loadPayer: () => Promise; @@ -24,7 +24,7 @@ export interface ShellProvisions { } /** The CLI's output, written at once: the result as one line of JSON on stdout, text on stdout and stderr. */ -export const processOutput: OutputSink = { +export const processOutput: CallOutput = { result: writeJsonResult, stdout: (text) => { process.stdout.write(text); }, stderr: (text) => { process.stderr.write(text); }, diff --git a/src/lib/mcp/known-params.ts b/src/lib/mcp/known-params.ts index 4e751fe6..192abc62 100644 --- a/src/lib/mcp/known-params.ts +++ b/src/lib/mcp/known-params.ts @@ -1,12 +1,19 @@ -// The MCP server's one check on a call's parameters: a parameter outside the -// tool's schema is refused before anything runs. +// The MCP server's checks on a call's parameters, before anything runs: a +// parameter outside the tool's schema is refused, and so is one whose value +// is not the type its schema says. import { UsageError } from '../errors.ts'; +/** A parameter's schema as the server checks it. */ +interface ParamCheck { + readonly type: string; + readonly enum?: readonly string[]; +} + /** A tool's name and the schema of the parameters it takes. */ interface ToolSchema { readonly name: string; - readonly inputSchema: { readonly properties: Readonly> }; + readonly inputSchema: { readonly properties: Readonly> }; } /** The parameters a call gives that are not in the tool's schema, in the order given. */ @@ -28,3 +35,35 @@ export function assertKnownParams(tool: ToolSchema, params: Record 1 ? 's' : ''} for ${tool.name}: ${unknown.join(', ')}\n${takes}`); } + +/** Why the value doesn't fit the schema, or undefined when it does. Absent (undefined or null) always fits. */ +function mistyped(schema: ParamCheck, value: unknown): string | undefined { + if (value === undefined || value === null) return undefined; + if (schema.type === 'boolean') { + return typeof value === 'boolean' ? undefined : `must be true or false, not ${JSON.stringify(value)}`; + } + // A string parameter takes a number as its digits (an amount, a port): nothing is misread. + if (typeof value !== 'string' && !(typeof value === 'number' && Number.isFinite(value))) { + return `must be a string, not ${JSON.stringify(value)}`; + } + if (schema.enum !== undefined && !schema.enum.includes(String(value))) { + return `must be one of ${schema.enum.join(', ')}, not ${JSON.stringify(value)}`; + } + return undefined; +} + +/** + * Throw a UsageError (INVALID_ARGS) naming every known parameter whose value + * is not its schema's type. An on/off parameter must be a boolean: the + * string "false" used to switch it on, since any value but `false` set the + * flag. + */ +export function assertParamTypes(tool: ToolSchema, params: Record): void { + const problems = Object.entries(params).flatMap(([key, value]) => { + const schema = tool.inputSchema.properties[key]; + const why = schema === undefined ? undefined : mistyped(schema, value); + return why === undefined ? [] : [`${key} ${why}`]; + }); + if (problems.length === 0) return; + throw new UsageError(`Invalid parameter${problems.length > 1 ? 's' : ''} for ${tool.name}: ${problems.join('; ')}`); +} diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index 830effe9..bd5556d1 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -3,7 +3,7 @@ import { type ParsedArgs, MINIMAL_FLAG } from './argv.ts'; import type { Payer } from './payer.ts'; -import { createCallContext, runHandler, type CommandHandler, type OutputSink } from './call-context.ts'; +import { createCallContext, runHandler, type CommandHandler, type CallOutput } from './call-context.ts'; import type { SdkWarningCalls } from './sdk-warnings.ts'; import { CommandFailedError } from './errors.ts'; @@ -57,7 +57,7 @@ export async function captureCommand( { signal, onProgress, payer, sdkWarnings }: CommandRun, ): Promise> { let result: Record = {}; - const output: OutputSink = { + const output: CallOutput = { // Read back as JSON, as the server sends it: what was written then, nothing the handler changes after. result: (data) => { result = JSON.parse(JSON.stringify(data)) as Record; }, stdout: serverStderr, diff --git a/src/mcp-server.ts b/src/mcp-server.ts index f3639d48..011f3e08 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -20,8 +20,9 @@ import { classifyError } from './lib/exit-codes.ts'; import { trimAgentMessage } from './lib/error-trim.ts'; import { PKG_VERSION } from './lib/pkg.ts'; import { createConfirmationStore } from './lib/mcp/confirmation.ts'; -import { assertKnownParams } from './lib/mcp/known-params.ts'; +import { assertKnownParams, assertParamTypes } from './lib/mcp/known-params.ts'; import { CONFIRM_TOOL, confirmationFor, findTool, listedTools, runTool } from './lib/mcp/registry-tools.ts'; +import { needsConfirmation } from './lib/command-definition.ts'; import { ensureHeapForSync } from './lib/heap-guard.ts'; import { assertNodeSupported } from './lib/node-version.ts'; import { hideProjectIdsInOutput } from './lib/output-redaction.ts'; @@ -96,13 +97,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { const params = (rawParams ?? {}) as Record; const call = toolCall(request.params._meta?.progressToken, extra); - // A parameter outside the tool's schema is refused before anything runs or - // a token is given. An unknown tool is reported by executeTool. + // A parameter outside the tool's schema, or not of its type, is refused + // before anything runs or a token is given. An unknown tool is reported by + // executeTool. const tool = findTool(installedCommands, name); const schema = name === CONFIRM_TOOL.name ? CONFIRM_TOOL : tool; if (schema !== undefined) { try { assertKnownParams(schema, params); + assertParamTypes(schema, params); } catch (err) { return errorResponse(err instanceof Error ? err : new Error(String(err))); } @@ -119,7 +122,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { } // Step 1 of confirmation: return a pending token instead of executing. - if (tool?.confirmation !== undefined) { + if (tool !== undefined && needsConfirmation(tool, params)) { let description: string; try { description = await confirmationFor(tool, params, call); From 92660a09c144791174c1bc232292501129d0a9a8 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:49:46 -0800 Subject: [PATCH 14/88] MCP confirmations name the endpoints a call is sent to The text a user confirms named the network but not an endpoint given as a parameter or set with config, so a transfer's proof could go to a host the user never saw. Each endpoint other than the network's own is named now: given ones as given, configured ones marked "set with config". A tool that takes no endpoints reads as before. --- src/__tests__/mcp-server-confirmation.test.ts | 41 +++++++++++++++---- src/lib/mcp/registry-tools.ts | 30 +++++++++++++- 2 files changed, 60 insertions(+), 11 deletions(-) diff --git a/src/__tests__/mcp-server-confirmation.test.ts b/src/__tests__/mcp-server-confirmation.test.ts index dc5d457d..f054838b 100644 --- a/src/__tests__/mcp-server-confirmation.test.ts +++ b/src/__tests__/mcp-server-confirmation.test.ts @@ -16,6 +16,8 @@ import { freshGrantee, grantRequestFor, grantRequestLink } from '@kuiralabs/midn const REPO = fileURLToPath(new URL('../..', import.meta.url)); const TSX = path.join(REPO, 'node_modules', '.bin', 'tsx'); const ENDPOINTS = { node: 'ws://localhost:29944', 'indexer-ws': 'ws://localhost:28088/api/v4/graphql/ws', 'proof-server': 'http://localhost:26300' }; +// How a confirmation names those endpoints. +const VIA = '. Endpoints: node ws://localhost:29944, indexer ws://localhost:28088/api/v4/graphql/ws, proof server http://localhost:26300'; // An account's records as mn 0.6.0-rc.10 left them. const ACCOUNT = '5e'.repeat(32); @@ -87,14 +89,14 @@ describe('every tool that acts answers with a token, and does nothing until it i 3, new Uint8Array(32).fill(0x9a), 2, )); const cases: Array<[string, () => Record, () => string | RegExp]> = [ - ['midnight_transfer', () => ({ to: 'carol', amount: '5', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => 'Send 5 NIGHT from alice to carol on undeployed'], - ['midnight_contract_deploy', () => ({ path: dappDir, wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Deploy contract from ${dappDir} as alice on undeployed`], - ['midnight_contract_call', () => ({ path: dappDir, address: ADDRESS, circuit: 'increment', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Call circuit increment on contract ${ADDRESS} as alice on undeployed`], - ['midnight_grant_deploy', () => ({ wallet: 'carol', network: 'undeployed', ...ENDPOINTS }), () => "Deploy an account for carol on undeployed; its owner key is made on this machine and kept encrypted under mn's passphrase"], - ['midnight_grant_deposit', () => ({ amount: '2', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Deposit 2 shielded NIGHT (2000000 in the smallest unit) from wallet alice into its account ${ACCOUNT} on undeployed`], - ['midnight_grant_issue', () => ({ link: link(), wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => new RegExp(`^Issue a grant on alice's account on undeployed, letting an agent spend from it within these terms .*${ACCOUNT}`)], - ['midnight_grant_revoke', () => ({ grant: '3', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => "Revoke grant 3 on alice's account on undeployed"], - ['midnight_grant_revoke_all', () => ({ wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => "Revoke every grant on alice's account on undeployed"], + ['midnight_transfer', () => ({ to: 'carol', amount: '5', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => 'Send 5 NIGHT from alice to carol on undeployed' + VIA], + ['midnight_contract_deploy', () => ({ path: dappDir, wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Deploy contract from ${dappDir} as alice on undeployed` + VIA], + ['midnight_contract_call', () => ({ path: dappDir, address: ADDRESS, circuit: 'increment', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Call circuit increment on contract ${ADDRESS} as alice on undeployed` + VIA], + ['midnight_grant_deploy', () => ({ wallet: 'carol', network: 'undeployed', ...ENDPOINTS }), () => "Deploy an account for carol on undeployed; its owner key is made on this machine and kept encrypted under mn's passphrase" + VIA], + ['midnight_grant_deposit', () => ({ amount: '2', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => `Deposit 2 shielded NIGHT (2000000 in the smallest unit) from wallet alice into its account ${ACCOUNT} on undeployed` + VIA], + ['midnight_grant_issue', () => ({ link: link(), wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => new RegExp(`^Issue a grant on alice's account on undeployed, letting an agent spend from it within these terms .*${ACCOUNT}[\\s\\S]*\\. Endpoints: node ws://localhost:29944, indexer ws://localhost:28088/api/v4/graphql/ws, proof server http://localhost:26300$`)], + ['midnight_grant_revoke', () => ({ grant: '3', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => "Revoke grant 3 on alice's account on undeployed" + VIA], + ['midnight_grant_revoke_all', () => ({ wallet: 'alice', network: 'undeployed', ...ENDPOINTS }), () => "Revoke every grant on alice's account on undeployed" + VIA], ['midnight_wallet_remove', () => ({ name: 'carol' }), () => 'Remove wallet carol: its file, and the seed in it, is deleted from this machine'], ]; @@ -125,7 +127,7 @@ describe('midnight_grant_deposit', () => { expect(pending.pending).toBe(true); expect(pending.token).toEqual(expect.any(String)); expect(pending.tool).toBe('midnight_grant_deposit'); - expect(pending.description).toBe(`Deposit 1.5 shielded NIGHT (1500000 in the smallest unit) from wallet alice into its account ${ACCOUNT} on undeployed`); + expect(pending.description).toBe(`Deposit 1.5 shielded NIGHT (1500000 in the smallest unit) from wallet alice into its account ${ACCOUNT} on undeployed${VIA}`); // Nothing was built or kept: the records are as they were, and no private state was opened. expect(fs.readdirSync(recordsDir)).toEqual(['owner.json']); expect(JSON.parse(fs.readFileSync(path.join(recordsDir, 'owner.json'), 'utf8'))).toEqual(OWNER_RECORD); @@ -138,6 +140,27 @@ describe('midnight_grant_deposit', () => { }, 60_000); }); +describe('endpoints in what the user confirms', () => { + it('names one set with config for the network, and leaves out what is the network\'s own', async () => { + const file = path.join(home, '.midnight', 'config.json'); + const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : undefined; + fs.writeFileSync(file, JSON.stringify({ ...(before === undefined ? {} : JSON.parse(before)), networks: { undeployed: { 'proof-server': 'http://proofs.example:6300' } } })); + try { + const pending = await call('midnight_transfer', { to: 'carol', amount: '5', wallet: 'alice', network: 'undeployed', node: ENDPOINTS.node, 'indexer-ws': ENDPOINTS['indexer-ws'] }); + expect(pending.error, String(pending.message)).toBeUndefined(); + expect(pending.description).toBe('Send 5 NIGHT from alice to carol on undeployed. Endpoints: node ws://localhost:29944, indexer ws://localhost:28088/api/v4/graphql/ws, proof server http://proofs.example:6300 (set with config)'); + } finally { + if (before === undefined) fs.rmSync(file); + else fs.writeFileSync(file, before); + } + }); + + it('names none for a tool that takes no endpoints', async () => { + const pending = await call('midnight_wallet_remove', { name: 'carol' }); + expect(pending.description).toBe('Remove wallet carol: its file, and the seed in it, is deleted from this machine'); + }); +}); + describe('midnight_wallet_generate with force', () => { const walletFile = (name: string) => path.join(home, '.midnight', 'wallets', `${name}.json`); diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index 3bf88238..ab706af7 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -5,6 +5,8 @@ // the confirmation flow gives. import { type CommandRun, captureCommand } from '../run-command.ts'; +import { getEndpointOverridesForNetwork, loadCliConfig } from '../cli-config.ts'; +import { resolveNetworkName } from '../resolve-network.ts'; import { type CommandRegistry, type RegisteredTool, @@ -50,15 +52,39 @@ export async function runTool(tool: RegisteredTool, params: Readonly>): string { + const properties = tool.inputSchema.properties; + if (!ENDPOINTS.some(([param]) => Object.hasOwn(properties, param))) return ''; + const configured = getEndpointOverridesForNetwork(loadCliConfig(), resolveNetworkName({ args: toolArgv(tool, params) })); + const named = ENDPOINTS.flatMap(([param, label]) => { + const given = params[param]; + if (typeof given === 'string' && given !== '') return [`${label} ${given}`]; + const set = configured[param]; + return set === undefined ? [] : [`${label} ${set} (set with config)`]; + }); + return named.length === 0 ? '' : `. Endpoints: ${named.join(', ')}`; +} + /** * For a tool behind confirmation: runs its check, which throws when the call * can't run, and returns the text the user confirms (the check's own, or the - * definition's from the parameters). + * definition's from the parameters), naming any endpoint the call is sent to + * other than the network's own. */ export async function confirmationFor(tool: RegisteredTool, params: Readonly>, call: CommandRun): Promise { const found = await tool.confirmation?.check?.(params, { argv: () => toolArgv(tool, params), run: async (args) => captureCommand((await tool.command.load()).default, args, call), }); - return found ?? confirmationText(tool, params); + return (found ?? confirmationText(tool, params)) + endpointOverridesNote(tool, params); } From c2af1b9f5906a0a125270b794bc17f43d84c3846 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:51:00 -0800 Subject: [PATCH 15/88] mn --help shows the command's own help It showed the general help, and on a subcommand line (mn wallet generate --help) asked help for "generate", which isn't a command. Now it shows what mn help shows, whatever else is on the line; --help alone, after an unknown command or with --json (the manifest) reads as before. --- src/__tests__/shell-unknown-flag.test.ts | 27 ++++++++++++++++++++---- src/wallet.ts | 13 ++++++++++-- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/__tests__/shell-unknown-flag.test.ts b/src/__tests__/shell-unknown-flag.test.ts index a8192fd9..2ff1ea56 100644 --- a/src/__tests__/shell-unknown-flag.test.ts +++ b/src/__tests__/shell-unknown-flag.test.ts @@ -1,5 +1,5 @@ // The shell refuses a flag the command doesn't accept before the command runs, -// and shows help instead when help is asked for. Run as the CLI is: this +// and shows the command's help instead when help is asked for. Run as the CLI is: this // checkout's entry point in its own process, with a temporary home that holds // no wallet, so a command that ran would fail with WALLET_NOT_FOUND (exit 3). @@ -47,11 +47,30 @@ describe('the unknown-flag refusal, through the shell', () => { expect(JSON.parse(run.stdout)).toMatchObject({ error: true, code: 'WALLET_NOT_FOUND' }); }); - it('shows help instead when help is asked for, whatever else is on the line', () => { - // Today that is the general help, not the command's own. + it('shows the command\'s own help instead when help is asked for, whatever else is on the line', () => { const run = mn('info', '--bogus', '--help'); expect(run.status).toBe(0); - expect(run.stdout + run.stderr).toContain('Commands:'); + expect(run.stdout + run.stderr).toBe(mn('help', 'info').stdout + mn('help', 'info').stderr); + expect(run.stdout + run.stderr).toContain('Display wallet address, network, creation date'); expect(run.stdout + run.stderr).not.toContain('Unknown flag'); }); + + it('shows the command\'s help for a subcommand line too, and -h does the same', () => { + const own = mn('help', 'wallet'); + expect(mn('wallet', 'generate', 'alice', '--help').stdout + mn('wallet', 'generate', 'alice', '--help').stderr).toBe(own.stdout + own.stderr); + expect(mn('wallet', '-h').stdout + mn('wallet', '-h').stderr).toBe(own.stdout + own.stderr); + }); + + it('shows the general help for --help alone, or after a command it doesn\'t know', () => { + for (const run of [mn('--help'), mn('bogus', '--help'), mn('help', '--help')]) { + expect(run.status).toBe(0); + expect(run.stdout + run.stderr).toContain('Commands:'); + } + }); + + it('keeps --help --json as the JSON manifest', () => { + const run = mn('--help', '--json'); + expect(run.status).toBe(0); + expect(JSON.parse(run.stdout)).toMatchObject({ cli: { name: 'midnight-wallet-cli' } }); + }); }); diff --git a/src/wallet.ts b/src/wallet.ts index d7f26c16..c837df70 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -36,11 +36,20 @@ if (hasFlag(args, 'version') || hasFlag(args, 'v')) { process.exit(0); } -// Global --help / -h handling. `mn --help` shows help whatever other -// flags are present, so flag checking is skipped for it. +// Global --help / -h handling. `mn --help` shows that command's help, +// as `mn help ` does, whatever other flags are present, so flag checking +// is skipped for it; with no command help lists, the general help. const helpRequested = hasFlag(args, 'help') || hasFlag(args, 'h'); if (helpRequested) { + const target = args.command !== undefined && installedCommands.find(args.command)?.help !== undefined ? args.command : undefined; args.command = 'help'; + args.positionals = []; + if (target !== undefined && target !== 'help') { + args.subcommand = target; + args.flags = {}; + } else { + args.subcommand = undefined; + } } // Default to help when no command given From 2b42d2276dc94f607091930ff68ab2aa885e335b Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:52:51 -0800 Subject: [PATCH 16/88] The CLI refuses a flag that belongs to another subcommand mn dust register --seed x ran and ignored the seed; the MCP server already refused it. The shell now refuses, before the command runs, a flag the command accepts but its subcommand doesn't read, naming the subcommands it is for (INVALID_ARGS, exit 2). The definitions' scopes are made to match what the handlers read: wallet list and info read --network, test results reads --suite, and test's --network and --path are read by create only (run and results find the dApp from the working directory, so --path there was silently ignored). A definition may name its subcommands' aliases (wallet's ls and rm). --- src/__tests__/command-flags.test.ts | 34 +++++++++++++++- src/__tests__/shell-unknown-flag.test.ts | 6 +++ src/commands/test.definition.ts | 12 ++++-- src/commands/wallet.definition.ts | 4 +- src/lib/command-definition.ts | 5 +++ src/lib/command-flags.ts | 50 +++++++++++++++++++----- 6 files changed, 95 insertions(+), 16 deletions(-) diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 8ee8bf9d..4a735771 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -9,7 +9,7 @@ import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { parseArgs } from '../lib/argv.ts'; import { UsageError } from '../lib/errors.ts'; -import { findUnknownFlags as findUnknownFlagsIn, assertKnownFlags as assertKnownFlagsIn } from '../lib/command-flags.ts'; +import { findUnknownFlags as findUnknownFlagsIn, findMisplacedFlags as findMisplacedFlagsIn, assertKnownFlags as assertKnownFlagsIn } from '../lib/command-flags.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import type { ParsedArgs } from '../lib/argv.ts'; @@ -56,6 +56,38 @@ describe('assertKnownFlags', () => { }); }); +describe('a flag that belongs to another subcommand', () => { + const misplaced = (...argv: string[]) => findMisplacedFlagsIn(parseArgs(argv), installedCommands); + + it('is refused, naming the subcommands it is for, before the command runs', () => { + const args = parseArgs(['dust', 'register', '--seed', 'ab']); + expect(findMisplacedFlagsIn(args, installedCommands)).toEqual([{ flag: 'seed', subcommands: ['export'] }]); + expect(() => assertKnownFlags(args)).toThrow(new UsageError('Not a flag of "midnight dust register": --seed (only for export)\nRun "midnight help dust" for the flags each subcommand takes.')); + }); + + it('names every one', () => { + expect(misplaced('wallet', 'use', 'alice', '--force', '--entropy')).toEqual([{ flag: 'force', subcommands: ['generate'] }, { flag: 'entropy', subcommands: ['seed'] }]); + }); + + it('reads an alias as its subcommand', () => { + expect(misplaced('wallet', 'ls', '--network', 'preprod')).toEqual([]); + expect(misplaced('wallet', 'rm', 'bob', '--force')).toEqual([{ flag: 'force', subcommands: ['generate'] }]); + }); + + it('lets through a flag its subcommand reads, and every flag of a command without subcommands', () => { + expect(misplaced('wallet', 'list', '--network', 'preprod')).toEqual([]); + expect(misplaced('wallet', 'info', 'bob', '--network', 'preprod')).toEqual([]); + expect(misplaced('test', 'results', '--suite', 'e2e')).toEqual([]); + expect(misplaced('dust', 'status', '--no-cache')).toEqual([]); + expect(misplaced('balance', 'mn_addr_undeployed1x', '--shielded')).toEqual([]); + }); + + it('leaves a missing or unknown subcommand to the handler', () => { + expect(misplaced('dust', '--seed', 'ab')).toEqual([]); + expect(misplaced('dust', 'regster', '--seed', 'ab')).toEqual([]); + }); +}); + describe('the accepted flags match the code', () => { // A flag a command reads but the registry lacks would be rejected even // though it works; a registry entry no code reads would be accepted and diff --git a/src/__tests__/shell-unknown-flag.test.ts b/src/__tests__/shell-unknown-flag.test.ts index 2ff1ea56..5824be27 100644 --- a/src/__tests__/shell-unknown-flag.test.ts +++ b/src/__tests__/shell-unknown-flag.test.ts @@ -41,6 +41,12 @@ describe('the unknown-flag refusal, through the shell', () => { expect(run.stderr).toContain('Unknown flags for "midnight info": --bogus, --other'); }); + it('refuses a flag of another subcommand with exit 2 and INVALID_ARGS, before the command runs', () => { + const run = mn('dust', 'register', '--seed', 'ab', '--json'); + expect(run.status).toBe(2); + expect(JSON.parse(run.stdout)).toMatchObject({ error: true, code: 'INVALID_ARGS', message: expect.stringContaining('--seed (only for export)') }); + }); + it('runs the command when its flags are known: here it finds no wallet', () => { const run = mn('info', '--network', 'undeployed', '--json'); expect(run.status).toBe(3); diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index 8e452718..6b6dbaad 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -63,7 +63,9 @@ export const testDefinition: CommandDefinition = { { name: 'network', takesValue: true, - help: ['--network Network for the generated suite (default: undeployed)'], + // run takes its network from dapp.test.json. + subcommands: ['create'], + help: ['--network Network for the generated suite (create; default: undeployed)'], agent: NETWORK_PARAM, }, { @@ -75,7 +77,9 @@ export const testDefinition: CommandDefinition = { { name: 'path', takesValue: true, - help: ['--path dApp directory (default: cwd)'], + // run and results find the dApp from the working directory. + subcommands: ['create'], + help: ['--path dApp directory (create; default: cwd)'], agent: { type: 'string', description: 'dApp directory (defaults to cwd)' }, }, { @@ -106,8 +110,8 @@ export const testDefinition: CommandDefinition = { { name: 'suite', takesValue: true, - subcommands: ['run', 'create'], - help: ['--suite Select a specific test suite (run, create)'], + subcommands: ['run', 'create', 'results'], + help: ['--suite Select a specific test suite (run, create, results)'], agent: { type: 'string', description: 'Suite directory name under tests/suites/ (auto-derived from circuit/screen when AI scaffolds)' }, }, { diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 96b2eda6..edde035e 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -6,6 +6,7 @@ export const walletDefinition: CommandDefinition = { name: 'wallet', order: 10, subcommands: ['generate', 'list', 'use', 'info', 'remove', 'seed', 'protect'], + subcommandAliases: { ls: 'list', rm: 'remove' }, flags: [ { name: 'entropy', @@ -35,7 +36,8 @@ export const walletDefinition: CommandDefinition = { { name: 'network', takesValue: true, - subcommands: ['generate'], + // list and info show the addresses for it. + subcommands: ['generate', 'list', 'info'], help: ['--network Network: preprod, preview, undeployed'], agent: NETWORK_PARAM, }, diff --git a/src/lib/command-definition.ts b/src/lib/command-definition.ts index 353af7a9..b72fd467 100644 --- a/src/lib/command-definition.ts +++ b/src/lib/command-definition.ts @@ -185,6 +185,8 @@ export interface CommandDefinition { /** Its place among the installed commands, which help lists in this order; a plugin takes one no other command has. */ readonly order: number; readonly subcommands?: readonly string[]; + /** Other spellings its handler takes for a subcommand: `ls` for `list`. */ + readonly subcommandAliases?: Readonly>; readonly flags: readonly FlagDefinition[]; /** Absent: help does not list the command. */ readonly help?: CommandHelp; @@ -260,6 +262,9 @@ function checkDefinition(command: CommandDefinition): void { if (shown.has(entry.flag)) throw new CommandDefinitionError(`${command.name}: help shows --${entry.flag} twice`); shown.add(entry.flag); } + for (const [alias, sub] of Object.entries(command.subcommandAliases ?? {})) { + if (!command.subcommands?.includes(sub)) throw new CommandDefinitionError(`${command.name}: "${alias}" stands for "${sub}", not one of its subcommands`); + } for (const flag of command.flags) { if (flag.help !== undefined && !shown.has(flag.name)) throw new CommandDefinitionError(`${command.name}: --${flag.name} has help lines that help never shows`); for (const sub of flag.subcommands ?? []) { diff --git a/src/lib/command-flags.ts b/src/lib/command-flags.ts index c49c8810..373e31a5 100644 --- a/src/lib/command-flags.ts +++ b/src/lib/command-flags.ts @@ -1,11 +1,13 @@ // The unknown-flag refusal. The CLI rejects any flag a command doesn't accept // before the command runs: an unrecognised flag used to be silently ignored, so // a typo or a malformed argument fell back to defaults (for endpoints, a -// different chain). The accepted flags come from the command registry: -// each command's definition, and the registry's global flags. +// different chain). So is a flag that belongs to another subcommand of the +// command (`mn dust register --seed x` ignored the seed). The accepted flags +// come from the command registry: each command's definition, and the +// registry's global flags. import { type ParsedArgs } from './argv.ts'; -import type { CommandRegistry } from './command-definition.ts'; +import type { CommandRegistry, FlagDefinition } from './command-definition.ts'; import { UsageError } from './errors.ts'; /** The registry, as far as the refusal reads it. */ @@ -19,13 +21,41 @@ export function findUnknownFlags(args: ParsedArgs, registry: FlagRegistry): stri return Object.keys(args.flags).filter((f) => !accepted.has(f)); } -/** Throw a UsageError naming every flag the command doesn't accept. */ +/** + * Flags on the command line that the command accepts but its subcommand + * doesn't read, with the subcommands that do, in the order given. None when + * the subcommand is missing or not one of the command's: the handler reports + * that. + */ +export function findMisplacedFlags(args: ParsedArgs, registry: FlagRegistry): Array<{ flag: string; subcommands: readonly string[] }> { + const definition = args.command === undefined ? undefined : registry.find(args.command); + if (definition === undefined || args.subcommand === undefined) return []; + const subcommand = definition.subcommandAliases?.[args.subcommand] ?? args.subcommand; + if (!definition.subcommands?.includes(subcommand)) return []; + const byName = new Map(definition.flags.map((flag) => [flag.name, flag])); + return Object.keys(args.flags).flatMap((name) => { + const scope = byName.get(name)?.subcommands; + return scope === undefined || scope.includes(subcommand) ? [] : [{ flag: name, subcommands: scope }]; + }); +} + +const shown = (flag: string): string => (flag.length === 1 ? `-${flag}` : `--${flag}`); + +/** Throw a UsageError naming every flag the command doesn't accept, or else every one its subcommand doesn't read. */ export function assertKnownFlags(args: ParsedArgs, registry: FlagRegistry): void { const unknown = findUnknownFlags(args, registry); - if (unknown.length === 0) return; - const listed = unknown.map((f) => (f.length === 1 ? `-${f}` : `--${f}`)).join(', '); - throw new UsageError( - `Unknown flag${unknown.length > 1 ? 's' : ''} for "midnight ${args.command}": ${listed}\n` + - `Run "midnight help ${args.command}" for the flags it accepts.`, - ); + if (unknown.length > 0) { + throw new UsageError( + `Unknown flag${unknown.length > 1 ? 's' : ''} for "midnight ${args.command}": ${unknown.map(shown).join(', ')}\n` + + `Run "midnight help ${args.command}" for the flags it accepts.`, + ); + } + const misplaced = findMisplacedFlags(args, registry); + if (misplaced.length > 0) { + const listed = misplaced.map(({ flag, subcommands }) => `${shown(flag)} (only for ${subcommands.join(', ')})`).join(', '); + throw new UsageError( + `Not a flag of "midnight ${args.command} ${args.subcommand}": ${listed}\n` + + `Run "midnight help ${args.command}" for the flags each subcommand takes.`, + ); + } } From 63aa3dc07ce270b967bc010be9ac46c9dac021bf Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:54:17 -0800 Subject: [PATCH 17/88] wallet's and generate's help name the JSON fields they write MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit help --json and the agent manual described fewer fields than wallet writes (addresses, seed, file, createdAt, …), and named two generate doesn't write (address, network). Both now list what each subcommand writes, and the test that listed the gap checks there is none, with wallet seed, remove and protect added to its runs. --- src/__tests__/json-fields.test.ts | 41 ++++++++++++++--------------- src/commands/generate.definition.ts | 5 ++-- src/commands/wallet.definition.ts | 25 ++++++++++++++---- 3 files changed, 43 insertions(+), 28 deletions(-) diff --git a/src/__tests__/json-fields.test.ts b/src/__tests__/json-fields.test.ts index a54009b7..c721f9d0 100644 --- a/src/__tests__/json-fields.test.ts +++ b/src/__tests__/json-fields.test.ts @@ -39,32 +39,31 @@ async function run(...argv: string[]): Promise> { return captureCommand(handler as CommandHandler, args, ownCall()); } -// In order: a later run reads what an earlier one wrote. Each run lists the -// fields it writes that its help doesn't name yet: wallet's and generate's help -// predate what they write, and correcting help is a change to what users and -// agents read, waiting on the owner's approval. A field missing from help that -// isn't listed here fails, and so does a listed one once help names it. -const runs: ReadonlyArray = [ - [['wallet', 'generate', 'alice'], ['addresses', 'shieldedAddresses', 'activeAddress', 'activeNetwork', 'seed', 'file', 'createdAt', 'mnemonic']], - [['wallet', 'generate', 'bob'], ['addresses', 'shieldedAddresses', 'activeAddress', 'activeNetwork', 'seed', 'file', 'createdAt', 'mnemonic']], - [['wallet', 'use', 'alice'], ['wallet']], - [['wallet', 'list'], ['activeNetwork']], - [['wallet', 'info', 'bob'], ['addresses', 'activeAddress', 'activeNetwork', 'createdAt', 'file', 'shieldedAddresses']], - [['info'], []], - [['address', '--seed', 'aa'.repeat(32), '--network', 'undeployed'], []], - [['genesis-address', '--network', 'undeployed'], []], - [['config', 'set', 'network', 'preview'], []], - [['config', 'get', 'network'], []], - [['config', 'unset', 'network'], []], - [['cache', 'clear'], []], - [['generate', '--output', 'legacy.json'], ['addresses', 'activeAddress', 'activeNetwork']], +// In order: a later run reads what an earlier one wrote. +const runs: ReadonlyArray = [ + ['wallet', 'generate', 'alice'], + ['wallet', 'generate', 'bob'], + ['wallet', 'use', 'alice'], + ['wallet', 'list'], + ['wallet', 'info', 'bob'], + ['wallet', 'seed', 'bob', '--entropy'], + ['wallet', 'remove', 'bob'], + ['wallet', 'protect'], + ['info'], + ['address', '--seed', 'aa'.repeat(32), '--network', 'undeployed'], + ['genesis-address', '--network', 'undeployed'], + ['config', 'set', 'network', 'preview'], + ['config', 'get', 'network'], + ['config', 'unset', 'network'], + ['cache', 'clear'], + ['generate', '--output', 'legacy.json'], ]; describe('every field a command writes with --json is one its definition names', () => { - it.each(runs.map(([argv, notYetInHelp]) => [argv.join(' '), argv, notYetInHelp] as const))('%s', async (_name, argv, notYetInHelp) => { + it.each(runs.map((argv) => [argv.join(' '), argv] as const))('%s', async (_name, argv) => { const declared = Object.keys(installedCommands.find(argv[0]!)!.help?.jsonFields ?? {}); const written = Object.keys(await run(...argv.map((a) => (a === 'legacy.json' ? path.join(home, a) : a)))); expect(written.length).toBeGreaterThan(0); - expect(written.filter((field) => !declared.includes(field)).sort()).toStrictEqual([...notYetInHelp].sort()); + expect(written.filter((field) => !declared.includes(field))).toStrictEqual([]); }); }); diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index 10083f7e..9aa7d0d5 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -46,8 +46,9 @@ export const generateDefinition: CommandDefinition = { ], examples: ['midnight generate --network preprod'], jsonFields: { - address: 'Generated wallet address (bech32m)', - network: 'Network name', + addresses: 'Per-network unshielded addresses { preprod, preview, undeployed }', + activeAddress: 'Unshielded address on the active network (bech32m)', + activeNetwork: 'The active network', seed: 'Hex-encoded seed (32-byte raw, or 64-byte if mnemonic-derived)', mnemonic: 'BIP-39 mnemonic (24 words, only if generated or provided)', file: 'Path where wallet file was saved', diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index edde035e..9bc32540 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -87,11 +87,26 @@ export const walletDefinition: CommandDefinition = { 'midnight wallet protect', ], jsonFields: { - name: 'Wallet name', - address: 'Wallet address (bech32m)', - network: 'Network name', - active: 'Whether this is the active wallet', - wallets: 'Array of wallet info objects (list only)', + name: 'Wallet name (generate, info, seed)', + active: 'Whether this is the active wallet (generate, use, info)', + network: 'Network the address is for (info, slim output over MCP)', + address: 'Unshielded address on that network (info, slim output over MCP)', + shieldedAddress: 'Shielded address on that network, or null before the first sync (info, slim output over MCP)', + addresses: 'Per-network unshielded addresses { preprod, preview, undeployed } (generate, info)', + shieldedAddresses: 'Per-network shielded addresses { preprod, preview, undeployed } (generate, info)', + activeAddress: 'Unshielded address on the active network (generate, info)', + activeNetwork: 'The active network (generate, list, info)', + createdAt: 'ISO 8601 creation timestamp (generate, info)', + file: 'Wallet file path (generate, info)', + seed: 'Hex-encoded seed (generate, seed)', + mnemonic: 'BIP-39 mnemonic, 24 words, when the wallet has one (generate, seed)', + entropy: 'The 32-byte BIP-39 entropy (seed with --entropy)', + wallets: 'Array of wallet info objects (list)', + wallet: 'The wallet acted on (use, remove)', + removed: 'true once the wallet is removed (remove)', + sealed: 'Wallets encrypted by this run (protect)', + alreadySealed: 'Wallets that were already encrypted (protect)', + accounts: "What protect did to grant's account records (protect)", }, }, intro: { brief: 'Manage named wallets', order: 1 }, From 4b1bd57467031292f1e244023a4ea9a2f6840bff Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:57:32 -0800 Subject: [PATCH 18/88] Skills: the server's text says only what is true for every install skill/full said every CLI command is an MCP tool and pointed to mn status, which isn't a command; both skills named other packages' tools as examples and told agents only transfers are confirmed. - The confirmed tools (both skills' safety rules and the manual's confirmation flow) and the commands no tool runs come from the registry. - What each package does, the localnet refusal and the WASM Dust note are the packages' own lines, gone with the package. - A package may add sections of its own to the three texts, each after one the text has (or another package added). - References name mn help --json instead of mn status. --- docs/SKILL-CORE.md | 10 +++-- docs/SKILL.md | 24 +++++++--- src/__tests__/agent-guidance.test.ts | 66 +++++++++++++++++++++++++++- src/commands/connect.guidance.ts | 7 +++ src/commands/contract.guidance.ts | 7 +++ src/commands/dev.guidance.ts | 23 ++++++++++ src/commands/grant.guidance.ts | 7 +++ src/commands/wallet.guidance.ts | 14 ++++++ src/lib/agent-guidance.ts | 36 +++++++++++++++ src/lib/agent-manual.ts | 26 ++++++++--- src/lib/mcp/skills.ts | 55 ++++++++++++++++------- 11 files changed, 243 insertions(+), 32 deletions(-) diff --git a/docs/SKILL-CORE.md b/docs/SKILL-CORE.md index a1a83ce0..0a7c25c7 100644 --- a/docs/SKILL-CORE.md +++ b/docs/SKILL-CORE.md @@ -2,7 +2,9 @@ You have access to the `midnight-wallet-cli` MCP server. This is the **core** skill — intent routing and non-negotiable safety rules. Fetch `midnight-wallet://skill/full` on demand for canonical multi-step flows, error-recovery recipes, concept primers (NIGHT, DUST, shielded vs unshielded), network selection, and deeper context. -**Ledger 9 only.** This build refuses a chain still on ledger 8 (preview and preprod today; those stay on `midnight-wallet-cli` 0.5.x) and refuses `midnight_localnet_up` (no published ledger-9 indexer image yet). The user runs a ledger-9 stack and points mn at it; details in `/full`. +**Ledger 9 only.** This build refuses a chain still on ledger 8 (preview and preprod today; those stay on `midnight-wallet-cli` 0.5.x). The user runs a ledger-9 stack and points mn at it; details in `/full`. + +`midnight_localnet_up` is refused on this build: no published indexer image runs ledger 9 yet. ## Intent routing (natural language → tool) @@ -33,12 +35,12 @@ You have access to the `midnight-wallet-cli` MCP server. This is the **core** sk ## Safety rules (non-negotiable) -- **Read tools** (`readOnlyHint: true`) — safe to call without user consent. Examples: balance, info, list, status, address derivation. -- **Destructive tools** (`destructiveHint: true`) — require explicit user consent before calling. Examples: transfer, airdrop, dust register, wallet generate, wallet remove, cache clear, localnet down. +- **Read tools** (`readOnlyHint: true`) — safe to call without user consent. +- **Destructive tools** (`destructiveHint: true`) — require explicit user consent before calling. - **Open-world tools** (`openWorldHint: true`) — touch the network/chain/Docker. Can fail non-deterministically; retry is usually safe for reads, risky for writes. - **Never** auto-execute a fund-moving operation. Always describe amount + recipient + network first. - **Never** invent a mnemonic, seed, or private key. If the user needs one, call `midnight_wallet_generate`. -- **Transfers use a two-step confirmation token.** `midnight_transfer` returns a pending token + description; you must show the description verbatim and then call `midnight_confirm_operation({ token })` only after the user explicitly says yes. Full flow in `midnight-wallet://skill/full`. +- **Some tools use a two-step confirmation token**: `midnight_wallet_generate`, `midnight_wallet_remove`, `midnight_transfer`, `midnight_contract_deploy`, `midnight_contract_call`, `midnight_grant_deploy`, `midnight_grant_deposit`, `midnight_grant_issue`, `midnight_grant_revoke`, `midnight_grant_revoke_all`. The first call returns a pending token + description and does nothing else; show the description verbatim, and call `midnight_confirm_operation({ token })` only after the user explicitly says yes. (`midnight_wallet_generate` asks only with `force: true`, which replaces a wallet.) Full flow in `midnight-wallet://skill/full`. ## When to fetch the full skill diff --git a/docs/SKILL.md b/docs/SKILL.md index 8ec89785..843dfa80 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -2,11 +2,21 @@ You have access to the `midnight-wallet-cli` MCP server. This document teaches you how to use it well. Read it once at the start of a session; use it as reference throughout. -> **Ledger 9 only.** This build speaks ledger 9 only. A chain still on ledger 8 (preview and preprod today) is refused up front with an error saying so: tell the user to use `midnight-wallet-cli` 0.5.x for it, don't retry. `midnight_localnet_up` is refused too, because no published indexer image runs ledger 9 yet. The user runs a ledger-9 stack themselves; on the default ports (node 9944, indexer 8088, proof server 6300) `undeployed` reaches it with no configuration, otherwise set its URLs with `midnight_config_set` (keys `node`, `indexer-ws`, `proof-server`) or pass `--node` / `--indexer-ws` / `--proof-server` on the CLI. +> **Ledger 9 only.** This build speaks ledger 9 only. A chain still on ledger 8 (preview and preprod today) is refused up front with an error saying so: tell the user to use `midnight-wallet-cli` 0.5.x for it, don't retry. The user runs a ledger-9 stack themselves; on the default ports (node 9944, indexer 8088, proof server 6300) `undeployed` reaches it with no configuration, otherwise set its URLs with `midnight_config_set` (keys `node`, `indexer-ws`, `proof-server`) or pass `--node` / `--indexer-ws` / `--proof-server` on the CLI. + +> `midnight_localnet_up` is refused on this build, because no published indexer image runs ledger 9 yet. ## What you can do with this CLI -Manage wallets, check balances, transfer NIGHT tokens, register dust (fee token), manage a local Midnight network, act as a fee wallet for an agent's dApp transactions (`mn serve --approve-fees`), and deploy/call/inspect Compact smart contracts — all on behalf of the user. Every CLI command is also an MCP tool. +Act on the user's behalf on Midnight, through what the installed packages bring: + +- Manage wallets, check balances, transfer NIGHT (unshielded or shielded) and register Dust, the fee token. +- Deploy, call, inspect and read Compact smart contracts, and read the chain's block limits. +- Serve a wallet to a dApp over the DApp connector, including as a fee wallet for an agent's transactions (`mn serve --approve-fees`). +- Scaffold and run a dApp's end-to-end tests, and manage a local Midnight network. +- Deploy the wallet's account, fund it, and issue and revoke the grants that let an agent spend from it. + +Most commands are MCP tools (`tools/list` shows each, and what it takes). These have none, and the user runs them in their own terminal: `mn generate`, `mn serve`, `mn dev`, `mn help`, `mn manual`; some subcommands have none either. ## Core concepts (teach these accurately) @@ -118,11 +128,12 @@ Running a suite is a CLI command, not an MCP tool: `mn test run --suite ` ## Safety rules (non-negotiable) -- **Read tools** (`readOnlyHint: true`) — safe to call without user consent. Examples: balance, info, list, status, address derivation. -- **Destructive tools** (`destructiveHint: true`) — require explicit user consent before calling. Examples: transfer, airdrop, dust register, wallet generate, wallet remove, cache clear, localnet down. +- **Read tools** (`readOnlyHint: true`) — safe to call without user consent. +- **Destructive tools** (`destructiveHint: true`) — require explicit user consent before calling. - **Open-world tools** (`openWorldHint: true`) — touch the network/chain/Docker. Can fail non-deterministically; retry is usually safe for reads, risky for writes. - **Never** auto-execute a fund-moving operation. Always describe amount + recipient + network first. - **Never** invent a mnemonic, seed, or private key. If the user needs one, call `midnight_wallet_generate`. +- **Some tools use a two-step confirmation token**: `midnight_wallet_generate`, `midnight_wallet_remove`, `midnight_transfer`, `midnight_contract_deploy`, `midnight_contract_call`, `midnight_grant_deploy`, `midnight_grant_deposit`, `midnight_grant_issue`, `midnight_grant_revoke`, `midnight_grant_revoke_all`. The first call returns a pending token + description and does nothing else; show the description verbatim, and call `midnight_confirm_operation({ token })` only after the user explicitly says yes. (`midnight_wallet_generate` asks only with `force: true`, which replaces a wallet.) ## Error recovery recipes @@ -166,11 +177,12 @@ Every MCP tool error returns `{ error: true, code: , message: .json`). -- Not an instant-sync tool for a first-time wallet on a hosted network. First run replays the chain's event history; the CLI caches state after that so repeat runs are fast. On this ledger-9 build dust priming always runs in WASM (the native accelerator is built for ledger 8 and is not used), so a cold prime takes minutes, not seconds. +- Not an instant-sync tool for a first-time wallet on a hosted network. First run replays the chain's event history; the CLI caches state after that so repeat runs are fast. - Not a contract compiler. The project's `package.json` should expose a `compact` script (Midnight convention, e.g. `"compact": "compact compile src/foo.compact src/managed/foo"`) or a `compile` script as a generic fallback. `mn dev` detects whichever is present; create-mn-app and midnight-starship templates ship with the `compact` script already wired. +- Not quick to prime Dust on a hosted network, on this ledger-9 build: priming always runs in WASM (the native accelerator is built for ledger 8 and is not used), so a cold prime takes minutes, not seconds. ## Authoritative references - `mn help ` — per-command usage and flags. - `mn help --agent` — structured reference manual for AI clients. -- `mn status` — live network health (indexer, node, proof server). +- `mn help --json` — every command's usage, flags and JSON fields, as JSON. diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index cb6310c0..0c56d6d2 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -15,7 +15,7 @@ import { type CommandPackage, type CommandRegistry, } from '../lib/command-definition.ts'; -import { GuidanceError, assembleGuidance, type GuidancePiece, type GuidanceText } from '../lib/agent-guidance.ts'; +import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '../lib/agent-guidance.ts'; import { AGENT_MANUAL_SECTIONS, TOOL_GROUPS, agentManual } from '../lib/agent-manual.ts'; import { SKILL_CORE_SECTIONS, SKILL_FULL_SECTIONS, skillCore, skillFull } from '../lib/mcp/skills.ts'; import { listedTools } from '../lib/mcp/registry-tools.ts'; @@ -60,6 +60,70 @@ describe('assembleGuidance', () => { }); }); +describe('sections a package adds', () => { + const added = (name: string, after: string, text: GuidanceText = 'skill-core') => ({ text, name, after }); + + it('follow the section they name, several after one in the order given, each followed by its own', () => { + expect(sectionsWithAdded('skill-core', ['a', 'b'], [added('x', 'a'), added('y', 'a'), added('z', 'x'), added('w', 'b', 'skill-full')])).toStrictEqual(['a', 'x', 'z', 'y', 'b']); + }); + + it('refuse a section added twice, or over one the text has', () => { + expect(() => sectionsWithAdded('skill-core', ['a'], [added('x', 'a'), added('x', 'a')])).toThrow(GuidanceError); + expect(() => sectionsWithAdded('skill-core', ['a', 'b'], [added('b', 'a')])).toThrow(/"b" of skill-core is added twice, or over one it has/); + }); + + it('refuse one placed after a section the text has not', () => { + expect(() => sectionsWithAdded('skill-core', ['a'], [added('x', 'nope')])).toThrow(/No section of skill-core is called "nope", which "x" should follow/); + }); + + it('reach the skills and the manual with the package\'s pieces in them', () => { + const plugin: CommandPackage = { + name: 'plugin', + commands: [], + guidance: { + sections: [added('plugin-notes', 'safety-rules'), added('plugin-notes', 'secrets', 'skill-full'), added('plugin-notes', 'overview', 'agent-manual')], + pieces: [ + piece('plugin-notes', 0, '## Plugin notes (core)\n'), + piece('plugin-notes', 0, '## Plugin notes (full)\n', 'skill-full'), + piece('plugin-notes', 0, 'PLUGIN NOTES\n', 'agent-manual'), + ], + }, + }; + const registry = createPackageRegistry([...installedCommands.packages, plugin], installedCommands.globalFlags, installedCommands.globalFlagsHelp); + const core = skillCore(registry); + expect(core.indexOf('## Plugin notes (core)')).toBeGreaterThan(core.indexOf('## Safety rules')); + expect(core.indexOf('## Plugin notes (core)')).toBeLessThan(core.indexOf('## When to fetch')); + expect(skillFull(registry)).toContain('## Plugin notes (full)'); + expect(agentManual(registry)).toContain('PLUGIN NOTES'); + }); +}); + +describe('what the skills say from the registry', () => { + it('names every confirmed tool in both skills\' safety rules, and the manual\'s confirmation flow', () => { + const confirmed = installedCommands.tools.filter((tool) => tool.confirmation !== undefined).map((tool) => tool.name); + expect(confirmed.length).toBeGreaterThan(1); + for (const text of [skillCore(installedCommands), skillFull(installedCommands)]) { + const rule = text.split('\n').find((line) => line.startsWith('- **Some tools use a two-step confirmation token**'))!; + for (const name of confirmed) expect(rule, name).toContain(`\`${name}\``); + } + const flow = agentManual(installedCommands).split('TWO-STEP CONFIRMATION FLOW')[1]!.split('MCP RESOURCES')[0]!; + for (const name of confirmed) expect(flow, name).toContain(` ${name}\n`); + }); + + it('names the commands no tool runs, and says no more that every command is a tool', () => { + const full = skillFull(installedCommands); + expect(full).not.toContain('Every CLI command is also an MCP tool'); + expect(full).not.toContain('mn status'); + expect(full).toContain('the user runs them in their own terminal: `mn generate`, `mn serve`, `mn dev`, `mn help`, `mn manual`'); + }); + + it('leaves a package\'s own lines out with the package', () => { + expect(skillFull(installedCommands)).toContain('Deploy the wallet\'s account, fund it'); + expect(skillFull(withoutPackage('grant'))).not.toContain('Deploy the wallet\'s account, fund it'); + expect(skillFull(withoutPackage('grant'))).not.toContain('midnight_grant_issue'); + }); +}); + describe('createPackageRegistry', () => { let nextPlace = 0; const command = (name: string, tools: string[] = [], order = ++nextPlace): CommandDefinition => ({ diff --git a/src/commands/connect.guidance.ts b/src/commands/connect.guidance.ts index 66601c7c..271494b4 100644 --- a/src/commands/connect.guidance.ts +++ b/src/commands/connect.guidance.ts @@ -6,6 +6,13 @@ import type { PackageGuidance } from '../lib/agent-guidance.ts'; export const connectGuidance: PackageGuidance = { pieces: [ + { + text: 'skill-full', + section: 'what-you-can-do', + order: 30, + body: `- Serve a wallet to a dApp over the DApp connector, including as a fee wallet for an agent's transactions (\`mn serve --approve-fees\`). +`, + }, { text: 'agent-manual', section: 'dapp-connector', diff --git a/src/commands/contract.guidance.ts b/src/commands/contract.guidance.ts index d66dce61..77c5be9f 100644 --- a/src/commands/contract.guidance.ts +++ b/src/commands/contract.guidance.ts @@ -6,6 +6,13 @@ import type { PackageGuidance } from '../lib/agent-guidance.ts'; export const contractGuidance: PackageGuidance = { pieces: [ + { + text: 'skill-full', + section: 'what-you-can-do', + order: 20, + body: `- Deploy, call, inspect and read Compact smart contracts, and read the chain's block limits. +`, + }, { text: 'agent-manual', section: 'smart-contracts', diff --git a/src/commands/dev.guidance.ts b/src/commands/dev.guidance.ts index 55e769ed..913cff30 100644 --- a/src/commands/dev.guidance.ts +++ b/src/commands/dev.guidance.ts @@ -6,6 +6,29 @@ import type { PackageGuidance } from '../lib/agent-guidance.ts'; export const devGuidance: PackageGuidance = { pieces: [ + { + text: 'skill-full', + section: 'what-you-can-do', + order: 40, + body: `- Scaffold and run a dApp's end-to-end tests, and manage a local Midnight network. +`, + }, + { + text: 'skill-core', + section: 'title', + order: 10, + body: `\`midnight_localnet_up\` is refused on this build: no published indexer image runs ledger 9 yet. + +`, + }, + { + text: 'skill-full', + section: 'title', + order: 10, + body: `> \`midnight_localnet_up\` is refused on this build, because no published indexer image runs ledger 9 yet. + +`, + }, { text: 'agent-manual', section: 'e2e-testing', diff --git a/src/commands/grant.guidance.ts b/src/commands/grant.guidance.ts index e895ac57..9ae61ba6 100644 --- a/src/commands/grant.guidance.ts +++ b/src/commands/grant.guidance.ts @@ -6,6 +6,13 @@ import type { PackageGuidance } from '../lib/agent-guidance.ts'; export const grantGuidance: PackageGuidance = { pieces: [ + { + text: 'skill-full', + section: 'what-you-can-do', + order: 50, + body: `- Deploy the wallet's account, fund it, and issue and revoke the grants that let an agent spend from it. +`, + }, { text: 'agent-manual', section: 'grants', diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index 15018469..2942ff21 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -7,6 +7,20 @@ import type { PackageGuidance } from '../lib/agent-guidance.ts'; export const walletGuidance: PackageGuidance = { pieces: [ + { + text: 'skill-full', + section: 'what-you-can-do', + order: 10, + body: `- Manage wallets, check balances, transfer NIGHT (unshielded or shielded) and register Dust, the fee token. +`, + }, + { + text: 'skill-full', + section: 'not-this-cli', + order: 20, + body: `- Not quick to prime Dust on a hosted network, on this ledger-9 build: priming always runs in WASM (the native accelerator is built for ledger 8 and is not used), so a cold prime takes minutes, not seconds. +`, + }, { text: 'agent-manual', section: 'shielded-transactions', diff --git a/src/lib/agent-guidance.ts b/src/lib/agent-guidance.ts index cc267b26..54df86a0 100644 --- a/src/lib/agent-guidance.ts +++ b/src/lib/agent-guidance.ts @@ -36,9 +36,19 @@ export interface ToolsTableRow { readonly params?: readonly string[]; } +/** A section a package adds to a text, for its own pieces: placed right after a section the text has. */ +export interface GuidanceSection { + readonly text: GuidanceText; + readonly name: string; + /** The section it follows: one of the text's own, or one another package adds. */ + readonly after: string; +} + /** What a package tells agents. */ export interface PackageGuidance { readonly pieces: readonly GuidancePiece[]; + /** Sections it adds to the texts, beyond the ones their assemblers own. */ + readonly sections?: readonly GuidanceSection[]; readonly toolsTable?: readonly ToolsTableRow[]; } @@ -55,6 +65,32 @@ export function unplacedPieces(text: GuidanceText, sections: readonly string[], return pieces.filter((piece) => piece.text === text && !sections.includes(piece.section)); } +/** + * A text's sections: its skeleton's, each followed by the sections packages + * add after it (several after one in the order given, each followed by its + * own). Refuses a section added twice or over one the text has, and one + * placed after a section the text doesn't have. + */ +export function sectionsWithAdded(text: GuidanceText, skeleton: readonly string[], added: readonly GuidanceSection[]): string[] { + const own = added.filter((section) => section.text === text); + const names = new Set(skeleton); + for (const { name } of own) { + if (names.has(name)) throw new GuidanceError(`Section "${name}" of ${text} is added twice, or over one it has`); + names.add(name); + } + const sections: string[] = []; + const place = (name: string): void => { + sections.push(name); + for (const next of own.filter((section) => section.after === name)) place(next.name); + }; + skeleton.forEach(place); + const unplaced = own.filter((section) => !sections.includes(section.name)); + if (unplaced.length > 0) { + throw new GuidanceError(`No section of ${text} is called ${unplaced.map((section) => `"${section.after}"`).join(', ')}, which ${unplaced.map((section) => `"${section.name}"`).join(', ')} should follow`); + } + return sections; +} + /** Refuses two pieces in one place of one section. */ export function assertDistinctPlaces(pieces: readonly GuidancePiece[]): void { const seen = new Set(); diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index 0d090b05..767018aa 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -5,7 +5,7 @@ // registry's tools, each in the topic group its package's row names. import { PKG_VERSION } from './pkg.ts'; -import { GuidanceError, assembleGuidance, type GuidancePiece, type ToolsTableRow } from './agent-guidance.ts'; +import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type ToolsTableRow } from './agent-guidance.ts'; import { commandHelpSpecs, type CommandRegistry, type RegisteredTool } from './command-definition.ts'; /** The manual's sections, in order. */ @@ -251,8 +251,8 @@ without hardcoding per-tool rules: text: 'agent-manual', section: 'two-step-confirmation', order: 0, - body: `TWO-STEP CONFIRMATION FLOW (midnight_transfer) -────────────────────────────────────────────── + body: `TWO-STEP CONFIRMATION FLOW +────────────────────────── midnight_transfer does NOT execute on the first call. It returns a pending token that the agent must show to the user for consent, then redeem via @@ -266,6 +266,15 @@ midnight_confirm_operation to actually execute. Tokens are single-use and expire after 5 minutes. +`, + }, + { + text: 'agent-manual', + section: 'two-step-confirmation', + order: 20, + body: `Every tool that moves funds, changes an account or deletes a seed works +the same way (midnight_wallet_generate only with force: true): + `, }, { @@ -316,8 +325,15 @@ resources/list. Ground responses in these instead of training-data guesses. }, ]; +/** The tools behind the two-step confirmation, one per line, from the registry. */ +function confirmedTools(registry: CommandRegistry): GuidancePiece { + const names = registry.tools.filter((tool) => tool.confirmation !== undefined).map((tool) => ` ${tool.name}\n`); + return { text: 'agent-manual', section: 'two-step-confirmation', order: 30, body: `${names.join('')}\n` }; +} + /** The `help --agent` manual for the installed packages. */ export function agentManual(registry: CommandRegistry): string { - const pieces = [overview(), jsonSchemas(registry), mcpTools(registry), ...SHELL_PIECES, ...registry.packages.flatMap((pkg) => pkg.guidance.pieces)]; - return assembleGuidance('agent-manual', AGENT_MANUAL_SECTIONS, pieces); + const pieces = [overview(), jsonSchemas(registry), mcpTools(registry), confirmedTools(registry), ...SHELL_PIECES, ...registry.packages.flatMap((pkg) => pkg.guidance.pieces)]; + const added = registry.packages.flatMap((pkg) => pkg.guidance.sections ?? []); + return assembleGuidance('agent-manual', sectionsWithAdded('agent-manual', AGENT_MANUAL_SECTIONS, added), pieces); } diff --git a/src/lib/mcp/skills.ts b/src/lib/mcp/skills.ts index 94c43e41..1426fb6f 100644 --- a/src/lib/mcp/skills.ts +++ b/src/lib/mcp/skills.ts @@ -6,7 +6,7 @@ // at each resources/read; scripts/write-skill-docs.ts writes the same text to // docs/SKILL-CORE.md and docs/SKILL.md, the copies the README links to. -import { assembleGuidance, type GuidancePiece } from '../agent-guidance.ts'; +import { assembleGuidance, sectionsWithAdded, type GuidancePiece } from '../agent-guidance.ts'; import type { CommandRegistry } from '../command-definition.ts'; /** skill/core's sections, in order. */ @@ -38,7 +38,7 @@ const SERVER_PIECES: readonly GuidancePiece[] = [ You have access to the \`midnight-wallet-cli\` MCP server. This is the **core** skill — intent routing and non-negotiable safety rules. Fetch \`midnight-wallet://skill/full\` on demand for canonical multi-step flows, error-recovery recipes, concept primers (NIGHT, DUST, shielded vs unshielded), network selection, and deeper context. -**Ledger 9 only.** This build refuses a chain still on ledger 8 (preview and preprod today; those stay on \`midnight-wallet-cli\` 0.5.x) and refuses \`midnight_localnet_up\` (no published ledger-9 indexer image yet). The user runs a ledger-9 stack and points mn at it; details in \`/full\`. +**Ledger 9 only.** This build refuses a chain still on ledger 8 (preview and preprod today; those stay on \`midnight-wallet-cli\` 0.5.x). The user runs a ledger-9 stack and points mn at it; details in \`/full\`. `, }, @@ -65,13 +65,11 @@ You have access to the \`midnight-wallet-cli\` MCP server. This is the **core** order: 0, body: `## Safety rules (non-negotiable) -- **Read tools** (\`readOnlyHint: true\`) — safe to call without user consent. Examples: balance, info, list, status, address derivation. -- **Destructive tools** (\`destructiveHint: true\`) — require explicit user consent before calling. Examples: transfer, airdrop, dust register, wallet generate, wallet remove, cache clear, localnet down. +- **Read tools** (\`readOnlyHint: true\`) — safe to call without user consent. +- **Destructive tools** (\`destructiveHint: true\`) — require explicit user consent before calling. - **Open-world tools** (\`openWorldHint: true\`) — touch the network/chain/Docker. Can fail non-deterministically; retry is usually safe for reads, risky for writes. - **Never** auto-execute a fund-moving operation. Always describe amount + recipient + network first. - **Never** invent a mnemonic, seed, or private key. If the user needs one, call \`midnight_wallet_generate\`. -- **Transfers use a two-step confirmation token.** \`midnight_transfer\` returns a pending token + description; you must show the description verbatim and then call \`midnight_confirm_operation({ token })\` only after the user explicitly says yes. Full flow in \`midnight-wallet://skill/full\`. - `, }, { @@ -95,7 +93,7 @@ You have access to the \`midnight-wallet-cli\` MCP server. This is the **core** You have access to the \`midnight-wallet-cli\` MCP server. This document teaches you how to use it well. Read it once at the start of a session; use it as reference throughout. -> **Ledger 9 only.** This build speaks ledger 9 only. A chain still on ledger 8 (preview and preprod today) is refused up front with an error saying so: tell the user to use \`midnight-wallet-cli\` 0.5.x for it, don't retry. \`midnight_localnet_up\` is refused too, because no published indexer image runs ledger 9 yet. The user runs a ledger-9 stack themselves; on the default ports (node 9944, indexer 8088, proof server 6300) \`undeployed\` reaches it with no configuration, otherwise set its URLs with \`midnight_config_set\` (keys \`node\`, \`indexer-ws\`, \`proof-server\`) or pass \`--node\` / \`--indexer-ws\` / \`--proof-server\` on the CLI. +> **Ledger 9 only.** This build speaks ledger 9 only. A chain still on ledger 8 (preview and preprod today) is refused up front with an error saying so: tell the user to use \`midnight-wallet-cli\` 0.5.x for it, don't retry. The user runs a ledger-9 stack themselves; on the default ports (node 9944, indexer 8088, proof server 6300) \`undeployed\` reaches it with no configuration, otherwise set its URLs with \`midnight_config_set\` (keys \`node\`, \`indexer-ws\`, \`proof-server\`) or pass \`--node\` / \`--indexer-ws\` / \`--proof-server\` on the CLI. `, }, @@ -105,7 +103,7 @@ You have access to the \`midnight-wallet-cli\` MCP server. This document teaches order: 0, body: `## What you can do with this CLI -Manage wallets, check balances, transfer NIGHT tokens, register dust (fee token), manage a local Midnight network, act as a fee wallet for an agent's dApp transactions (\`mn serve --approve-fees\`), and deploy/call/inspect Compact smart contracts — all on behalf of the user. Every CLI command is also an MCP tool. +Act on the user's behalf on Midnight, through what the installed packages bring: `, }, @@ -193,12 +191,11 @@ Midnight shut its own preprod indexer down on 2026-10-09. Blockfrost serves prep order: 0, body: `## Safety rules (non-negotiable) -- **Read tools** (\`readOnlyHint: true\`) — safe to call without user consent. Examples: balance, info, list, status, address derivation. -- **Destructive tools** (\`destructiveHint: true\`) — require explicit user consent before calling. Examples: transfer, airdrop, dust register, wallet generate, wallet remove, cache clear, localnet down. +- **Read tools** (\`readOnlyHint: true\`) — safe to call without user consent. +- **Destructive tools** (\`destructiveHint: true\`) — require explicit user consent before calling. - **Open-world tools** (\`openWorldHint: true\`) — touch the network/chain/Docker. Can fail non-deterministically; retry is usually safe for reads, risky for writes. - **Never** auto-execute a fund-moving operation. Always describe amount + recipient + network first. - **Never** invent a mnemonic, seed, or private key. If the user needs one, call \`midnight_wallet_generate\`. - `, }, { @@ -240,7 +237,7 @@ Every MCP tool error returns \`{ error: true, code: , message: .json\`). -- Not an instant-sync tool for a first-time wallet on a hosted network. First run replays the chain's event history; the CLI caches state after that so repeat runs are fast. On this ledger-9 build dust priming always runs in WASM (the native accelerator is built for ledger 8 and is not used), so a cold prime takes minutes, not seconds. +- Not an instant-sync tool for a first-time wallet on a hosted network. First run replays the chain's event history; the CLI caches state after that so repeat runs are fast. `, }, { @@ -258,23 +255,49 @@ Every MCP tool error returns \`{ error: true, code: , message: \` — per-command usage and flags. - \`mn help --agent\` — structured reference manual for AI clients. -- \`mn status\` — live network health (indexer, node, proof server). +- \`mn help --json\` — every command's usage, flags and JSON fields, as JSON. `, }, ]; +/** The tools behind the two-step confirmation, as a list of names in the registry's order. */ +const confirmedTools = (registry: CommandRegistry): string => + registry.tools.filter((tool) => tool.confirmation !== undefined).map((tool) => `\`${tool.name}\``).join(', '); + +/** + * What the skills say from the registry: the safety rule on the confirmed + * tools, in both, and in skill/full the commands no tool runs, which the user + * runs in a terminal. + */ +function registryPieces(registry: CommandRegistry): GuidancePiece[] { + const confirmation = `- **Some tools use a two-step confirmation token**: ${confirmedTools(registry)}. The first call returns a pending token + description and does nothing else; show the description verbatim, and call \`midnight_confirm_operation({ token })\` only after the user explicitly says yes. (\`midnight_wallet_generate\` asks only with \`force: true\`, which replaces a wallet.)`; + const terminalOnly = registry.commands.filter((command) => command.help !== undefined && (command.mcp?.tools.length ?? 0) === 0).map((command) => `\`mn ${command.name}\``); + return [ + { text: 'skill-core', section: 'safety-rules', order: 500, body: `${confirmation} Full flow in \`midnight-wallet://skill/full\`.\n\n` }, + { text: 'skill-full', section: 'safety-rules', order: 500, body: `${confirmation}\n\n` }, + { + text: 'skill-full', + section: 'what-you-can-do', + order: 1000, + body: `\nMost commands are MCP tools (\`tools/list\` shows each, and what it takes). ${terminalOnly.length === 0 ? '' : `These have none, and the user runs them in their own terminal: ${terminalOnly.join(', ')}; some subcommands have none either.`}\n\n`, + }, + ]; +} + function piecesOf(registry: CommandRegistry): GuidancePiece[] { - return [...SERVER_PIECES, ...registry.packages.flatMap((pkg) => pkg.guidance.pieces)]; + return [...SERVER_PIECES, ...registryPieces(registry), ...registry.packages.flatMap((pkg) => pkg.guidance.pieces)]; } +const addedSections = (registry: CommandRegistry) => registry.packages.flatMap((pkg) => pkg.guidance.sections ?? []); + /** skill/core for the installed packages. */ export function skillCore(registry: CommandRegistry): string { - return assembleGuidance('skill-core', SKILL_CORE_SECTIONS, piecesOf(registry)); + return assembleGuidance('skill-core', sectionsWithAdded('skill-core', SKILL_CORE_SECTIONS, addedSections(registry)), piecesOf(registry)); } /** skill/full (and the legacy skill URI) for the installed packages. */ export function skillFull(registry: CommandRegistry): string { - return assembleGuidance('skill-full', SKILL_FULL_SECTIONS, piecesOf(registry)); + return assembleGuidance('skill-full', sectionsWithAdded('skill-full', SKILL_FULL_SECTIONS, addedSections(registry)), piecesOf(registry)); } /** The repository's copies of the skills, by path from its root, and what writes each. */ From 39395a10ec79a6b2c173ee45692e9bb1c9058ba6 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 17:59:52 -0800 Subject: [PATCH 19/88] The README's command table is generated from the registry It lacked grant. It is now written between markers by npm run readme-commands, one row per command help lists, with its help's usage and description, and a test fails when the README differs. The table says less than the hand-written one did (per-subcommand rows, flag notes); mn help and mn manual carry those. --- README.md | 49 ++++++++++++--------------- package.json | 3 +- scripts/check-layering.mjs | 2 +- scripts/write-readme-commands.ts | 15 ++++++++ src/__tests__/readme-commands.test.ts | 36 ++++++++++++++++++++ src/lib/readme-commands.ts | 27 +++++++++++++++ 6 files changed, 103 insertions(+), 29 deletions(-) create mode 100644 scripts/write-readme-commands.ts create mode 100644 src/__tests__/readme-commands.test.ts create mode 100644 src/lib/readme-commands.ts diff --git a/README.md b/README.md index 605e7840..947010f0 100644 --- a/README.md +++ b/README.md @@ -28,35 +28,30 @@ This installs two commands: `midnight` (or `mn` for short) and `midnight-wallet- ## Commands + | Command | Description | |---------|-------------| -| `midnight wallet generate ` | Create a named wallet and set it as active | -| `midnight wallet list` | List all wallets with active marker | -| `midnight wallet use ` | Set the active wallet | -| `midnight wallet info [name]` | Show wallet details | -| `midnight wallet remove ` | Remove a wallet | -| `midnight info` | Display wallet address, network, creation date | -| `midnight balance [address]` | Check unshielded + shielded NIGHT balance (`--force-shielded` to sync shielded on preview/preprod, off by default) | -| `midnight transfer ` | Send NIGHT tokens (`--shielded` for shielded; `--force-shielded` to allow it on preview/preprod) | -| `midnight airdrop ` | Fund a wallet or raw address from genesis (`--shielded` for shielded, undeployed only) | -| `midnight dust register` | Register NIGHT UTXOs for dust (fee token) generation | -| `midnight dust status` | Check dust registration status and balance | -| `midnight dust export` | Emit a restorable dust snapshot for fast warm-restore (ledger-9 snapshot on this build) | -| `midnight address --seed ` | Derive an address from a seed | -| `midnight genesis-address` | Show the genesis wallet address | -| `midnight inspect-cost` | Display current block cost limits | -| `midnight serve` | Start DApp Connector server (WebSocket JSON-RPC); `--approve-fees` runs it as a fee wallet for an agent | -| `midnight contract inspect` | Show circuits, witnesses, and types for a compiled contract | -| `midnight contract deploy` | Deploy a contract to the network (`--secret-key <64-hex>` seeds a caller-chosen initial private-state secret for constructors that derive their owner from `public_key(secret_key())`; passed via env to the deploy subprocess, never written to disk) | -| `midnight contract call` | Call a circuit on a deployed contract | -| `midnight contract state` | Read ledger state of a deployed contract | -| `midnight dev` | Contract dev loop — watcher auto-compiles on save; `[t]` runs tests, `[d]` deploys (on this build it uses a ledger-9 stack you run, at the configured endpoints) | -| `midnight test create/run/list/results` | Generate and run E2E tests for Midnight dApps | -| `midnight config get/set/unset` | Manage persistent config (network, wallet, endpoints) | -| `midnight cache clear` | Clear wallet state cache | -| `midnight localnet up/stop/down/status/logs/clean` | Manage a local Midnight network via Docker (`up` is refused on this ledger-9 build) | -| `midnight help [command]` | Show usage for all or a specific command | -| `midnight manual` | Full reference manual (every command, every flag) | +| `midnight wallet [args]` | Manage named wallets (generate, list, use, info, remove, seed, protect) | +| `midnight generate [--network ] [--seed ] [--mnemonic "..."] [--output ] [--force]` | (Deprecated — use "midnight wallet generate " instead) | +| `midnight info [--wallet ]` | Display wallet address, network, creation date (no secrets shown) | +| `midnight balance [address] [--network ] [--indexer-ws ]` | Check unshielded + shielded balance (full wallet sync) | +| `midnight address --seed [--network ] [--index ]` | Derive and display an unshielded address from a seed | +| `midnight genesis-address [--network ]` | Display the genesis wallet address (seed 0x01) for a network | +| `midnight inspect-cost [--network ] [--node ] [--indexer-ws ] [--proof-server ]` | Display the chain's current block limits, from its latest block's ledger parameters | +| `midnight airdrop [--shielded] [--wallet ]` | Fund a wallet from the genesis wallet (undeployed network only) | +| `midnight transfer [--shielded] [--wallet ] [--proof-server ] [--node ] [--indexer-ws ]` | Send NIGHT tokens to another address (unshielded or --shielded) | +| `midnight dust [--wallet ] [--seed (export only)] [--proof-server ] [--node ] [--indexer-ws ] [--no-cache (status only)]` | Register UTXOs for dust (fee token) generation, check status, or export a restorable snapshot | +| `midnight config [value] [--network ]` | Manage persistent config (default network, endpoints, etc.) | +| `midnight cache clear [--network ] [--wallet ]` | Manage wallet state cache (clear cached sync data) | +| `midnight serve [--port ] [--wallet ] [--network ] [--proof-server ] [--node ] [--indexer-ws ] [--approve-all \| --approve-fees [--max-fee ] [--max-pending ]] [--no-auto-approve-reads] [--json]` | Start DApp Connector server over WebSocket JSON-RPC | +| `midnight test [options]` | Generate and run E2E test suites for Midnight dApps | +| `midnight dev [path]` | Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy) | +| `midnight contract [options]` | Inspect, deploy, call, and query Midnight smart contracts | +| `midnight grant [options]` | This wallet's account, and the grants that let an agent spend from it (experimental) | +| `midnight localnet ` | Manage a local Midnight network via Docker Compose (up is refused on this ledger-9 build) | +| `midnight help [command]` | Show usage for all commands or a specific command | +| `midnight manual [--no-pager] [--raw] [--json]` | Full reference manual (long form, paged through $PAGER) | + ## Quick Start diff --git a/package.json b/package.json index 8a920d1b..3d545bbe 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,8 @@ "test:live": "vitest run --config vitest.live.config.ts", "test:watch": "vitest", "typecheck": "tsc --noEmit", - "skill-docs": "tsx scripts/write-skill-docs.ts" + "skill-docs": "tsx scripts/write-skill-docs.ts", + "readme-commands": "tsx scripts/write-readme-commands.ts" }, "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 36c82ae4..2b6ce646 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -29,7 +29,7 @@ const HOMES = [ ['shell', /^wallet\.ts$/], // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], - ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|command-dispatch|agent-manual)\.ts$/], + ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|command-dispatch|agent-manual|readme-commands)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], diff --git a/scripts/write-readme-commands.ts b/scripts/write-readme-commands.ts new file mode 100644 index 00000000..e00bbe17 --- /dev/null +++ b/scripts/write-readme-commands.ts @@ -0,0 +1,15 @@ +// Writes the README's table of commands from the installed commands' +// definitions, between its markers. A test fails when the README differs. +// +// Usage: npm run readme-commands + +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { installedCommands } from '../src/lib/installed-commands.ts'; +import { readmeCommandTable, withReadmeCommandTable } from '../src/lib/readme-commands.ts'; + +const README = join(resolve(dirname(fileURLToPath(import.meta.url)), '..'), 'README.md'); + +writeFileSync(README, withReadmeCommandTable(readFileSync(README, 'utf8'), readmeCommandTable(installedCommands))); +process.stdout.write('wrote README.md\n'); diff --git a/src/__tests__/readme-commands.test.ts b/src/__tests__/readme-commands.test.ts new file mode 100644 index 00000000..c83ed83e --- /dev/null +++ b/src/__tests__/readme-commands.test.ts @@ -0,0 +1,36 @@ +// The README's table of commands is generated from the command registry, so +// a command can't be missing from it (grant was). When it differs, run +// `npm run readme-commands`. + +import { describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { README_COMMANDS_END, README_COMMANDS_START, readmeCommandTable, withReadmeCommandTable } from '../lib/readme-commands.ts'; + +const README = path.join(fileURLToPath(new URL('../..', import.meta.url)), 'README.md'); + +describe("the README's table of commands", () => { + it('is the generated table, byte for byte (npm run readme-commands writes it)', () => { + const readme = fs.readFileSync(README, 'utf8'); + expect(readme).toBe(withReadmeCommandTable(readme, readmeCommandTable(installedCommands))); + }); + + it('has a row for every command help lists, grant among them', () => { + const table = readmeCommandTable(installedCommands); + const listed = installedCommands.commands.filter((command) => command.help !== undefined); + expect(table.trimEnd().split('\n')).toHaveLength(listed.length + 2); + expect(table).toContain('| `midnight grant { + const table = readmeCommandTable({ commands: [{ ...installedCommands.find('config')!, help: { description: 'a | b', usage: 'midnight x ' } }] }); + expect(table).toBe('| Command | Description |\n|---------|-------------|\n| `midnight x ` | a \\| b |\n'); + }); + + it('refuses a README without the markers', () => { + expect(() => withReadmeCommandTable('# no markers\n', '')).toThrow(README_COMMANDS_START); + expect(withReadmeCommandTable(`a\n${README_COMMANDS_START}\nold\n${README_COMMANDS_END}\nb`, 'new\n')).toBe(`a\n${README_COMMANDS_START}\nnew\n${README_COMMANDS_END}\nb`); + }); +}); diff --git a/src/lib/readme-commands.ts b/src/lib/readme-commands.ts new file mode 100644 index 00000000..8a5c1646 --- /dev/null +++ b/src/lib/readme-commands.ts @@ -0,0 +1,27 @@ +// The README's table of commands, from the command registry: one row per +// command help lists, in help's order, with its help's usage and +// description. scripts/write-readme-commands.ts writes it between the +// README's markers; a test fails when the README differs. + +import type { CommandRegistry } from './command-definition.ts'; + +/** The markers around the generated table in README.md. */ +export const README_COMMANDS_START = ''; +export const README_COMMANDS_END = ''; + +/** The table, as markdown, ending with a newline. */ +export function readmeCommandTable(registry: Pick): string { + // A pipe splits a table cell, inside a code span too, unless escaped. + const cell = (text: string): string => text.replaceAll('|', '\\|'); + const rows = registry.commands.flatMap((command) => + command.help === undefined ? [] : [`| \`${cell(command.help.usage)}\` | ${cell(command.help.description)} |`]); + return ['| Command | Description |', '|---------|-------------|', ...rows].join('\n') + '\n'; +} + +/** The README with the table between its markers replaced by `table`. */ +export function withReadmeCommandTable(readme: string, table: string): string { + const start = readme.indexOf(README_COMMANDS_START); + const end = readme.indexOf(README_COMMANDS_END); + if (start === -1 || end < start) throw new Error(`README.md has no ${README_COMMANDS_START} … ${README_COMMANDS_END} markers`); + return readme.slice(0, start + README_COMMANDS_START.length) + '\n' + table + readme.slice(end); +} From d4128b967a9e3079d1c85b174abccd0220fe38d1 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:04:32 -0800 Subject: [PATCH 20/88] A node's refusal is reported with the node's reason The wallet SDK reports a refused transaction as "Transaction submission error" and keeps the node's words only among its causes, inside an Effect FiberFailure; mn reported UNKNOWN (exit 1), and the reason (an invalid Dust proof) was only in the node's log. The CLI and the MCP server now report such an error as a TransactionRefusedError, "The node refused the transaction: ", classified by the reason when a rule knows it (Custom error: 170 is INVALID_DUST_PROOF, 115 STALE_UTXO) and as TX_REJECTED (exit 6) otherwise. Retry logic still sees the SDK's own error. --- src/__tests__/sdk-errors.test.ts | 56 +++++++++++++++++++++++++++++++- src/lib/errors.ts | 16 +++++++++ src/lib/exit-codes.ts | 8 ++--- src/lib/sdk-errors.ts | 46 ++++++++++++++++++++++++++ src/mcp-server.ts | 5 ++- src/wallet.ts | 5 ++- 6 files changed, 129 insertions(+), 7 deletions(-) diff --git a/src/__tests__/sdk-errors.test.ts b/src/__tests__/sdk-errors.test.ts index ec340d6c..c3f3a45f 100644 --- a/src/__tests__/sdk-errors.test.ts +++ b/src/__tests__/sdk-errors.test.ts @@ -3,7 +3,12 @@ // (an Effect tagged error carrying tokenType), not just matching strings. import { describe, it, expect } from 'vitest'; -import { dustShortfallOf, isColdStartRace, isDustShortage, withDustShortfall } from '../lib/sdk-errors.ts'; +import { Brand, Effect } from 'effect'; +import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; +import { NodeClientError } from '@midnightntwrk/wallet-sdk/node-client/effect'; +import { dustShortfallOf, isColdStartRace, isDustShortage, nodeRefusalOf, withDustShortfall, withNodeReason } from '../lib/sdk-errors.ts'; +import { TransactionRefusedError } from '../lib/errors.ts'; +import { classifyError } from '../lib/exit-codes.ts'; /** wallet-sdk 2.0's dust InsufficientFundsError: tagged, with the token it could not balance. */ function sdkInsufficientFunds(tokenType: string): Error { @@ -137,3 +142,52 @@ describe('isColdStartRace', () => { expect(isColdStartRace(new Error('Transaction submission error'))).toBe(false); }); }); + +// A node's refusal, built as wallet-sdk 2.0 raises it: its submission +// service wraps the node client's error in a SubmissionError, and the promise +// rejects with an Effect FiberFailure that holds it. +describe("the node's reason for refusing a transaction", () => { + // The transaction's bytes, branded as the SDK brands them (its SerializedTransaction is a nominal brand it doesn't export). + type TxData = ConstructorParameters[0]['txData']; + const TX_DATA = Brand.nominal()(new Uint8Array([0])); + const refusal = (nodeError: unknown): Promise => { + const failure = Effect.runPromise(Effect.fail(new SubmissionError({ message: 'Transaction submission error', cause: nodeError }))); + failure.catch(() => {}); + return failure; + }; + const caught = (promise: Promise) => promise.catch((err: Error) => err); + + it('is found under the SDK\'s wrappers, and reported as a TransactionRefusedError classified by it', async () => { + const thrown = await caught(refusal(new NodeClientError.SubmissionError({ message: 'Transaction submission failed', txData: TX_DATA, cause: new Error('1010: Invalid Transaction: Custom error: 170') }))); + expect(thrown.message).toBe('Transaction submission error'); + expect(nodeRefusalOf(thrown)).toBe('1010: Invalid Transaction: Custom error: 170'); + const reported = withNodeReason(thrown); + expect(reported).toBeInstanceOf(TransactionRefusedError); + expect(reported.message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 170'); + expect(reported.cause).toBe(thrown); + expect(classifyError(reported)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); + // Unexplained, the same error was UNKNOWN. + expect(classifyError(thrown).errorCode).toBe('UNKNOWN'); + }); + + it("is the node client's own words when the node gave none", async () => { + const thrown = await caught(refusal(new NodeClientError.TransactionInvalidError({ message: 'Transaction is invalid and was rejected by the node', txData: TX_DATA }))); + expect(nodeRefusalOf(thrown)).toBe('Transaction is invalid and was rejected by the node'); + expect(classifyError(withNodeReason(thrown))).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); + }); + + it('classifies a reason no rule knows as TX_REJECTED, with the reason in the message', async () => { + const reported = withNodeReason(await caught(refusal(new NodeClientError.SubmissionError({ message: 'Transaction submission failed', txData: TX_DATA, cause: new Error('1010: Invalid Transaction: Custom error: 199') })))); + expect(reported.message).toContain('Custom error: 199'); + expect(classifyError(reported)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); + }); + + it('leaves any other error as it is, and a submission error with nothing under its wrapper', async () => { + const other = new Error('ECONNREFUSED'); + expect(nodeRefusalOf(other)).toBeUndefined(); + expect(withNodeReason(other)).toBe(other); + const bare = await caught(refusal(undefined)); + expect(nodeRefusalOf(bare)).toBeUndefined(); + expect(withNodeReason(bare)).toBe(bare); + }); +}); diff --git a/src/lib/errors.ts b/src/lib/errors.ts index d1dc10bd..7c0b4a5c 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -42,6 +42,22 @@ export class CancelledError extends Error { } } +/** + * The node refused a transaction, with what it said. The wallet SDK reports a + * refusal as "Transaction submission error" and keeps the node's words (the + * reason: an invalid Dust proof, a stale coin, …) only among its causes. + */ +export class TransactionRefusedError extends Error { + readonly reason: string; + + constructor(reason: string, options?: { cause?: unknown }) { + super(`The node refused the transaction: ${reason}`, options); + this.name = 'TransactionRefusedError'; + this.reason = reason; + Object.setPrototypeOf(this, TransactionRefusedError.prototype); + } +} + /** * A command that ended with a non-zero exit code without throwing (a test run * whose tests failed): the code, and the JSON result it wrote. A runner with no diff --git a/src/lib/exit-codes.ts b/src/lib/exit-codes.ts index dfb087d7..0f4b88e6 100644 --- a/src/lib/exit-codes.ts +++ b/src/lib/exit-codes.ts @@ -156,13 +156,13 @@ export function classifyError(err: Error): ClassifiedError { } // Stale UTXO — match the specific error code from the Midnight node - if (msg.includes('stale utxo') || msg.includes('error code 115') || msg.includes('errorcode: 115')) { + if (msg.includes('stale utxo') || msg.includes('error code 115') || msg.includes('custom error: 115') || msg.includes('errorcode: 115')) { return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.STALE_UTXO }; } // Invalid dust spend proof — substrate "Custom error 170". Distinct from // PROOF_FAILURE because the recovery is "clear cache" not "retry". - if (msg.includes('error 170') || msg.includes('errorcode: 170') || msg.includes('invaliddustspendproof')) { + if (msg.includes('error 170') || msg.includes('error: 170') || msg.includes('errorcode: 170') || msg.includes('invaliddustspendproof')) { return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.INVALID_DUST_PROOF }; } @@ -199,8 +199,8 @@ export function classifyError(err: Error): ClassifiedError { return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.INSUFFICIENT_BALANCE }; } - // Transaction rejected - if (msg.includes('rejected') || msg.includes('transaction failed')) { + // Transaction rejected: by the node (its words in the message, when no rule above knew them), or as the message says. + if ((err as { name?: unknown }).name === 'TransactionRefusedError' || msg.includes('rejected') || msg.includes('transaction failed')) { return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.TX_REJECTED }; } diff --git a/src/lib/sdk-errors.ts b/src/lib/sdk-errors.ts index 9c965627..fd76dcc4 100644 --- a/src/lib/sdk-errors.ts +++ b/src/lib/sdk-errors.ts @@ -3,6 +3,8 @@ // side effects, no I/O. Lives in its own file so both transfer.ts and // wallet-data-repository.ts can import without a circular dependency. +import { TransactionRefusedError } from './errors.ts'; + /** * The chain rejected the transaction outright. Most commonly: balance check * failed because the dust capacity wasn't sufficient at submission time @@ -127,3 +129,47 @@ export function isSdkInsufficientFundsError(err: any): boolean { export function isColdStartRace(err: unknown): boolean { return isSdkInsufficientFundsError(err) && !isDustShortage(err); } + +/** The wallet SDK's message on the error it wraps a node's refusal in, at each level. */ +const SUBMISSION_WRAPPERS: readonly string[] = ['Transaction submission error', 'Transaction submission failed']; + +/** + * What the node said when it refused a transaction, from the wallet SDK's + * SubmissionError wherever it is among the error's causes (a FiberFailure's + * included): the messages under the SDK's own wrappers, outermost first. + * Undefined for any other error, and for a submission error that carries + * nothing more than the wrapper. + */ +export function nodeRefusalOf(err: unknown): string | undefined { + const next = (current: Record): unknown => { + const failure = current[FIBER_FAILURE_CAUSE] as { _tag?: string; error?: unknown; defect?: unknown } | undefined; + if (failure?._tag === 'Fail') return failure.error; + if (failure?._tag === 'Die') return failure.defect; + return current.cause; + }; + const seen = new Set(); + let current: unknown = err; + let found = false; + const said: string[] = []; + while (current !== null && current !== undefined && !seen.has(current)) { + seen.add(current); + if (typeof current === 'string') { + if (found) said.push(current); + break; + } + if (typeof current !== 'object') break; + const e = current as Record; + if (e._tag === 'SubmissionError') found = true; + const message = typeof e.message === 'string' ? e.message.trim() : ''; + if (found && message !== '' && !SUBMISSION_WRAPPERS.includes(message) && said.at(-1) !== message) said.push(message); + current = next(e); + } + return found && said.length > 0 ? said.join(': ') : undefined; +} + +/** The error as it is reported: a node's refusal as a TransactionRefusedError carrying the node's words; any other error as it is. */ +export function withNodeReason(err: Error): Error { + if (err instanceof TransactionRefusedError) return err; + const reason = nodeRefusalOf(err); + return reason === undefined ? err : new TransactionRefusedError(reason, { cause: err }); +} diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 011f3e08..96b048f8 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -17,6 +17,7 @@ import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/proto import type { CommandRun } from './lib/run-command.ts'; import { servePayer } from './lib/serve-payer.ts'; import { classifyError } from './lib/exit-codes.ts'; +import { withNodeReason } from './lib/sdk-errors.ts'; import { trimAgentMessage } from './lib/error-trim.ts'; import { PKG_VERSION } from './lib/pkg.ts'; import { createConfirmationStore } from './lib/mcp/confirmation.ts'; @@ -198,7 +199,9 @@ async function executeTool(name: string, params: Record, call: } } -function errorResponse(error: Error) { +function errorResponse(thrown: Error) { + // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. + const error = withNodeReason(thrown); const { errorCode } = classifyError(error); return { content: [{ diff --git a/src/wallet.ts b/src/wallet.ts index c837df70..b3dace05 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -6,6 +6,7 @@ import { parseArgs, hasFlag } from './lib/argv.ts'; import { errorMessage, usageMessage } from './ui/format.ts'; import { assertKnownFlags } from './lib/command-flags.ts'; +import { withNodeReason } from './lib/sdk-errors.ts'; import { installedCommands } from './lib/installed-commands.ts'; import { commandNeedsWalletSdk, dispatchCommand, processOutput } from './lib/command-dispatch.ts'; import type { CommandOutcome } from './lib/call-context.ts'; @@ -116,7 +117,9 @@ run().then((outcome) => { if (needsWalletSdk) { process.exit(process.exitCode ?? 0); } -}).catch((err: Error) => { +}).catch((thrown: Error) => { + // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. + const err = withNodeReason(thrown); // Usage errors (missing/unknown subcommand, bad args) render in yellow // with a softer "Usage" framing. They are the user's prompt to fix and // retry, not a system failure. Exit code 2 (INVALID_ARGS). From 59c2312dc89cddf306620abb9ef697915cffbb5a Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:15:27 -0800 Subject: [PATCH 21/88] Engine, part 1: the rc engine, and keys and addresses behind it Phase E's first step: everything that touches the SDK moves behind one engine interface, reached through the engine for a network's SDK set. - lib/engine.ts (core, SDK-free): the interface, which grows area by area, and the loader. engineFor(network) loads the network's engine on first use, one per process; anyEngine() is for work every set does alike. One set today, rc. - engine/rc: the rc engine. Key and address derivation moved into it. - Wallet creation and loading derive addresses through the engine, so createWallet, loadWalletConfig, listWallets and their callers are now async. The address commands and localnet use the engine. - The layering check gives the engine its own home: only core's loader reaches it, it reaches only core and chain, and only an engine may import the SDK. The modules that still do are listed, and a test pins the list so it only shrinks. No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.d.mts | 2 + scripts/check-layering.mjs | 54 +++++++++++++++-- scripts/check-process-safety.mjs | 1 + src/__tests__/airdrop-command.test.ts | 2 +- src/__tests__/balance-command.live.test.ts | 2 +- src/__tests__/balance-command.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 10 ++-- src/__tests__/dapp-connector.test.ts | 2 +- src/__tests__/derive-address.test.ts | 2 +- src/__tests__/dust-command.test.ts | 2 +- src/__tests__/engine.test.ts | 33 +++++++++++ src/__tests__/info-command.test.ts | 2 +- src/__tests__/json-output.test.ts | 2 +- src/__tests__/layering.test.ts | 46 ++++++++++++++- .../mcp-server-concurrent-calls.test.ts | 2 +- src/__tests__/multi-wallet.test.ts | 14 ++--- src/__tests__/network-cancellation.test.ts | 4 +- src/__tests__/notices.test.ts | 2 +- src/__tests__/run-command.test.ts | 2 +- src/__tests__/sealed-wallet.test.ts | 16 ++--- src/__tests__/serve-manager.test.ts | 2 +- src/__tests__/shielded-direct.test.ts | 2 +- src/__tests__/state-root.test.ts | 2 +- src/__tests__/transfer-command.test.ts | 2 +- src/__tests__/transfer-lib.test.ts | 2 +- src/__tests__/transfer-request.test.ts | 26 ++++----- src/__tests__/verbose-per-call.test.ts | 2 +- src/__tests__/wallet-config.test.ts | 42 +++++++------- src/__tests__/wallet-create.test.ts | 16 ++--- src/__tests__/wallet-protect.test.ts | 6 +- src/commands/address.ts | 4 +- src/commands/airdrop.ts | 10 ++-- src/commands/balance.ts | 4 +- src/commands/contract.definition.ts | 2 +- src/commands/dust.ts | 2 +- src/commands/generate.ts | 4 +- src/commands/genesis-address.ts | 4 +- src/commands/grant.definition.ts | 2 +- src/commands/info.ts | 2 +- src/commands/localnet.ts | 4 +- src/commands/transfer.definition.ts | 2 +- src/commands/transfer.ts | 2 +- src/commands/wallet.ts | 6 +- src/{lib => engine/rc}/derivation.ts | 0 src/{lib => engine/rc}/derive-address.ts | 9 ++- src/engine/rc/index.ts | 15 +++++ src/lib/dev/provision-wallets.ts | 6 +- src/lib/dust-direct-cache.ts | 2 +- src/lib/dust-sync-native.ts | 2 +- src/lib/engine.ts | 58 +++++++++++++++++++ src/lib/facade.ts | 2 +- src/lib/serve-manager.ts | 2 +- src/lib/shielded-direct-cache.ts | 2 +- src/lib/transfer-request.ts | 10 ++-- src/lib/wallet-config.ts | 44 +++++++------- src/lib/wallet-create.ts | 9 +-- src/lib/wallet-data-repository.ts | 4 +- 57 files changed, 363 insertions(+), 154 deletions(-) create mode 100644 src/__tests__/engine.test.ts rename src/{lib => engine/rc}/derivation.ts (100%) rename src/{lib => engine/rc}/derive-address.ts (88%) create mode 100644 src/engine/rc/index.ts create mode 100644 src/lib/engine.ts diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 68074d49..42440370 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -4,3 +4,5 @@ export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; export function importRule(fromRel: string, toRel: string): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; +/** Modules that still import the SDK themselves, until each moves behind the engine. */ +export const PENDING_ENGINE: ReadonlySet; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 2b6ce646..4b352ece 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -39,7 +39,10 @@ const HOMES = [ // A command's definition (.definition.ts) lives in its command's package. ['core', /^commands\/config(\.definition)?\.ts$/], - ['core', /^lib\/(argv|errors|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance)\.ts$/], + // The SDK engines: each is the only code that imports its SDK set. + ['engine', /^engine\//], + + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], @@ -67,8 +70,10 @@ const HOMES = [ // The packages each package may import, its own included. Dependencies point // one way: core, chain, wallet, then contract and connect side by side, then -// dev, then grant. +// dev, then grant. An engine sits beside chain: it uses core and chain, and +// nothing imports it but core's loader. const MAY_IMPORT = { + engine: ['core', 'chain', 'engine'], core: ['core'], chain: ['core', 'chain'], wallet: ['core', 'chain', 'wallet'], @@ -89,6 +94,44 @@ const MAY_IMPORT = { const DISPATCHERS = new Set(['shell', 'mcp']); const MIDNIGHT_SDK = /^@midnight(-ntwrk|ntwrk)\//; + +// The one module that may import an engine: core's loader, which imports the +// engine for a network's SDK set when a call needs it. +const ENGINE_LOADER = 'lib/engine.ts'; + +// Modules that still import the SDK themselves, until each moves behind the +// engine; a module on the list may also import the engine's own files. The +// list only shrinks (a test pins it), and is empty when the engine is done. +export const PENDING_ENGINE = new Set([ + 'commands/airdrop.ts', + 'commands/balance.ts', + 'commands/dust.ts', + 'commands/inspect-cost.ts', + 'commands/transfer.ts', + 'lib/chain-params.ts', + 'lib/contract/providers.ts', + 'lib/contract/runner.ts', + 'lib/dapp-connector.ts', + 'lib/dust-balance-direct.ts', + 'lib/dust-collapse.ts', + 'lib/dust-direct-cache.ts', + 'lib/dust-direct.ts', + 'lib/dust-sync-native.ts', + 'lib/dust-wallet.ts', + 'lib/facade.ts', + 'lib/fee-only-check.ts', + 'lib/fork-schedule.ts', + 'lib/grant/sealed-account.ts', + 'lib/shielded-direct-cache.ts', + 'lib/shielded-direct.ts', + 'lib/sign-recipe.ts', + 'lib/test/prep-runner.ts', + 'lib/transfer-request.ts', + 'lib/transfer.ts', + 'lib/tx-inspect.ts', + 'lib/wallet-data-repository.ts', + 'lib/ws-rpc.ts', +]); const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; const SDK_FREE = new Set(['core', 'chain']); @@ -143,6 +186,9 @@ export function importRule(fromRel, toRel) { const isCommand = (path) => path.startsWith('commands/'); const callsCommand = isCommand(toRel) && (!isCommand(fromRel) || targetHome !== home); if (callsCommand && !DISPATCHERS.has(home)) return `${isCommand(fromRel) ? 'command' : 'library'} → ${targetHome} command`; + if (targetHome === 'engine' && home !== 'engine') { + return fromRel === ENGINE_LOADER || PENDING_ENGINE.has(fromRel) ? undefined : `${home} → engine (reach it through ${ENGINE_LOADER})`; + } if (!MAY_IMPORT[home].includes(targetHome)) return `${home} → ${targetHome}`; return undefined; } @@ -173,8 +219,8 @@ export function findLayeringProblems() { if (specifier.startsWith('.')) { const rule = importRule(rel, relative(SRC, resolve(dirname(file), specifier))); if (rule !== undefined) violations.push({ home, rule, where, specifier }); - } else if (SDK_FREE.has(home) && MIDNIGHT_SDK.test(specifier)) { - violations.push({ home, rule: `${home} → Midnight SDK`, where, specifier }); + } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine' && (SDK_FREE.has(home) || !PENDING_ENGINE.has(rel))) { + violations.push({ home, rule: `${home} → Midnight SDK (only an engine imports it)`, where, specifier }); } else if (home !== 'grant' && ACCOUNT_CHAIN.test(specifier)) { violations.push({ home, rule: `${home} → account chain`, where, specifier }); } diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 48322130..a4fef87f 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -87,6 +87,7 @@ export const ALLOWED_STATE = { 'lib/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/ws-rpc.ts': { connectionCounter: 'shared on purpose: the RPC connection id counter, unique across servers in the process' }, + 'lib/engine.ts': { loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)' }, 'lib/wallet-config.ts': { warnedPlain: 'shared on purpose: each plain-text wallet is warned about once per run' }, // The host sources, set once by the host at start (handlers see them through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, diff --git a/src/__tests__/airdrop-command.test.ts b/src/__tests__/airdrop-command.test.ts index 3860729c..96b5d3b9 100644 --- a/src/__tests__/airdrop-command.test.ts +++ b/src/__tests__/airdrop-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import airdropCommand from '../commands/airdrop.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index 177e2066..bede333c 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/balance-command.test.ts b/src/__tests__/balance-command.test.ts index 8b10df78..7f2f3f61 100644 --- a/src/__tests__/balance-command.test.ts +++ b/src/__tests__/balance-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index a81146ce..b4ca31e1 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -18,7 +18,7 @@ import { parseArgs } from '../lib/argv.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { setPrompter, type Prompter } from '../lib/prompter.ts'; import { establishPassphrase, isPassphraseSet } from '../lib/passphrase.ts'; -import { deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { getCachePath } from '../lib/wallet-cache.ts'; import { loadWalletConfig, protectAllWallets } from '../lib/wallet-config.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; @@ -264,7 +264,7 @@ describe('commands that write check the call before each whole write', () => { createdAt: '2026-10-31T00:00:00.000Z', }, path.join(stateRootIn(home), 'wallets', `${name}.json`)); }; - const isSealed = (file: string): boolean => loadWalletConfig(file).isSealed === true; + const isSealed = async (file: string): Promise => (await loadWalletConfig(file)).isSealed === true; it('cancelled while the passphrase is asked for: no wallet is sealed', async () => { const files = [plainWallet('alice', 'a1'), plainWallet('bob', 'b2')]; @@ -273,7 +273,7 @@ describe('commands that write check the call before each whole write', () => { await expect(cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); - expect(files.map(isSealed)).toEqual([false, false]); + expect(await Promise.all(files.map(isSealed))).toEqual([false, false]); expect(io.stdout()).toBe(''); expect(isPassphraseSet(stateRootIn(home)), 'no new passphrase saved').toBe(false); }); @@ -287,7 +287,7 @@ describe('commands that write check the call before each whole write', () => { setImmediate(() => call.abort()); await expect(protecting).rejects.toMatchObject({ code: 'CANCELLED' }); - expect(files.map(isSealed)).toEqual([true, false, false]); + expect(await Promise.all(files.map(isSealed))).toEqual([true, false, false]); }); it('cancelled by a protector: the protectors after it do not run', async () => { @@ -316,7 +316,7 @@ describe('commands that write check the call before each whole write', () => { it('cache clear --wallet: cancelled while the wallet is unlocked, it clears no cache', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - const created = createWallet('alice', walletSecretFrom(), PASSPHRASE); + const created = await createWallet('alice', walletSecretFrom(), PASSPHRASE); const cache = getCachePath(created.addresses.undeployed, 'undeployed'); fs.mkdirSync(path.dirname(cache), { recursive: true }); fs.writeFileSync(cache, '{}'); diff --git a/src/__tests__/dapp-connector.test.ts b/src/__tests__/dapp-connector.test.ts index ebc0eda5..3ee18ccc 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/src/__tests__/dapp-connector.test.ts @@ -23,7 +23,7 @@ import { PROOF_TIMEOUT_MS } from '../lib/constants.ts'; import { withDustShortfall } from '../lib/sdk-errors.ts'; import { classifyError } from '../lib/exit-codes.ts'; import { FORK_SCHEDULE } from '../lib/fork-schedule.ts'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '../engine/rc/derive-address.ts'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import type { FeeLimits } from '../lib/fee-limits.ts'; diff --git a/src/__tests__/derive-address.test.ts b/src/__tests__/derive-address.test.ts index cc2ef302..2cc4774f 100644 --- a/src/__tests__/derive-address.test.ts +++ b/src/__tests__/derive-address.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); diff --git a/src/__tests__/dust-command.test.ts b/src/__tests__/dust-command.test.ts index 45373617..7f7f805a 100644 --- a/src/__tests__/dust-command.test.ts +++ b/src/__tests__/dust-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import dustCommand from '../commands/dust.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts new file mode 100644 index 00000000..4e95756a --- /dev/null +++ b/src/__tests__/engine.test.ts @@ -0,0 +1,33 @@ +// The engine for a network: one per process, loaded on first use, and the +// same for work every set does alike. + +import { describe, expect, it } from 'vitest'; +import { anyEngine, engineFor, sdkSetOf } from '../lib/engine.ts'; +import { getValidNetworkNames, type NetworkName } from '../lib/network.ts'; +import { rcEngine } from '../engine/rc/index.ts'; + +describe('the engine for a network', () => { + it('is the rc engine for every network mn knows today', async () => { + for (const network of getValidNetworkNames() as NetworkName[]) { + expect(sdkSetOf(network)).toBe('rc'); + expect(await engineFor(network)).toBe(rcEngine); + } + }); + + it('is the one loaded in this process for work every set does alike', async () => { + expect(await anyEngine()).toBe(await engineFor('undeployed')); + }); + + it('derives a wallet\'s addresses on every network, matching one network at a time', async () => { + const seed = Buffer.from('ab'.repeat(32), 'hex'); + const { keys } = await anyEngine(); + const unshielded = keys.unshieldedAddresses(seed); + const shielded = keys.shieldedAddresses(seed); + for (const network of getValidNetworkNames() as NetworkName[]) { + expect(unshielded[network]).toBe(keys.unshieldedAddress(seed, network)); + expect(unshielded[network]).toMatch(new RegExp(`^mn_addr_${network}1`)); + expect(shielded[network]).toBe(keys.shieldedAddress(seed, network)); + expect(shielded[network]).toMatch(new RegExp(`^mn_shield-addr_${network}1`)); + } + }); +}); diff --git a/src/__tests__/info-command.test.ts b/src/__tests__/info-command.test.ts index fec21d61..cf208b5d 100644 --- a/src/__tests__/info-command.test.ts +++ b/src/__tests__/info-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import infoCommand from '../commands/info.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index e9d9d329..221206d6 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -16,7 +16,7 @@ import inspectCostCommand from '../commands/inspect-cost.ts'; import configCommand from '../commands/config.ts'; import helpCommand from '../commands/help.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { loadCliConfig } from '../lib/cli-config.ts'; import { localIndexerFlags } from './helpers/local-indexer.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 6dffaa4b..cf0d0c72 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -2,7 +2,7 @@ // has a package, and no import crosses the layering the planned split needs. import { describe, expect, it } from 'vitest'; -import { findLayeringProblems, importRule } from '../../scripts/check-layering.mjs'; +import { PENDING_ENGINE, findLayeringProblems, importRule } from '../../scripts/check-layering.mjs'; describe('the layering', () => { it('holds across src/', () => { @@ -37,4 +37,48 @@ describe('the layering', () => { expect(importRule('lib/dev/deploy.ts', 'commands/contract.ts')).toBe('library → contract command'); expect(importRule('commands/dev.ts', 'commands/contract.ts')).toBe('command → contract command'); }); + + it('lets only core\'s loader reach an engine, and an engine reach only core and chain', () => { + expect(importRule('lib/engine.ts', 'engine/rc/index.ts')).toBeUndefined(); + expect(importRule('commands/address.ts', 'engine/rc/derive-address.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); + expect(importRule('lib/wallet-create.ts', 'engine/rc/index.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); + expect(importRule('engine/rc/derive-address.ts', 'lib/network.ts')).toBeUndefined(); + expect(importRule('engine/rc/index.ts', 'lib/facade.ts')).toBe('engine → wallet'); + }); + + // Each module here still imports the SDK itself. Taking one off is the + // point of moving it behind the engine; adding one is refused. + it('has no module importing the SDK outside the engine but those still waiting to move', () => { + expect([...PENDING_ENGINE].sort()).toStrictEqual([ + 'commands/airdrop.ts', + 'commands/balance.ts', + 'commands/dust.ts', + 'commands/inspect-cost.ts', + 'commands/transfer.ts', + 'lib/chain-params.ts', + 'lib/contract/providers.ts', + 'lib/contract/runner.ts', + 'lib/dapp-connector.ts', + 'lib/dust-balance-direct.ts', + 'lib/dust-collapse.ts', + 'lib/dust-direct-cache.ts', + 'lib/dust-direct.ts', + 'lib/dust-sync-native.ts', + 'lib/dust-wallet.ts', + 'lib/facade.ts', + 'lib/fee-only-check.ts', + 'lib/fork-schedule.ts', + 'lib/grant/sealed-account.ts', + 'lib/shielded-direct-cache.ts', + 'lib/shielded-direct.ts', + 'lib/sign-recipe.ts', + 'lib/test/prep-runner.ts', + 'lib/transfer-request.ts', + 'lib/transfer.ts', + 'lib/tx-inspect.ts', + 'lib/wallet-data-repository.ts', + 'lib/ws-rpc.ts', + ]); + expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); + }); }); diff --git a/src/__tests__/mcp-server-concurrent-calls.test.ts b/src/__tests__/mcp-server-concurrent-calls.test.ts index b7b5e577..a46f96db 100644 --- a/src/__tests__/mcp-server-concurrent-calls.test.ts +++ b/src/__tests__/mcp-server-concurrent-calls.test.ts @@ -21,7 +21,7 @@ import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.js'; -import { deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { toNight } from '../ui/format.ts'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; diff --git a/src/__tests__/multi-wallet.test.ts b/src/__tests__/multi-wallet.test.ts index 12d52152..ed09f21f 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/src/__tests__/multi-wallet.test.ts @@ -26,7 +26,7 @@ import { FILE_MODE, isValidWalletName, } from '../lib/constants.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; // Use a temp dir that simulates ~/.midnight const TEST_HOME = path.join(os.tmpdir(), `midnight-multi-wallet-test-${process.pid}`); @@ -111,8 +111,8 @@ describe('resolveWalletPath', () => { // ─── listWallets ──────────────────────────────────────────── describe('listWallets', () => { - it('returns empty array when wallets dir does not exist', () => { - const wallets = listWallets(); + it('returns empty array when wallets dir does not exist', async () => { + const wallets = await listWallets(); // There might be a real ~/.midnight/wallets dir, but in test context // we check the structure is correct expect(Array.isArray(wallets)).toBe(true); @@ -179,9 +179,9 @@ describe('migrateOldWallet', () => { // ─── loadWalletConfig error messages ──────────────────────── describe('loadWalletConfig error messages', () => { - it('suggests "midnight wallet generate" in missing file error', () => { + it('suggests "midnight wallet generate" in missing file error', async () => { const filePath = path.join(TEST_HOME, 'nonexistent.json'); - expect(() => loadWalletConfig(filePath)).toThrow('midnight wallet generate'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('midnight wallet generate'); }); }); @@ -252,10 +252,10 @@ describe('isValidWalletName', () => { // ─── saveWalletConfig + loadWalletConfig round-trip ───────── describe('wallet config round-trip with named wallets', () => { - it('saves and loads from wallets directory path', () => { + it('saves and loads from wallets directory path', async () => { const walletPath = path.join(TEST_WALLETS_DIR, 'test.json'); saveWalletConfig(VALID_WALLET, walletPath); - const loaded = loadWalletConfig(walletPath); + const loaded = await loadWalletConfig(walletPath); expect(loaded).not.toHaveProperty('seed'); expect(loaded.isSealed).toBe(false); expect(loaded.addresses).toEqual(VALID_WALLET.addresses); diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index d9ddbc0e..d843c6ce 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -39,8 +39,8 @@ beforeEach(async () => { process.env.HOME = home; process.env.MN_PASSPHRASE = PASSPHRASE; establishPassphrase(stateRootIn(home), PASSPHRASE); - createWallet('alice', walletSecretFrom(), PASSPHRASE); - createWallet('bob', walletSecretFrom(), PASSPHRASE); + await createWallet('alice', walletSecretFrom(), PASSPHRASE); + await createWallet('bob', walletSecretFrom(), PASSPHRASE); io = captureOutput(); // Every endpoint: takes HTTP requests and WebSocket upgrades, and answers none. requests = 0; diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index 46c76310..17743703 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -9,7 +9,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { notice, setNoticeSink } from '../lib/notices.ts'; import { unlockWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; const ROOT = path.resolve(import.meta.dirname, '..', '..'); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index cca7a34b..f0d6752c 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -16,7 +16,7 @@ import addressCommand from '../commands/address.ts'; import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { localIndexerFlags } from './helpers/local-indexer.ts'; import { ownCall } from './helpers/own-call.ts'; diff --git a/src/__tests__/sealed-wallet.test.ts b/src/__tests__/sealed-wallet.test.ts index 060cb56c..e6dddfca 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/src/__tests__/sealed-wallet.test.ts @@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { WrongPassphraseError } from '../lib/keystore.ts'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { loadWalletConfig, protectAllWallets, sealWalletInPlace, unlockWallet, writeSealedWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; import { FILE_MODE } from '../lib/constants.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; @@ -46,9 +46,9 @@ describe('a sealed wallet', () => { expect(fs.statSync(file).mode & 0o777).toBe(FILE_MODE); }); - it('shows its addresses without the passphrase', () => { + it('shows its addresses without the passphrase', async () => { writeSealedWallet(file, PUBLIC, { seed: SEED }, PASSPHRASE); - const config = loadWalletConfig(file); + const config = await loadWalletConfig(file); expect(config.addresses).toEqual(PUBLIC.addresses); expect(config.shieldedAddresses).toEqual(PUBLIC.shieldedAddresses); expect(config.isSealed).toBe(true); @@ -84,26 +84,26 @@ describe('a wallet an earlier mn wrote in plain text', () => { const warnings: string[] = []; const wallet = await unlockWallet(file, { root: stateRootIn(home), warn: (line) => warnings.push(line) }); expect(wallet.seed).toBe(SEED); - expect(loadWalletConfig(file).isSealed).toBe(false); + expect((await loadWalletConfig(file)).isSealed).toBe(false); expect(warnings.join('\n')).toMatch(/not protected[\s\S]*midnight wallet protect/); }); it('is sealed in place, keeping its seed, mnemonic and addresses, with nothing left in the clear', async () => { writePlain(); - sealWalletInPlace(file, PASSPHRASE); + await sealWalletInPlace(file, PASSPHRASE); const text = fs.readFileSync(file, 'utf8'); expect(text).not.toContain(SEED); expect(text).not.toContain('abandon'); - expect(loadWalletConfig(file)).toMatchObject({ ...PUBLIC, isSealed: true }); + expect(await loadWalletConfig(file)).toMatchObject({ ...PUBLIC, isSealed: true }); const wallet = await unlockWallet(file, withPassphrase(PASSPHRASE)); expect(wallet.seed).toBe(SEED); expect(wallet.mnemonic).toBe(MNEMONIC); }); - it('is left as it was when it is already sealed', () => { + it('is left as it was when it is already sealed', async () => { writeSealedWallet(file, PUBLIC, { seed: SEED }, PASSPHRASE); const before = fs.readFileSync(file, 'utf8'); - sealWalletInPlace(file, PASSPHRASE); + await sealWalletInPlace(file, PASSPHRASE); expect(fs.readFileSync(file, 'utf8')).toBe(before); }); }); diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index 561a2846..32cba373 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; diff --git a/src/__tests__/shielded-direct.test.ts b/src/__tests__/shielded-direct.test.ts index 9b846e56..a93ef5aa 100644 --- a/src/__tests__/shielded-direct.test.ts +++ b/src/__tests__/shielded-direct.test.ts @@ -3,7 +3,7 @@ import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; import type { AddressInfo } from 'node:net'; import * as ledger from '@midnightntwrk/ledger-v9'; import { readShieldedBalanceDirect } from '../lib/shielded-direct.ts'; -import { deriveShieldedSeed } from '../lib/derivation.ts'; +import { deriveShieldedSeed } from '../engine/rc/derivation.ts'; import zswapEvents from './fixtures/zswap-events-localnet.json'; // Real zswap ledger events (ledger 9, event[v14]) captured from a fresh localnet chain. Seeds 0x01 and diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 050be28c..35db5310 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -41,7 +41,7 @@ async function writeEveryOwnersFiles(): Promise { setConfigValue('network', 'preview'); setConfigValue('node', 'ws://localhost:29944', undefined, 'undeployed'); bindCachesToIndexer('undeployed', 'ws://localhost:28088/api/v4/graphql/ws'); - createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret()); + await createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret()); fs.mkdirSync(accountRecordsDir('undeployed', 'alice'), { recursive: true }); } diff --git a/src/__tests__/transfer-command.test.ts b/src/__tests__/transfer-command.test.ts index b0e1042a..992a70fc 100644 --- a/src/__tests__/transfer-command.test.ts +++ b/src/__tests__/transfer-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import transferCommand from '../commands/transfer.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/transfer-lib.test.ts b/src/__tests__/transfer-lib.test.ts index 428049a9..c95b62b2 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/src/__tests__/transfer-lib.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import { validateRecipientAddress, isDustRelatedError } from '../lib/transfer.ts'; import { nightToMicro, parseAmount } from '../lib/amount.ts'; import { getNetworkConfig } from '../lib/network.ts'; -import { deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '../lib/constants.ts'; import { UsageError } from '../lib/errors.ts'; import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '../lib/exit-codes.ts'; diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index 5876a6d6..1a1d82a1 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -9,7 +9,7 @@ import * as path from 'path'; import { resolveTransferRequest } from '../lib/transfer-request.ts'; import { parseArgs } from '../lib/argv.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '../lib/constants.ts'; import { UsageError } from '../lib/errors.ts'; import { classifyError } from '../lib/exit-codes.ts'; @@ -49,18 +49,18 @@ afterEach(() => { }); describe('resolveTransferRequest', () => { - it('takes an address and an amount, on the network asked for', () => { - const r = request(RECIPIENT.preprod, '1.5', '--wallet', 'sender', '--network', 'preprod'); + it('takes an address and an amount, on the network asked for', async () => { + const r = await request(RECIPIENT.preprod, '1.5', '--wallet', 'sender', '--network', 'preprod'); expect(r).toMatchObject({ recipientAddress: RECIPIENT.preprod, amountNight: 1.5, shielded: false, networkName: 'preprod' }); expect(r.walletPath).toBe(path.join(WALLETS, 'sender.json')); // The request is checked without the passphrase: it carries the wallet's addresses, never its seed. expect(r.walletConfig).not.toHaveProperty('seed'); }); - it('resolves a wallet name given as the recipient to that wallet\'s address on the network', () => { + it('resolves a wallet name given as the recipient to that wallet\'s address on the network', async () => { saveWallet('bob', RECIPIENT_SEED, true); - expect(request('bob', '2', '--wallet', 'sender').recipientAddress).toBe(RECIPIENT.undeployed); - expect(request('bob', '2', '--wallet', 'sender', '--shielded').recipientAddress).toBe(RECIPIENT_SHIELDED.undeployed); + expect((await request('bob', '2', '--wallet', 'sender')).recipientAddress).toBe(RECIPIENT.undeployed); + expect((await request('bob', '2', '--wallet', 'sender', '--shielded')).recipientAddress).toBe(RECIPIENT_SHIELDED.undeployed); }); it.each([ @@ -75,8 +75,8 @@ describe('resolveTransferRequest', () => { [[RECIPIENT_SHIELDED.undeployed, '1'], 'Invalid recipient address'], [[RECIPIENT.undeployed, '1', '--shielded'], 'Invalid shielded address'], [[RECIPIENT.undeployed, '1', '--wallet', 'nosuchsender'], 'Wallet file not found'], - ])('refuses %j', (argv, message) => { - expect(() => request(...argv, ...(argv.includes('--wallet') ? [] : ['--wallet', 'sender']))).toThrow(message); + ])('refuses %j', async (argv, message) => { + await expect(request(...argv, ...(argv.includes('--wallet') ? [] : ['--wallet', 'sender']))).rejects.toThrow(message); }); it.each([ @@ -84,15 +84,15 @@ describe('resolveTransferRequest', () => { [[RECIPIENT.undeployed, 'ten']], [['mn_addr_undeployed1notanaddress', '1']], [[RECIPIENT.preprod, '1']], - ])('refuses %j as a usage mistake, which an agent sees as INVALID_ARGS', (argv) => { + ])('refuses %j as a usage mistake, which an agent sees as INVALID_ARGS', async (argv) => { let err: unknown; - try { request(...argv, '--wallet', 'sender'); } catch (e) { err = e; } + try { await request(...argv, '--wallet', 'sender'); } catch (e) { err = e; } expect(err).toBeInstanceOf(UsageError); expect(classifyError(err as Error).errorCode).toBe('INVALID_ARGS'); }); - it('refuses a shielded transfer where shielded is off before reading the address', () => { - expect(() => request('mn_shield-addr_preprod1garbage', '1', '--wallet', 'sender', '--shielded', '--network', 'preprod')) - .toThrow(/Shielded is unavailable on preprod/); + it('refuses a shielded transfer where shielded is off before reading the address', async () => { + await expect(request('mn_shield-addr_preprod1garbage', '1', '--wallet', 'sender', '--shielded', '--network', 'preprod')) + .rejects.toThrow(/Shielded is unavailable on preprod/); }); }); diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 4261780b..3f0d7a7a 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -12,7 +12,7 @@ import { captureCommand } from '../lib/run-command.ts'; import { callDiagnostics } from '../lib/call-context.ts'; import { parseArgs } from '../lib/argv.ts'; import { setNoticeSink } from '../lib/notices.ts'; -import { deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; import type { NetworkConfig } from '../lib/network.ts'; import balanceCommand from '../commands/balance.ts'; diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 9a842373..9b370bb3 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -6,7 +6,7 @@ import { loadWalletConfig, matchWalletAddress, unlockWallet, writeSealedWallet, import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { DIR_MODE, FILE_MODE } from '../lib/constants.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-wallet-test-${process.pid}`); @@ -68,75 +68,75 @@ describe('writeSealedWallet', () => { }); describe('loadWalletConfig', () => { - it('loads a plain-text wallet an earlier mn wrote, without its secrets', () => { + it('loads a plain-text wallet an earlier mn wrote, without its secrets', async () => { const filePath = path.join(TEST_DIR, 'wallet.json'); saveWalletConfig(VALID_CONFIG, filePath); - const loaded = loadWalletConfig(filePath); + const loaded = await loadWalletConfig(filePath); expect(loaded).not.toHaveProperty('seed'); expect(loaded.isSealed).toBe(false); expect(loaded.addresses).toEqual(VALID_CONFIG.addresses); expect(loaded.createdAt).toBe(VALID_CONFIG.createdAt); }); - it('throws when file does not exist', () => { + it('throws when file does not exist', async () => { const filePath = path.join(TEST_DIR, 'nonexistent.json'); - expect(() => loadWalletConfig(filePath)).toThrow('Wallet file not found'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('Wallet file not found'); }); - it('includes actionable recovery guidance in missing file error', () => { + it('includes actionable recovery guidance in missing file error', async () => { const filePath = path.join(TEST_DIR, 'nonexistent.json'); - expect(() => loadWalletConfig(filePath)).toThrow('midnight wallet generate'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('midnight wallet generate'); }); - it('includes the file path in missing file error', () => { + it('includes the file path in missing file error', async () => { const filePath = path.join(TEST_DIR, 'nonexistent.json'); - expect(() => loadWalletConfig(filePath)).toThrow(filePath); + await expect(loadWalletConfig(filePath)).rejects.toThrow(filePath); }); - it('throws on invalid JSON', () => { + it('throws on invalid JSON', async () => { const filePath = path.join(TEST_DIR, 'bad.json'); fs.writeFileSync(filePath, 'not json at all'); - expect(() => loadWalletConfig(filePath)).toThrow('Invalid JSON'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('Invalid JSON'); }); - it('throws when seed is missing', () => { + it('throws when seed is missing', async () => { const filePath = path.join(TEST_DIR, 'incomplete.json'); fs.writeFileSync(filePath, JSON.stringify({ addresses: VALID_ADDRESSES, createdAt: '2025-01-01T00:00:00.000Z', })); - expect(() => loadWalletConfig(filePath)).toThrow('seed'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('seed'); }); - it('throws when address and addresses are both missing', () => { + it('throws when address and addresses are both missing', async () => { const filePath = path.join(TEST_DIR, 'incomplete.json'); fs.writeFileSync(filePath, JSON.stringify({ seed: VALID_SEED, createdAt: '2025-01-01T00:00:00.000Z', })); - expect(() => loadWalletConfig(filePath)).toThrow('address'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('address'); }); - it('throws when createdAt is missing', () => { + it('throws when createdAt is missing', async () => { const filePath = path.join(TEST_DIR, 'incomplete.json'); fs.writeFileSync(filePath, JSON.stringify({ seed: 'aabb00', addresses: VALID_ADDRESSES, })); - expect(() => loadWalletConfig(filePath)).toThrow('createdAt'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('createdAt'); }); - it('throws on non-hex seed', () => { + it('throws on non-hex seed', async () => { const filePath = path.join(TEST_DIR, 'badseed.json'); fs.writeFileSync(filePath, JSON.stringify({ seed: 'not-a-hex-string!', addresses: VALID_ADDRESSES, createdAt: '2025-01-01T00:00:00.000Z', })); - expect(() => loadWalletConfig(filePath)).toThrow('Invalid seed format'); + await expect(loadWalletConfig(filePath)).rejects.toThrow('Invalid seed format'); }); - it('auto-migrates old format with address and network fields', () => { + it('auto-migrates old format with address and network fields', async () => { const filePath = path.join(TEST_DIR, 'old-format.json'); fs.writeFileSync(filePath, JSON.stringify({ seed: VALID_SEED, @@ -144,7 +144,7 @@ describe('loadWalletConfig', () => { address: 'mn_addr_preprod1oldaddress', createdAt: '2025-01-01T00:00:00.000Z', })); - const loaded = loadWalletConfig(filePath); + const loaded = await loadWalletConfig(filePath); // Should have derived all addresses from the seed expect(loaded.addresses).toEqual(VALID_ADDRESSES); expect((loaded as any).network).toBeUndefined(); diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index 464c07e5..d6800c39 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -10,7 +10,7 @@ import * as path from 'node:path'; import { mnemonicToSeedSync } from '@scure/bip39'; import { createWallet, walletFilePath, walletSecretFrom } from '../lib/wallet-create.ts'; import { getActiveWalletName, unlockWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; @@ -38,7 +38,7 @@ afterEach(() => { describe('createWallet', () => { it('writes a sealed wallet that unlocks to its new mnemonic, and makes it active', async () => { - const created = createWallet('alice', walletSecretFrom(), PASSPHRASE); + const created = await createWallet('alice', walletSecretFrom(), PASSPHRASE); expect(created.file).toBe(walletFilePath('alice')); expect(created.mnemonic!.split(' ')).toHaveLength(24); @@ -49,25 +49,25 @@ describe('createWallet', () => { expect(getActiveWalletName()).toBe('alice'); }); - it('derives its addresses from a given mnemonic', () => { - const created = createWallet('bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE); + it('derives its addresses from a given mnemonic', async () => { + const created = await createWallet('bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE); expect(created.addresses).toEqual(deriveAllAddresses(Buffer.from(mnemonicToSeedSync(MNEMONIC)))); }); it('keeps a given seed and no mnemonic', async () => { const seed = Buffer.alloc(32, 2); - const created = createWallet('carol', walletSecretFrom({ seed }), PASSPHRASE); + const created = await createWallet('carol', walletSecretFrom({ seed }), PASSPHRASE); const unlocked = await unlockWallet(created.file); expect(unlocked.seed).toBe(seed.toString('hex')); expect(unlocked.mnemonic).toBeUndefined(); }); it('replaces an existing wallet only when asked', async () => { - const first = createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE); - expect(() => createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE)).toThrow(`Wallet file already exists: ${first.file}`); + const first = await createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE); + await expect(createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE)).rejects.toThrow(`Wallet file already exists: ${first.file}`); expect((await unlockWallet(first.file)).seed).toBe(Buffer.alloc(32, 1).toString('hex')); - createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, { overwrite: true }); + await createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, { overwrite: true }); expect((await unlockWallet(first.file)).seed).toBe(Buffer.alloc(32, 2).toString('hex')); }); diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index 012f069a..ae25ac5b 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -13,7 +13,7 @@ import walletCommand from '../commands/wallet.ts'; import { parseArgs } from '../lib/argv.ts'; import { PASSPHRASE_ENV, isPassphraseSet } from '../lib/passphrase.ts'; import { loadWalletConfig } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { accountProtector } from '../lib/grant/account-protector.ts'; @@ -58,7 +58,7 @@ describe('wallet protect', () => { const result = await protect(); expect(isPassphraseSet(stateRootIn(home))).toBe(true); expect(result).toMatchObject({ sealed: ['alice', 'bob'], alreadySealed: [] }); - expect(loadWalletConfig(alice).isSealed).toBe(true); + expect((await loadWalletConfig(alice)).isSealed).toBe(true); expect(fs.readFileSync(alice, 'utf8')).not.toContain(SEED); }); @@ -74,7 +74,7 @@ describe('wallet protect', () => { const bob = plainWallet('bob'); process.env[PASSPHRASE_ENV] = 'another passphrase entirely'; await expect(protect()).rejects.toThrow(/Wrong passphrase/); - expect(loadWalletConfig(bob).isSealed).toBe(false); + expect((await loadWalletConfig(bob)).isSealed).toBe(false); }); it("seals each wallet's plain-text account too, and names one whose wallet is gone", async () => { diff --git a/src/commands/address.ts b/src/commands/address.ts index 1648e86f..710bf505 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -3,7 +3,7 @@ import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; -import { deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { engineFor } from '../lib/engine.ts'; import { resolveNetworkName } from '../lib/resolve-network.ts'; import { keyValue, divider, formatAddress } from '../ui/format.ts'; import { dim } from '../ui/colors.ts'; @@ -20,7 +20,7 @@ export default async function addressCommand(args: ParsedArgs, ctx: CallContext) } const networkName = resolveNetworkName({ args }); - const address = deriveUnshieldedAddress(seedBuffer, networkName, keyIndex); + const address = (await engineFor(networkName)).keys.unshieldedAddress(seedBuffer, networkName, keyIndex); const derivationPath = `m/44'/2400'/0'/NightExternal/${keyIndex}`; // JSON mode diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index ba328aeb..1a240d3b 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -18,7 +18,7 @@ import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '../lib/network.ts'; import { getNetworkId } from '../lib/network-id.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; -import { deriveShieldedAddress } from '../lib/derive-address.ts'; +import { deriveShieldedAddress } from '../engine/rc/derive-address.ts'; import { ensureDust } from '../lib/transfer.ts'; import { parseAmount, nightToMicro } from '../lib/amount.ts'; import { airdropNight } from '../lib/airdrop.ts'; @@ -65,7 +65,7 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) const walletFlag = getFlag(args, 'wallet'); const isShielded = hasFlag(args, 'shielded') || (walletFlag !== undefined && walletFlag.startsWith('mn_shield-addr_')); - const destination = resolveDestination(args, networkName, networkConfig, isShielded); + const destination = await resolveDestination(args, networkName, networkConfig, isShielded); if (isShielded) { return shieldedAirdrop(args, destination as ShieldedDestination, amountNight, networkName, networkConfig, ctx); @@ -91,12 +91,12 @@ function looksLikeBech32mAddress(value: string): boolean { return value.startsWith('mn_addr_') || value.startsWith('mn_shield-addr_'); } -function resolveDestination( +async function resolveDestination( args: ParsedArgs, networkName: NetworkName, networkConfig: NetworkConfig, isShielded: boolean, -): UnshieldedDestination | ShieldedDestination { +): Promise { const walletFlag = getFlag(args, 'wallet'); if (walletFlag !== undefined && looksLikeBech32mAddress(walletFlag)) { @@ -105,7 +105,7 @@ function resolveDestination( // Fall back to wallet file (name, path, or active wallet) const walletPath = resolveWalletPath(walletFlag); - const config = loadWalletConfig(walletPath); + const config = await loadWalletConfig(walletPath); if (isShielded) { // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase. diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 1167c919..36722618 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -15,7 +15,7 @@ import { isNativeToken } from '../lib/balance-subscription.ts'; import { defaultRepository } from '../lib/wallet-data-repository.ts'; import { readShieldedBalanceCached } from '../lib/shielded-direct-cache.ts'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; -import { deriveShieldedAddress, deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { deriveShieldedAddress, deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { getChainGenesisHash } from '../lib/chain-id.ts'; import { createEtaEstimator, formatSyncStatus } from '../lib/sync-eta.ts'; import { header, keyValue, divider, formatNight, formatAddress, toNight } from '../ui/format.ts'; @@ -77,7 +77,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise // wallets we have the seed → run the full wallet sync (which shows shielded). // Otherwise there's nothing to decrypt with → fail with a clear, actionable error. if (hasFlag(args, 'shielded')) { - const owned = findWalletByAddress(address); + const owned = await findWalletByAddress(address); if (owned) { ctx.diagnostics.line('balance', `shielded positional → wallet ${owned.wallet.name} on ${owned.network}`); const delegated: ParsedArgs = { diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index 3e6a661f..f1389b08 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -8,7 +8,7 @@ const ON_CHAIN: readonly string[] = ['deploy', 'call', 'state']; /** The wallet a deploy or call pays from exists and can be read. */ async function checkSendingWallet(params: Readonly>): Promise { const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); - loadWalletConfig(resolveWalletPath(params.wallet as string | undefined)); + await loadWalletConfig(resolveWalletPath(params.wallet as string | undefined)); } export const contractDefinition: CommandDefinition = { diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 2e0df080..bcf47e63 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -9,7 +9,7 @@ import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides, type NetworkConfig } from '../lib/network.ts'; -import { deriveDustSeed } from '../lib/derivation.ts'; +import { deriveDustSeed } from '../engine/rc/derivation.ts'; import { registerDust } from '../lib/dust-register.ts'; import { checkBalance } from '../lib/balance-subscription.ts'; import { dustPublicKeyHex } from '../lib/dust-direct-cache.ts'; diff --git a/src/commands/generate.ts b/src/commands/generate.ts index 03c03d29..b16ed49e 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -8,7 +8,7 @@ import * as path from 'path'; import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { deriveAllAddresses } from '../lib/derive-address.ts'; +import { engineFor } from '../lib/engine.ts'; import { resolveNetworkName } from '../lib/resolve-network.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { passphraseForNewSecret } from '../lib/passphrase.ts'; @@ -66,7 +66,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic)); } - const addresses = deriveAllAddresses(seedBuffer); + const addresses = (await engineFor(networkName)).keys.unshieldedAddresses(seedBuffer); const activeAddress = addresses[networkName]; const config: WalletPublic = { diff --git a/src/commands/genesis-address.ts b/src/commands/genesis-address.ts index 0f83bb37..8492495c 100644 --- a/src/commands/genesis-address.ts +++ b/src/commands/genesis-address.ts @@ -2,7 +2,7 @@ import { type ParsedArgs, hasFlag } from '../lib/argv.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; -import { deriveUnshieldedAddress } from '../lib/derive-address.ts'; +import { engineFor } from '../lib/engine.ts'; import { resolveNetworkName } from '../lib/resolve-network.ts'; import { keyValue, divider, formatAddress } from '../ui/format.ts'; import { dim } from '../ui/colors.ts'; @@ -11,7 +11,7 @@ import type { CallContext } from '../lib/call-context.ts'; export default async function genesisAddressCommand(args: ParsedArgs, ctx: CallContext): Promise { const networkName = resolveNetworkName({ args }); const seedBuffer = Buffer.from(GENESIS_SEED, 'hex'); - const address = deriveUnshieldedAddress(seedBuffer, networkName); + const address = (await engineFor(networkName)).keys.unshieldedAddress(seedBuffer, networkName); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index a90a3508..ff9cc6ce 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -7,7 +7,7 @@ async function checkGrant(params: Readonly>, call: ToolC const { prepareGrant } = await import('../lib/grant/prepare.ts'); const prepared = await prepareGrant(call.argv()); const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); - loadWalletConfig(resolveWalletPath(params.wallet as string | undefined)); + await loadWalletConfig(resolveWalletPath(params.wallet as string | undefined)); return prepared; } diff --git a/src/commands/info.ts b/src/commands/info.ts index 668967e8..0e41a266 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -11,7 +11,7 @@ import type { CallContext } from '../lib/call-context.ts'; export default async function infoCommand(args: ParsedArgs, ctx: CallContext): Promise { const resolvedPath = resolveWalletPath(getFlag(args, 'wallet')); - const config = loadWalletConfig(resolvedPath); + const config = await loadWalletConfig(resolvedPath); const activeNetwork = resolveNetworkName({ args }); const activeAddress = config.addresses[activeNetwork]; diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index aa3ba67f..80c64ba8 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -72,14 +72,14 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) const { waitForAddressFunded } = await import('../lib/indexer-ready.ts'); const { waitForProofServerReady } = await import('../lib/proof-server-ready.ts'); const { getNetworkConfig } = await import('../lib/network.ts'); - const { deriveUnshieldedAddress } = await import('../lib/derive-address.ts'); + const { engineFor } = await import('../lib/engine.ts'); const { GENESIS_SEED } = await import('../lib/constants.ts'); const netCfg = getNetworkConfig('undeployed'); await waitForFirstBlock(netCfg.node, { timeoutMs: 30_000, signal: ctx.signal }); spinner.update('Waiting for indexer to ingest genesis state...'); - const genesisAddress = deriveUnshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const genesisAddress = (await engineFor('undeployed')).keys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); await waitForAddressFunded(netCfg.indexerWS, genesisAddress, { timeoutMs: 30_000, signal: ctx.signal }); spinner.update('Waiting for proof server...'); diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 8bb04603..45cbccf0 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -110,7 +110,7 @@ export const transferDefinition: CommandDefinition = { }, async check(_params, call) { const { resolveTransferRequest } = await import('../lib/transfer-request.ts'); - resolveTransferRequest(call.argv()); + await resolveTransferRequest(call.argv()); }, }, order: 12, diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 3aef8846..9c3476a0 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -21,7 +21,7 @@ import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '../lib/dust-wait.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); - const request = resolveTransferRequest(args); + const request = await resolveTransferRequest(args); return request.shielded ? shieldedTransfer(args, request, ctx) : unshieldedTransfer(args, request, ctx); } diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index 8386d544..19ace2e6 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -86,7 +86,7 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise // Cancelled while the passphrase was asked for: no wallet is written, and no new passphrase saved. throwIfCancelled(ctx.signal); // Checked above: an existing wallet is replaced only with --force. - const created = createWallet(name, secret, passphrase, { overwrite: hasFlag(args, 'force') }); + const created = await createWallet(name, secret, passphrase, { overwrite: hasFlag(args, 'force') }); const { addresses, shieldedAddresses, mnemonic, file: savedPath } = created; const seedBuffer = created.seed; const activeAddress = addresses[networkName]; @@ -139,7 +139,7 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise } async function walletList(args: ParsedArgs, ctx: CallContext): Promise { - const wallets = listWallets(); + const wallets = await listWallets(); const networkName = resolveNetworkName({ args }); if (hasFlag(args, 'json')) { @@ -234,7 +234,7 @@ async function walletInfo(args: ParsedArgs, ctx: CallContext): Promise { // (flag, consistent with balance/dust/transfer); fall back to the active wallet. const name = getFlag(args, 'wallet') ?? args.positionals[0] ?? getActiveWalletName(); const walletPath = resolveWalletPath(name); - const config = loadWalletConfig(walletPath); + const config = await loadWalletConfig(walletPath); const isActive = name === getActiveWalletName(); const networkName = resolveNetworkName({ args }); const activeAddress = config.addresses[networkName]; diff --git a/src/lib/derivation.ts b/src/engine/rc/derivation.ts similarity index 100% rename from src/lib/derivation.ts rename to src/engine/rc/derivation.ts diff --git a/src/lib/derive-address.ts b/src/engine/rc/derive-address.ts similarity index 88% rename from src/lib/derive-address.ts rename to src/engine/rc/derive-address.ts index 099e8958..e5e6cc41 100644 --- a/src/lib/derive-address.ts +++ b/src/engine/rc/derive-address.ts @@ -10,9 +10,9 @@ import { ShieldedEncryptionPublicKey, } from '@midnightntwrk/wallet-sdk/address-format'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { type NetworkName, getValidNetworkNames } from './network.ts'; +import { type NetworkName, getValidNetworkNames } from '../../lib/network.ts'; import { deriveShieldedSeed } from './derivation.ts'; -import { networkIdForName } from './network-id.ts'; +import { networkIdForName } from '../../lib/network-id.ts'; /** * Derive an unshielded address from a seed buffer, network, and optional key index. @@ -80,6 +80,11 @@ export function deriveAllShieldedAddresses( return out; } +/** The shielded address on one network, as its bech32m string. */ +export function deriveShieldedAddressString(seedBuffer: Buffer, networkName: NetworkName): string { + return MidnightBech32m.encode(networkIdForName(networkName), deriveShieldedAddress(seedBuffer)).asString(); +} + /** * Derive the raw `ShieldedAddress` (SDK type) from a seed. Cheap — pure * key derivation, no facade or network needed. Use when you need an diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts new file mode 100644 index 00000000..021cd512 --- /dev/null +++ b/src/engine/rc/index.ts @@ -0,0 +1,15 @@ +// The engine for the SDK's release candidates (rc): the wallet SDK 2.0 +// release candidates, ledger 9 and midnight-js 5 as mn pins them. + +import type { Engine } from '../../lib/engine.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; + +export const rcEngine: Engine = { + set: 'rc', + keys: { + unshieldedAddress: deriveUnshieldedAddress, + unshieldedAddresses: deriveAllAddresses, + shieldedAddress: deriveShieldedAddressString, + shieldedAddresses: deriveAllShieldedAddresses, + }, +}; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 8d7a313d..f3f1038c 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -148,16 +148,16 @@ async function generateWallet(name: string, signal?: AbortSignal): Promise const passphrase = await passphraseForNewSecret(); // Cancelled while the passphrase was asked for: no wallet is written. throwIfCancelled(signal); - createWallet(name, walletSecretFrom(), passphrase); + await createWallet(name, walletSecretFrom(), passphrase); } async function airdropToWallet(network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { - const recipientAddress = loadWalletConfig(resolveWalletPath(name)).addresses.undeployed; + const recipientAddress = (await loadWalletConfig(resolveWalletPath(name))).addresses.undeployed; await airdropNight({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings }); } async function walletNeedsDust(network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { - const address = loadWalletConfig(resolveWalletPath(name)).addresses.undeployed; + const address = (await loadWalletConfig(resolveWalletPath(name))).addresses.undeployed; const { registeredUtxos, unregisteredUtxos } = await checkBalance(address, network.indexerWS, undefined, signal); return registeredUtxos === 0 && unregisteredUtxos > 0; } diff --git a/src/lib/dust-direct-cache.ts b/src/lib/dust-direct-cache.ts index b6bfad33..cc25af0f 100644 --- a/src/lib/dust-direct-cache.ts +++ b/src/lib/dust-direct-cache.ts @@ -15,7 +15,7 @@ import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { deriveDustSeed } from './derivation.ts'; +import { deriveDustSeed } from '../engine/rc/derivation.ts'; import { type DustRetention } from './dust-direct.ts'; import { cacheKeyOf, cacheRootDir } from './wallet-cache.ts'; diff --git a/src/lib/dust-sync-native.ts b/src/lib/dust-sync-native.ts index ebaaa1b5..b4c6ece7 100644 --- a/src/lib/dust-sync-native.ts +++ b/src/lib/dust-sync-native.ts @@ -14,7 +14,7 @@ import { fileURLToPath } from 'node:url'; import * as ledger from '@midnightntwrk/ledger-v9'; import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { deriveDustSeed } from './derivation.ts'; +import { deriveDustSeed } from '../engine/rc/derivation.ts'; import type { NetworkConfig } from './network.ts'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; diff --git a/src/lib/engine.ts b/src/lib/engine.ts new file mode 100644 index 00000000..3e948ee3 --- /dev/null +++ b/src/lib/engine.ts @@ -0,0 +1,58 @@ +// The Midnight SDK, behind one interface. Everything that touches an SDK set +// is an engine's; the rest of mn reaches it through the engine for its +// network, and names no SDK type. One engine today, for the SDK's release +// candidates (rc). The interface grows area by area as code moves behind it. +// Loading an engine loads its SDK, so the loader imports it only when asked. + +import type { NetworkName } from './network.ts'; + +/** An SDK set mn runs on. */ +export type SdkSet = 'rc'; + +/** A wallet's keys and addresses, derived from its seed. Every set derives the same ones. */ +export interface EngineKeys { + /** The unshielded address of the seed's key at `keyIndex` (default 0) on a network. */ + unshieldedAddress(seed: Buffer, network: NetworkName, keyIndex?: number): string; + /** The first unshielded address on every network. */ + unshieldedAddresses(seed: Buffer, keyIndex?: number): Record; + /** The shielded address on a network. */ + shieldedAddress(seed: Buffer, network: NetworkName): string; + /** The shielded address on every network. */ + shieldedAddresses(seed: Buffer): Record; +} + +/** One SDK set, as mn uses it. */ +export interface Engine { + readonly set: SdkSet; + readonly keys: EngineKeys; +} + +/** The SDK set a network runs on. */ +export function sdkSetOf(_network: NetworkName): SdkSet { + return 'rc'; +} + +// The engine this process has loaded: one per process, since two SDK sets' +// WASM ledgers can't share one. +let loaded: Promise | undefined; + +function loadEngine(set: SdkSet): Promise { + loaded ??= import('../engine/rc/index.ts').then((module) => module.rcEngine); + return loaded.then((engine) => { + if (engine.set !== set) throw new Error(`This process runs the ${engine.set} SDK set and can't load the ${set} one`); + return engine; + }); +} + +/** The engine for a network's SDK set, loaded on first use. */ +export function engineFor(network: NetworkName): Promise { + return loadEngine(sdkSetOf(network)); +} + +/** + * An engine for work every set does alike, such as deriving addresses: the + * one this process has loaded, else the rc set's. + */ +export function anyEngine(): Promise { + return loaded ?? loadEngine('rc'); +} diff --git a/src/lib/facade.ts b/src/lib/facade.ts index c2ee7389..57b3970d 100644 --- a/src/lib/facade.ts +++ b/src/lib/facade.ts @@ -21,7 +21,7 @@ import * as rx from 'rxjs'; import { type NetworkConfig } from './network.ts'; import { FORK_SCHEDULE } from './fork-schedule.ts'; import { getNetworkId } from './network-id.ts'; -import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; +import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from '../engine/rc/derivation.ts'; import { type WalletCacheData } from './wallet-cache.ts'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; import { diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index c36f8921..dc0c5813 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -198,7 +198,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise [--shielded] [--wallet] [--network]`, checked without touching the chain. */ -export function resolveTransferRequest(args: ParsedArgs): TransferRequest { +export async function resolveTransferRequest(args: ParsedArgs): Promise { const recipientInput = args.subcommand; const amountStr = args.positionals[0]; @@ -45,10 +45,10 @@ export function resolveTransferRequest(args: ParsedArgs): TransferRequest { } const shielded = hasFlag(args, 'shielded'); - const recipientAddress = resolveRecipient(recipientInput, args, shielded); + const recipientAddress = await resolveRecipient(recipientInput, args, shielded); const amountNight = parseAmount(amountStr); const walletPath = resolveWalletPath(getFlag(args, 'wallet')); - const walletConfig = loadWalletConfig(walletPath); + const walletConfig = await loadWalletConfig(walletPath); const networkName = resolveNetworkName({ args }); if (shielded) { @@ -89,12 +89,12 @@ function decodeUnshieldedRecipient(address: string, networkName: NetworkName): U * An address (mn_addr_ or mn_shield-addr_ prefix) is used as given. Anything * else is a wallet name, and the address comes from that wallet's file. */ -function resolveRecipient(input: string, args: ParsedArgs, shielded: boolean): string { +async function resolveRecipient(input: string, args: ParsedArgs, shielded: boolean): Promise { if (input.startsWith('mn_addr_') || input.startsWith('mn_shield-addr_')) { return input; } - const recipientConfig = loadWalletConfig(resolveWalletPath(input)); + const recipientConfig = await loadWalletConfig(resolveWalletPath(input)); const networkName = resolveNetworkName({ args }); if (shielded) { diff --git a/src/lib/wallet-config.ts b/src/lib/wallet-config.ts index c31af991..7637c2c0 100644 --- a/src/lib/wallet-config.ts +++ b/src/lib/wallet-config.ts @@ -5,7 +5,7 @@ import { DEFAULT_WALLET_FILENAME, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, FILE_MO import { type NetworkName } from './network.ts'; import { loadCliConfig, saveCliConfig } from './cli-config.ts'; import { getDefaultWalletPath, getWalletsDir } from './wallet-paths.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from './derive-address.ts'; +import { anyEngine, type EngineKeys } from './engine.ts'; import { isSealedSecret, openSecret, sealSecret } from './keystore.ts'; import { FileExistsError, writeJsonDurably } from './durable-file.ts'; import { type PassphraseSource, unlockPassphrase } from './passphrase.ts'; @@ -138,16 +138,19 @@ export function setActiveWallet(name: string): void { /** * List all wallets in ~/.midnight/wallets/. */ -export function listWallets(): WalletInfo[] { +export async function listWallets(): Promise { const walletsDir = getWalletsDir(); if (!fs.existsSync(walletsDir)) { return []; } + // Only a plain-text wallet's missing addresses are derived, and so need the SDK. + let keys: EngineKeys | undefined; + const engineKeys = async (): Promise => (keys ??= (await anyEngine()).keys); const activeName = getActiveWalletName(); const files = fs.readdirSync(walletsDir).filter(f => f.endsWith('.json')).sort(); - return files.map(file => { + return Promise.all(files.map(async (file) => { const name = file.replace(/\.json$/, ''); const filePath = path.join(walletsDir, file); try { @@ -160,7 +163,7 @@ export function listWallets(): WalletInfo[] { // Old format — derive all addresses from seed try { const seedBuffer = Buffer.from(content.seed, 'hex'); - addresses = deriveAllAddresses(seedBuffer); + addresses = (await engineKeys()).unshieldedAddresses(seedBuffer); } catch { addresses = { undeployed: content.address, preprod: '(unknown)', preview: '(unknown)' } as Record; } @@ -173,7 +176,7 @@ export function listWallets(): WalletInfo[] { shieldedAddresses = content.shieldedAddresses; } else if (content.seed) { try { - shieldedAddresses = deriveAllShieldedAddresses(Buffer.from(content.seed, 'hex')); + shieldedAddresses = (await engineKeys()).shieldedAddresses(Buffer.from(content.seed, 'hex')); } catch { /* best-effort */ } } return { @@ -192,7 +195,7 @@ export function listWallets(): WalletInfo[] { file: filePath, }; } - }); + })); } /** @@ -221,10 +224,10 @@ export function matchWalletAddress( * Locate the saved wallet that owns an address (across all networks), if any. * Convenience wrapper over matchWalletAddress + listWallets. */ -export function findWalletByAddress( +export async function findWalletByAddress( address: string, -): { wallet: WalletInfo; network: NetworkName } | undefined { - return matchWalletAddress(listWallets(), address); +): Promise<{ wallet: WalletInfo; network: NetworkName } | undefined> { + return matchWalletAddress(await listWallets(), address); } /** @@ -288,7 +291,7 @@ export function assertWalletFileExists(resolvedPath: string): void { * Throws with an actionable message if file is missing or invalid. * Callers should use resolveWalletPath() to get the path first. */ -export function loadWalletConfig(walletPath?: string): WalletConfig { +export async function loadWalletConfig(walletPath?: string): Promise { const resolvedPath = walletPath ? path.resolve(walletPath) : getDefaultWalletPath(); @@ -348,14 +351,14 @@ export function loadWalletConfig(walletPath?: string): WalletConfig { } // Old format — derive all addresses from seed const seedBuffer = Buffer.from(raw.seed, 'hex'); - const addresses = deriveAllAddresses(seedBuffer); + const addresses = (await anyEngine()).keys.unshieldedAddresses(seedBuffer); const config: WalletConfig = { addresses, createdAt: raw.createdAt, isSealed: false, }; - const shieldedAddresses = resolveShieldedAddresses(raw, seedBuffer); + const shieldedAddresses = await resolveShieldedAddresses(raw, seedBuffer); if (shieldedAddresses) config.shieldedAddresses = shieldedAddresses; // Write back migrated format (keep old fields for backwards compat) @@ -383,7 +386,7 @@ export function loadWalletConfig(walletPath?: string): WalletConfig { }; const seedBuffer = Buffer.from(raw.seed, 'hex'); - const shieldedAddresses = resolveShieldedAddresses(raw, seedBuffer); + const shieldedAddresses = await resolveShieldedAddresses(raw, seedBuffer); if (shieldedAddresses) config.shieldedAddresses = shieldedAddresses; // One-time backfill: if the file is missing shieldedAddresses (or only has @@ -413,13 +416,14 @@ export function loadWalletConfig(walletPath?: string): WalletConfig { * future seed format ever changes encoding without changing the seed itself, * preferring stored values protects external tools that read the file directly. */ -function resolveShieldedAddresses( +async function resolveShieldedAddresses( raw: any, seedBuffer: Buffer, -): Record | undefined { +): Promise | undefined> { let derived: Record | undefined; + const { keys } = await anyEngine(); try { - derived = deriveAllShieldedAddresses(seedBuffer); + derived = keys.shieldedAddresses(seedBuffer); } catch { /* derivation can fail on malformed seeds */ } const storedRaw = raw.shieldedAddresses; @@ -464,9 +468,9 @@ export function writeSealedWallet(walletPath: string, wallet: WalletPublic, secr * field it holds. What was sealed is opened again before the file is * replaced, so a wallet is never left unreadable. A sealed wallet is left as it is. */ -export function sealWalletInPlace(walletPath: string, passphrase: string): boolean { +export async function sealWalletInPlace(walletPath: string, passphrase: string): Promise { const resolvedPath = path.resolve(walletPath); - const config = loadWalletConfig(resolvedPath); + const config = await loadWalletConfig(resolvedPath); if (config.isSealed) return false; const raw = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8')); const secrets: WalletSecrets = typeof raw.mnemonic === 'string' ? { seed: raw.seed, mnemonic: raw.mnemonic } : { seed: raw.seed }; @@ -502,7 +506,7 @@ export async function protectAllWallets(root: string, passphrase: string, signal // Sealing runs synchronously; a cancellation that came meanwhile lands here, before the next wallet. await new Promise((resolve) => setImmediate(resolve)); throwIfCancelled(signal); - report.push({ name, file, sealedNow: sealWalletInPlace(file, passphrase) }); + report.push({ name, file, sealedNow: await sealWalletInPlace(file, passphrase) }); } return report; } @@ -520,7 +524,7 @@ const warnedPlain = new Set(); /** A wallet with its secrets: opened with mn's passphrase, or read as it is from a plain-text file an earlier mn wrote. */ export async function unlockWallet(walletPath: string, options: UnlockOptions = {}): Promise { const resolvedPath = path.resolve(walletPath); - const config = loadWalletConfig(resolvedPath); + const config = await loadWalletConfig(resolvedPath); const raw = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8')); if (!config.isSealed) { if (!warnedPlain.has(resolvedPath) || options.warn !== undefined) { diff --git a/src/lib/wallet-create.ts b/src/lib/wallet-create.ts index a325d85a..e311f87f 100644 --- a/src/lib/wallet-create.ts +++ b/src/lib/wallet-create.ts @@ -6,7 +6,7 @@ import * as path from 'path'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from './derive-address.ts'; +import { anyEngine } from './engine.ts'; import { writeSealedWallet, setActiveWallet, type WalletPublic } from './wallet-config.ts'; import { isValidWalletName } from './constants.ts'; import { getWalletsDir } from './wallet-paths.ts'; @@ -54,10 +54,11 @@ export function walletSecretFrom(given: { seed?: Buffer; mnemonic?: string } = { * Writes the wallet `name` sealed under `passphrase` and makes it the active * wallet. An existing wallet of that name is replaced only with `overwrite`. */ -export function createWallet(name: string, secret: WalletSecret, passphrase: string, { overwrite = false }: { overwrite?: boolean } = {}): CreatedWallet { +export async function createWallet(name: string, secret: WalletSecret, passphrase: string, { overwrite = false }: { overwrite?: boolean } = {}): Promise { const targetPath = walletFilePath(name); - const addresses = deriveAllAddresses(secret.seed); - const shieldedAddresses = deriveAllShieldedAddresses(secret.seed); + const { keys } = await anyEngine(); + const addresses = keys.unshieldedAddresses(secret.seed); + const shieldedAddresses = keys.shieldedAddresses(secret.seed); const config: WalletPublic = { addresses, shieldedAddresses, createdAt: new Date().toISOString() }; const seedHex = secret.seed.toString('hex'); const secrets = secret.mnemonic ? { seed: seedHex, mnemonic: secret.mnemonic } : { seed: seedHex }; diff --git a/src/lib/wallet-data-repository.ts b/src/lib/wallet-data-repository.ts index 9ab1927a..26749044 100644 --- a/src/lib/wallet-data-repository.ts +++ b/src/lib/wallet-data-repository.ts @@ -56,8 +56,8 @@ import { bindCachesToIndexer, describeIndexerChange } from './cache-indexer.ts'; import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; import type { VerboseLog } from './verbose.ts'; import { callNodeRpc } from './node-rpc.ts'; -import { deriveDustSeed } from './derivation.ts'; -import { deriveUnshieldedAddress } from './derive-address.ts'; +import { deriveDustSeed } from '../engine/rc/derivation.ts'; +import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from './event-tip.ts'; // ── Public types ────────────────────────────────────────── From d82fd5465204a114a21c486e11bce804fe1af3e9 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:17:48 -0800 Subject: [PATCH 22/88] Engine, part 2: reading the ledger's bytes - The block limits in a chain's ledger parameters are the engine's (ledger.blockLimits); chain-params only reads the bytes from the indexer, and inspect-cost asks the engine for the chain's set. - The fee-only check and the transaction summary for approval prompts move into the rc engine as they are: only the connector and the sign recipe use them, and both move behind the engine later. Four modules leave the pending list. No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.mjs | 4 -- src/__tests__/fee-only-check.test.ts | 2 +- src/__tests__/fee-only-signing.test.ts | 2 +- src/__tests__/layering.test.ts | 4 -- src/__tests__/sign-recipe.test.ts | 2 +- src/commands/inspect-cost.ts | 52 +++--------------------- src/{lib => engine/rc}/fee-only-check.ts | 0 src/engine/rc/index.ts | 4 ++ src/engine/rc/ledger-parameters.ts | 29 +++++++++++++ src/{lib => engine/rc}/tx-inspect.ts | 6 +-- src/lib/chain-params.ts | 13 +++--- src/lib/dapp-connector.ts | 4 +- src/lib/engine.ts | 22 ++++++++++ src/lib/sign-recipe.ts | 2 +- 14 files changed, 76 insertions(+), 70 deletions(-) rename src/{lib => engine/rc}/fee-only-check.ts (100%) create mode 100644 src/engine/rc/ledger-parameters.ts rename src/{lib => engine/rc}/tx-inspect.ts (96%) diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 4b352ece..b8e55e08 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -106,9 +106,7 @@ export const PENDING_ENGINE = new Set([ 'commands/airdrop.ts', 'commands/balance.ts', 'commands/dust.ts', - 'commands/inspect-cost.ts', 'commands/transfer.ts', - 'lib/chain-params.ts', 'lib/contract/providers.ts', 'lib/contract/runner.ts', 'lib/dapp-connector.ts', @@ -119,7 +117,6 @@ export const PENDING_ENGINE = new Set([ 'lib/dust-sync-native.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', - 'lib/fee-only-check.ts', 'lib/fork-schedule.ts', 'lib/grant/sealed-account.ts', 'lib/shielded-direct-cache.ts', @@ -128,7 +125,6 @@ export const PENDING_ENGINE = new Set([ 'lib/test/prep-runner.ts', 'lib/transfer-request.ts', 'lib/transfer.ts', - 'lib/tx-inspect.ts', 'lib/wallet-data-repository.ts', 'lib/ws-rpc.ts', ]); diff --git a/src/__tests__/fee-only-check.test.ts b/src/__tests__/fee-only-check.test.ts index 796ceeba..36c6e2a9 100644 --- a/src/__tests__/fee-only-check.test.ts +++ b/src/__tests__/fee-only-check.test.ts @@ -14,7 +14,7 @@ import { shieldedToken, signData, } from '@midnightntwrk/ledger-v9'; -import { expiredIntents, feeOnlyRefusals, readDAppTransaction } from '../lib/fee-only-check.ts'; +import { expiredIntents, feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; import { AGENT_SK, AGENT_VK, NETWORK, NIGHT, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, sealedBytes, spend, unsealedBytes, diff --git a/src/__tests__/fee-only-signing.test.ts b/src/__tests__/fee-only-signing.test.ts index e36c313d..f9bcffa4 100644 --- a/src/__tests__/fee-only-signing.test.ts +++ b/src/__tests__/fee-only-signing.test.ts @@ -23,7 +23,7 @@ import { type SignatureVerifyingKey, } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { feeOnlyRefusals, readDAppTransaction } from '../lib/fee-only-check.ts'; +import { feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; import { signRecipe } from '../lib/sign-recipe.ts'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index cf0d0c72..facb694b 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -53,9 +53,7 @@ describe('the layering', () => { 'commands/airdrop.ts', 'commands/balance.ts', 'commands/dust.ts', - 'commands/inspect-cost.ts', 'commands/transfer.ts', - 'lib/chain-params.ts', 'lib/contract/providers.ts', 'lib/contract/runner.ts', 'lib/dapp-connector.ts', @@ -66,7 +64,6 @@ describe('the layering', () => { 'lib/dust-sync-native.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', - 'lib/fee-only-check.ts', 'lib/fork-schedule.ts', 'lib/grant/sealed-account.ts', 'lib/shielded-direct-cache.ts', @@ -75,7 +72,6 @@ describe('the layering', () => { 'lib/test/prep-runner.ts', 'lib/transfer-request.ts', 'lib/transfer.ts', - 'lib/tx-inspect.ts', 'lib/wallet-data-repository.ts', 'lib/ws-rpc.ts', ]); diff --git a/src/__tests__/sign-recipe.test.ts b/src/__tests__/sign-recipe.test.ts index 596dcd87..6f692463 100644 --- a/src/__tests__/sign-recipe.test.ts +++ b/src/__tests__/sign-recipe.test.ts @@ -20,7 +20,7 @@ import { type SignatureVerifyingKey, } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { feeOnlyRefusals, readDAppTransaction } from '../lib/fee-only-check.ts'; +import { feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; import { PartlySignedTransactionError, SignedTransactionNeedsUnshieldedError, assertSignable, signRecipe, unshieldedImbalanceSegments, unshieldedSignatures, } from '../lib/sign-recipe.ts'; diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 0249936f..8561a15d 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -1,58 +1,16 @@ // inspect-cost command — display the chain's current block limits, from the -// ledger parameters of its latest block. Uses the probeDimension technique -// from the reference implementation. +// ledger parameters of its latest block, as the engine for the chain's SDK +// set reads them. import { type ParsedArgs, hasFlag } from '../lib/argv.ts'; -import * as ledger from '@midnightntwrk/ledger-v9'; import { header, keyValue, divider } from '../ui/format.ts'; import { bold, dim } from '../ui/colors.ts'; import type { CallContext } from '../lib/call-context.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { fetchLedgerParameters } from '../lib/chain-params.ts'; +import { engineFor } from '../lib/engine.ts'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; -interface SyntheticCost { - readTime: bigint; - computeTime: bigint; - blockUsage: bigint; - bytesWritten: bigint; - bytesChurned: bigint; -} - -/** - * Probe a single block limit dimension by reverse-engineering normalizeFullness. - * normalized = value / limit → limit = value / normalized - */ -function probeDimension( - params: ledger.LedgerParameters, - dimension: keyof SyntheticCost, - probeValue: bigint, -): number { - const cost: SyntheticCost = { - readTime: 0n, - computeTime: 0n, - blockUsage: 0n, - bytesWritten: 0n, - bytesChurned: 0n, - }; - cost[dimension] = probeValue; - - // Cast required: our SyntheticCost shape matches the ledger type but TS can't verify the opaque SDK type - const normalized = params.normalizeFullness(cost as unknown as ledger.SyntheticCost); - const normalizedValue = (normalized as Record)[dimension]!; - return Math.round(Number(probeValue) / normalizedValue); -} - -function deriveBlockLimits(params: ledger.LedgerParameters) { - return { - readTime: probeDimension(params, 'readTime', 1_000_000_000n), - computeTime: probeDimension(params, 'computeTime', 1_000_000_000n), - blockUsage: probeDimension(params, 'blockUsage', 10_000n), - bytesWritten: probeDimension(params, 'bytesWritten', 10_000n), - bytesChurned: probeDimension(params, 'bytesChurned', 1_000_000n), - }; -} - const UNITS: Record = { readTime: 'picoseconds', computeTime: 'picoseconds', @@ -65,8 +23,8 @@ export default async function inspectCostCommand(args: ParsedArgs, ctx: CallCont const { name: networkName, config } = resolveNetwork({ args }); // A ledger-8 chain's parameters aren't ledger-9 ones: refuse it like every other chain read. await assertLedgerSupported(networkName, config, fetchProtocolVersion, ctx.signal); - const { height, params } = await fetchLedgerParameters(config.indexer, ctx.signal); - const limits = deriveBlockLimits(params); + const { height, parametersHex } = await fetchLedgerParameters(config.indexer, ctx.signal); + const limits = (await engineFor(networkName)).ledger.blockLimits(parametersHex); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/lib/fee-only-check.ts b/src/engine/rc/fee-only-check.ts similarity index 100% rename from src/lib/fee-only-check.ts rename to src/engine/rc/fee-only-check.ts diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index 021cd512..b3c9aadd 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -2,6 +2,7 @@ // release candidates, ledger 9 and midnight-js 5 as mn pins them. import type { Engine } from '../../lib/engine.ts'; +import { blockLimitsOf } from './ledger-parameters.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; export const rcEngine: Engine = { @@ -12,4 +13,7 @@ export const rcEngine: Engine = { shieldedAddress: deriveShieldedAddressString, shieldedAddresses: deriveAllShieldedAddresses, }, + ledger: { + blockLimits: blockLimitsOf, + }, }; diff --git a/src/engine/rc/ledger-parameters.ts b/src/engine/rc/ledger-parameters.ts new file mode 100644 index 00000000..2d32b92a --- /dev/null +++ b/src/engine/rc/ledger-parameters.ts @@ -0,0 +1,29 @@ +// A chain's block limits, from its ledger parameters' bytes. The ledger +// doesn't expose the limits themselves, so each is probed through +// normalizeFullness: normalized = value / limit, so limit = value / normalized. + +import * as ledger from '@midnightntwrk/ledger-v9'; +import type { BlockLimits } from '../../lib/engine.ts'; + +type Dimension = keyof BlockLimits; + +function probeDimension(params: ledger.LedgerParameters, dimension: Dimension, probeValue: bigint): number { + const cost: Record = { readTime: 0n, computeTime: 0n, blockUsage: 0n, bytesWritten: 0n, bytesChurned: 0n }; + cost[dimension] = probeValue; + // Cast required: the shape matches the ledger's SyntheticCost, which TS can't verify for the opaque SDK type. + const normalized = params.normalizeFullness(cost as unknown as ledger.SyntheticCost); + const normalizedValue = (normalized as Record)[dimension]!; + return Math.round(Number(probeValue) / normalizedValue); +} + +/** The block limits in serialized ledger parameters (hex). Throws when the bytes aren't this ledger's parameters. */ +export function blockLimitsOf(parametersHex: string): BlockLimits { + const params = ledger.LedgerParameters.deserialize(Buffer.from(parametersHex, 'hex')); + return { + readTime: probeDimension(params, 'readTime', 1_000_000_000n), + computeTime: probeDimension(params, 'computeTime', 1_000_000_000n), + blockUsage: probeDimension(params, 'blockUsage', 10_000n), + bytesWritten: probeDimension(params, 'bytesWritten', 10_000n), + bytesChurned: probeDimension(params, 'bytesChurned', 1_000_000n), + }; +} diff --git a/src/lib/tx-inspect.ts b/src/engine/rc/tx-inspect.ts similarity index 96% rename from src/lib/tx-inspect.ts rename to src/engine/rc/tx-inspect.ts index a6da3ab6..5a6f1428 100644 --- a/src/lib/tx-inspect.ts +++ b/src/engine/rc/tx-inspect.ts @@ -2,15 +2,15 @@ // Used by the DApp Connector approval prompt to show Lace-style transaction summaries import { Transaction } from '@midnightntwrk/ledger-v9'; -import type { ApprovalDetail } from './approval.ts'; +import type { TransactionDetail } from '../../lib/engine.ts'; /** * Try to extract structured details from a transaction hex string. * Returns an array of label/value pairs for the approval prompt. * Falls back gracefully — never throws. */ -export function inspectTxHex(txHex: string, stage: 'unsealed' | 'sealed'): ApprovalDetail[] { - const details: ApprovalDetail[] = []; +export function inspectTxHex(txHex: string, stage: 'unsealed' | 'sealed'): TransactionDetail[] { + const details: TransactionDetail[] = []; details.push({ label: 'Tx size', value: formatBytes(txHex.length / 2) }); const summary = tryDeserializeAndSummarize(txHex, stage); diff --git a/src/lib/chain-params.ts b/src/lib/chain-params.ts index a16bf718..812a7b97 100644 --- a/src/lib/chain-params.ts +++ b/src/lib/chain-params.ts @@ -1,14 +1,15 @@ // The chain's current ledger parameters (block limits, fee prices), as the -// indexer serves them for the latest block. They differ from -// LedgerParameters.initialParameters(): on a ledger-9 localnet the block -// limits for read time and block usage are 2x and 5x the initial ones. +// indexer serves them for the latest block, still serialized: the engine for +// the chain's SDK set reads them. They differ from the ledger's initial +// parameters: on a ledger-9 localnet the block limits for read time and +// block usage are 2x and 5x the initial ones. -import * as ledger from '@midnightntwrk/ledger-v9'; import { queryIndexer } from './indexer-graphql.ts'; export interface ChainLedgerParameters { height: number; - params: ledger.LedgerParameters; + /** The serialized ledger parameters, hex. */ + parametersHex: string; } /** The latest block's ledger parameters. Throws IndexerQueryError when the indexer can't answer, CancelledError when `signal` cancels the read. */ @@ -19,5 +20,5 @@ export async function fetchLedgerParameters(indexerHttpUrl: string, signal?: Abo if (typeof hex !== 'string' || typeof data.block?.height !== 'number') { throw new Error('The indexer returned no ledger parameters for its latest block'); } - return { height: data.block.height, params: ledger.LedgerParameters.deserialize(Buffer.from(hex, 'hex')) }; + return { height: data.block.height, parametersHex: hex }; } diff --git a/src/lib/dapp-connector.ts b/src/lib/dapp-connector.ts index ea8e73b3..076cb0b6 100644 --- a/src/lib/dapp-connector.ts +++ b/src/lib/dapp-connector.ts @@ -18,8 +18,8 @@ import { toHex, fromHex } from './tx-serde.ts'; import { getNetworkId } from './network-id.ts'; import { isDustShortage } from './sdk-errors.ts'; import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from './fee-limits.ts'; -import { inspectTxHex } from './tx-inspect.ts'; -import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; +import { inspectTxHex } from '../engine/rc/tx-inspect.ts'; +import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from '../engine/rc/fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; import { decodeSignPayload, signedMessageBytes } from './sign-data.ts'; import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from './dust-wait.ts'; diff --git a/src/lib/engine.ts b/src/lib/engine.ts index 3e948ee3..7d4bd17a 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -21,10 +21,32 @@ export interface EngineKeys { shieldedAddresses(seed: Buffer): Record; } +/** A line of what a transaction is, as an approval prompt shows it. */ +export interface TransactionDetail { + label: string; + value: string; +} + +/** A chain's block limits: time in picoseconds, the rest in bytes. */ +export interface BlockLimits { + readTime: number; + computeTime: number; + blockUsage: number; + bytesWritten: number; + bytesChurned: number; +} + +/** What an engine reads from the ledger's serialized values. */ +export interface EngineLedger { + /** The block limits in serialized ledger parameters (hex), as the indexer serves them. Throws when the bytes aren't this set's ledger parameters. */ + blockLimits(parametersHex: string): BlockLimits; +} + /** One SDK set, as mn uses it. */ export interface Engine { readonly set: SdkSet; readonly keys: EngineKeys; + readonly ledger: EngineLedger; } /** The SDK set a network runs on. */ diff --git a/src/lib/sign-recipe.ts b/src/lib/sign-recipe.ts index 65d88789..6d3b174d 100644 --- a/src/lib/sign-recipe.ts +++ b/src/lib/sign-recipe.ts @@ -20,7 +20,7 @@ import type { Signature } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { readDAppTransaction, segmentsOf, unshieldedInputs, type FeeCheckTransaction } from './fee-only-check.ts'; +import { readDAppTransaction, segmentsOf, unshieldedInputs, type FeeCheckTransaction } from '../engine/rc/fee-only-check.ts'; export type SignSegment = (data: Uint8Array) => Promise; From 7d23a93fd1caf2b7020a067b80523cc2cff67d8d Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:21:04 -0800 Subject: [PATCH 23/88] Engine, part 3: the Dust and shielded readers - mn's own Dust and shielded readers, their caches, the Dust collapse and the native sidecar's glue move into the rc engine. So does the unused direct Dust balance reader, as it is (deleting it is for the owner to approve). - Where the readers keep their caches, and clearing them, needs no SDK: it is reader-cache-files.ts in core, beside wallet-cache.ts and cache-indexer.ts, which the engine uses and which move to core with it. mn cache clear names caches through the engine's keys (dustPublicKeyHex, shieldedCoinPublicKeyHex), and so do dust export and wallet protect. Seven modules leave the pending list. No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.mjs | 11 +- src/__tests__/chain-reset-clearing.test.ts | 4 +- .../contract-script-packages.test.ts | 2 +- src/__tests__/dust-collapse.test.ts | 2 +- src/__tests__/dust-direct-cache.test.ts | 9 +- src/__tests__/dust-export.test.ts | 4 +- src/__tests__/dust-sync-native.test.ts | 2 +- src/__tests__/layering.test.ts | 7 - src/__tests__/shielded-direct-cache.test.ts | 9 +- src/__tests__/shielded-direct.test.ts | 2 +- src/__tests__/state-root.test.ts | 4 +- src/__tests__/wallet-data-repository.test.ts | 2 +- .../wallet-state-to-restore.live.test.ts | 2 +- src/commands/balance.ts | 2 +- src/commands/cache.ts | 10 +- src/commands/dust.ts | 2 +- src/{lib => engine/rc}/dust-balance-direct.ts | 4 +- src/{lib => engine/rc}/dust-collapse.ts | 0 src/{lib => engine/rc}/dust-direct-cache.ts | 61 +------ src/{lib => engine/rc}/dust-direct.ts | 6 +- src/{lib => engine/rc}/dust-sync-native.ts | 40 +---- src/engine/rc/index.ts | 4 + .../rc}/shielded-direct-cache.ts | 65 +------- src/{lib => engine/rc}/shielded-direct.ts | 2 +- src/lib/chain-caches.ts | 6 +- src/lib/dust-export.ts | 4 +- src/lib/engine.ts | 4 + src/lib/facade.ts | 2 +- src/lib/reader-cache-files.ts | 154 ++++++++++++++++++ src/lib/wallet-data-repository.ts | 13 +- src/lib/wallet-protector.ts | 6 +- 31 files changed, 221 insertions(+), 224 deletions(-) rename src/{lib => engine/rc}/dust-balance-direct.ts (98%) rename src/{lib => engine/rc}/dust-collapse.ts (100%) rename src/{lib => engine/rc}/dust-direct-cache.ts (78%) rename src/{lib => engine/rc}/dust-direct.ts (98%) rename src/{lib => engine/rc}/dust-sync-native.ts (87%) rename src/{lib => engine/rc}/shielded-direct-cache.ts (80%) rename src/{lib => engine/rc}/shielded-direct.ts (98%) create mode 100644 src/lib/reader-cache-files.ts diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index b8e55e08..bdf5c364 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -42,7 +42,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], @@ -50,7 +50,7 @@ const HOMES = [ ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription)\.ts$/], ['wallet', /^commands\/(wallet|generate|address|genesis-address|info|balance|transfer|airdrop|dust|cache)(\.definition)?\.ts$/], - ['wallet', /^lib\/(derivation|derive-address|wallet-config|seed-resolver|passphrase|facade|wallet-data-repository|wallet-cache|cache-indexer|transfer|transfer-request|sync-eta|wallet-can-pay|wallet-create|airdrop|wallet-protector|chain-caches|wallet-paths|fork-schedule)\.ts$/], + ['wallet', /^lib\/(derivation|derive-address|wallet-config|seed-resolver|passphrase|facade|wallet-data-repository|transfer|transfer-request|sync-eta|wallet-can-pay|wallet-create|airdrop|wallet-protector|chain-caches|wallet-paths|fork-schedule)\.ts$/], ['wallet', /^lib\/(dust-[a-z-]+|shielded-[a-z-]+)\.ts$/], ['contract', /^commands\/(contract|inspect-cost)(\.definition)?\.ts$/], @@ -110,17 +110,10 @@ export const PENDING_ENGINE = new Set([ 'lib/contract/providers.ts', 'lib/contract/runner.ts', 'lib/dapp-connector.ts', - 'lib/dust-balance-direct.ts', - 'lib/dust-collapse.ts', - 'lib/dust-direct-cache.ts', - 'lib/dust-direct.ts', - 'lib/dust-sync-native.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', 'lib/fork-schedule.ts', 'lib/grant/sealed-account.ts', - 'lib/shielded-direct-cache.ts', - 'lib/shielded-direct.ts', 'lib/sign-recipe.ts', 'lib/test/prep-runner.ts', 'lib/transfer-request.ts', diff --git a/src/__tests__/chain-reset-clearing.test.ts b/src/__tests__/chain-reset-clearing.test.ts index d2cb109e..9f89e99b 100644 --- a/src/__tests__/chain-reset-clearing.test.ts +++ b/src/__tests__/chain-reset-clearing.test.ts @@ -8,8 +8,8 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { clearChainCaches } from '../lib/chain-caches.ts'; import { getCachePath } from '../lib/wallet-cache.ts'; -import { getDustCachePath } from '../lib/dust-direct-cache.ts'; -import { getShieldedCachePath } from '../lib/shielded-direct-cache.ts'; +import { getDustCachePath } from '../lib/reader-cache-files.ts'; +import { getShieldedCachePath } from '../lib/reader-cache-files.ts'; import { PRIVATE_STATE_DATABASE, clearDappPrivateState } from '../lib/contract/private-state.ts'; let dir: string; diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index e02590b0..bb5502f3 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -24,7 +24,7 @@ import { scriptRuntime, undoOverlay, } from '../lib/contract/runner.ts'; -import { platformPackageBinary } from '../lib/dust-sync-native.ts'; +import { platformPackageBinary } from '../engine/rc/dust-sync-native.ts'; const NETWORK = { indexer: 'http://localhost:28088/api/v4/graphql', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', node: 'ws://localhost:29944', proofServer: 'http://localhost:26300', networkId: 'Undeployed' }; let dir: string; diff --git a/src/__tests__/dust-collapse.test.ts b/src/__tests__/dust-collapse.test.ts index ac58e476..84c49e33 100644 --- a/src/__tests__/dust-collapse.test.ts +++ b/src/__tests__/dust-collapse.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { computeForeignRanges, collapseForeignGenerations } from '../lib/dust-collapse.ts'; +import { computeForeignRanges, collapseForeignGenerations } from '../engine/rc/dust-collapse.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; // Same initial dust params the sync path uses (dust-direct.ts). diff --git a/src/__tests__/dust-direct-cache.test.ts b/src/__tests__/dust-direct-cache.test.ts index 44a9e4cc..35994996 100644 --- a/src/__tests__/dust-direct-cache.test.ts +++ b/src/__tests__/dust-direct-cache.test.ts @@ -7,13 +7,8 @@ import * as path from 'path'; import * as os from 'os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { - loadDustCache, - saveDustCache, - clearDustDirectCache, - getDustCachePath, - dustPublicKeyHex, -} from '../lib/dust-direct-cache.ts'; +import { loadDustCache, saveDustCache, dustPublicKeyHex } from '../engine/rc/dust-direct-cache.ts'; +import { clearDustDirectCache, getDustCachePath } from '../lib/reader-cache-files.ts'; const CACHE_DIR = path.join(os.tmpdir(), `midnight-dust-cache-test-${process.pid}-${Date.now()}`); const NETWORK = 'undeployed'; diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index e42fea71..832c8610 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; import { overlayDustDirectSnapshot } from '../lib/facade.ts'; -import type { DustCacheEntry } from '../lib/dust-direct-cache.ts'; +import type { DustCacheEntry } from '../engine/rc/dust-direct-cache.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; // overlayDustDirectSnapshot is the seam behind `dust export` (and the write-command @@ -99,7 +99,7 @@ import { join } from 'node:path'; import { exportDustSnapshot } from '../lib/dust-export.ts'; import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; import type { NetworkConfig } from '../lib/network.ts'; -import type { DustDirectResult } from '../lib/dust-direct.ts'; +import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; const EXPORT_NETWORK: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', diff --git a/src/__tests__/dust-sync-native.test.ts b/src/__tests__/dust-sync-native.test.ts index 544f4361..cedbb65e 100644 --- a/src/__tests__/dust-sync-native.test.ts +++ b/src/__tests__/dust-sync-native.test.ts @@ -10,7 +10,7 @@ import { nativeDustSyncAvailable, runDustSyncNative, type SidecarCheckpoint, -} from '../lib/dust-sync-native.ts'; +} from '../engine/rc/dust-sync-native.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; describe('resumeDecision (kill-safe resume)', () => { diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index facb694b..3d2cda76 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -57,17 +57,10 @@ describe('the layering', () => { 'lib/contract/providers.ts', 'lib/contract/runner.ts', 'lib/dapp-connector.ts', - 'lib/dust-balance-direct.ts', - 'lib/dust-collapse.ts', - 'lib/dust-direct-cache.ts', - 'lib/dust-direct.ts', - 'lib/dust-sync-native.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', 'lib/fork-schedule.ts', 'lib/grant/sealed-account.ts', - 'lib/shielded-direct-cache.ts', - 'lib/shielded-direct.ts', 'lib/sign-recipe.ts', 'lib/test/prep-runner.ts', 'lib/transfer-request.ts', diff --git a/src/__tests__/shielded-direct-cache.test.ts b/src/__tests__/shielded-direct-cache.test.ts index de2097fc..54d263b4 100644 --- a/src/__tests__/shielded-direct-cache.test.ts +++ b/src/__tests__/shielded-direct-cache.test.ts @@ -3,13 +3,8 @@ import { mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync, mkdirSync import { join } from 'node:path'; import { tmpdir } from 'node:os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { - shieldedCoinPublicKeyHexFromSeed, - getShieldedCachePath, - loadShieldedCache, - saveShieldedCache, - clearShieldedDirectCache, -} from '../lib/shielded-direct-cache.ts'; +import { shieldedCoinPublicKeyHexFromSeed, loadShieldedCache, saveShieldedCache } from '../engine/rc/shielded-direct-cache.ts'; +import { getShieldedCachePath, clearShieldedDirectCache } from '../lib/reader-cache-files.ts'; const PUBKEY = 'aabbccddeeff00112233445566778899aabbccddeeff001122334455667788ff'; const OTHER_PUBKEY = '1122334455667788112233445566778811223344556677881122334455667788'; diff --git a/src/__tests__/shielded-direct.test.ts b/src/__tests__/shielded-direct.test.ts index a93ef5aa..37e900c2 100644 --- a/src/__tests__/shielded-direct.test.ts +++ b/src/__tests__/shielded-direct.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; import type { AddressInfo } from 'node:net'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { readShieldedBalanceDirect } from '../lib/shielded-direct.ts'; +import { readShieldedBalanceDirect } from '../engine/rc/shielded-direct.ts'; import { deriveShieldedSeed } from '../engine/rc/derivation.ts'; import zswapEvents from './fixtures/zswap-events-localnet.json'; diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 35db5310..0c706308 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -16,8 +16,8 @@ import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import { accountRecordsDir } from '../lib/grant/account-records.ts'; import { accountArtifactsDir } from '../lib/grant/account.ts'; import { getCachePath } from '../lib/wallet-cache.ts'; -import { getDustCachePath } from '../lib/dust-direct-cache.ts'; -import { getShieldedCachePath } from '../lib/shielded-direct-cache.ts'; +import { getDustCachePath } from '../lib/reader-cache-files.ts'; +import { getShieldedCachePath } from '../lib/reader-cache-files.ts'; import { getComposePath } from '../lib/localnet.ts'; import { MIDNIGHT_DIR } from '../lib/constants.ts'; import before from './fixtures/state-layout-before-1g.json'; diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index 0da6ba81..3d62c3ad 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -14,7 +14,7 @@ import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps import { UnsupportedLedgerError } from '../lib/ledger-guard.ts'; import type { NetworkConfig } from '../lib/network.ts'; import type { BalanceSummary } from '../lib/balance-subscription.ts'; -import type { DustDirectResult } from '../lib/dust-direct.ts'; +import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; // ── Test fixtures ───────────────────────────────────────── diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index 8b75471c..54f3da67 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import * as ledger from '@midnightntwrk/ledger-v9'; import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; -import { dustPublicKeyHexFromSeed, saveDustCache } from '../lib/dust-direct-cache.ts'; +import { dustPublicKeyHexFromSeed, saveDustCache } from '../engine/rc/dust-direct-cache.ts'; import type { NetworkConfig } from '../lib/network.ts'; import { parseArgs } from '../lib/argv.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 36722618..33498422 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -13,7 +13,7 @@ import { shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-pol import { getNetworkId } from '../lib/network-id.ts'; import { isNativeToken } from '../lib/balance-subscription.ts'; import { defaultRepository } from '../lib/wallet-data-repository.ts'; -import { readShieldedBalanceCached } from '../lib/shielded-direct-cache.ts'; +import { readShieldedBalanceCached } from '../engine/rc/shielded-direct-cache.ts'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; import { deriveShieldedAddress, deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { getChainGenesisHash } from '../lib/chain-id.ts'; diff --git a/src/commands/cache.ts b/src/commands/cache.ts index 41c37bb7..df4a1b1a 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -4,9 +4,8 @@ import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; import { UsageError, throwIfCancelled } from '../lib/errors.ts'; import { clearWalletCache } from '../lib/wallet-cache.ts'; -import { clearDustDirectCache, dustPublicKeyHexFromSeed } from '../lib/dust-direct-cache.ts'; -import { clearShieldedDirectCache, shieldedCoinPublicKeyHexFromSeed } from '../lib/shielded-direct-cache.ts'; -import { clearNativeDustCheckpoint } from '../lib/dust-sync-native.ts'; +import { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from '../lib/reader-cache-files.ts'; +import { engineFor } from '../lib/engine.ts'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetworkName } from '../lib/resolve-network.ts'; import { green } from '../ui/colors.ts'; @@ -36,11 +35,12 @@ export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): const address = config.addresses[networkName]; clearWalletCache(address, networkName); // Also clear the dust-direct cache for this wallet on this network. - const dustPubkey = dustPublicKeyHexFromSeed(Buffer.from(config.seed, 'hex')); + const { keys } = await engineFor(networkName); + const dustPubkey = keys.dustPublicKeyHex(Buffer.from(config.seed, 'hex')); clearDustDirectCache(networkName, dustPubkey); clearNativeDustCheckpoint(networkName, dustPubkey); // And the shielded-direct cache (keyed by the wallet's coin public key). - const shieldedPubkey = shieldedCoinPublicKeyHexFromSeed(Buffer.from(config.seed, 'hex')); + const shieldedPubkey = keys.shieldedCoinPublicKeyHex(Buffer.from(config.seed, 'hex')); clearShieldedDirectCache(networkName, shieldedPubkey); if (jsonMode) { ctx.output.result({ action: 'clear', scope: 'wallet', wallet: walletFlag, network: networkName }); diff --git a/src/commands/dust.ts b/src/commands/dust.ts index bcf47e63..880d2302 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -12,7 +12,7 @@ import { applyEndpointOverrides, type NetworkConfig } from '../lib/network.ts'; import { deriveDustSeed } from '../engine/rc/derivation.ts'; import { registerDust } from '../lib/dust-register.ts'; import { checkBalance } from '../lib/balance-subscription.ts'; -import { dustPublicKeyHex } from '../lib/dust-direct-cache.ts'; +import { dustPublicKeyHex } from '../engine/rc/dust-direct-cache.ts'; import { exportDustSnapshot } from '../lib/dust-export.ts'; import { defaultRepository } from '../lib/wallet-data-repository.ts'; import { header, keyValue, divider, formatDust, successMessage, toDust } from '../ui/format.ts'; diff --git a/src/lib/dust-balance-direct.ts b/src/engine/rc/dust-balance-direct.ts similarity index 98% rename from src/lib/dust-balance-direct.ts rename to src/engine/rc/dust-balance-direct.ts index 1cb8f863..cb34fb8c 100644 --- a/src/lib/dust-balance-direct.ts +++ b/src/engine/rc/dust-balance-direct.ts @@ -24,8 +24,8 @@ import { INITIAL_NIGHT_DUST_RATIO, INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from './constants.ts'; -import { subscribeGraphqlWs } from './graphql-ws-subscription.ts'; +} from '../../lib/constants.ts'; +import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; const SUBSCRIPTION_QUERY = ` subscription DustGenerations($a: DustAddress!, $s: Int!, $e: Int!) { diff --git a/src/lib/dust-collapse.ts b/src/engine/rc/dust-collapse.ts similarity index 100% rename from src/lib/dust-collapse.ts rename to src/engine/rc/dust-collapse.ts diff --git a/src/lib/dust-direct-cache.ts b/src/engine/rc/dust-direct-cache.ts similarity index 78% rename from src/lib/dust-direct-cache.ts rename to src/engine/rc/dust-direct-cache.ts index cc25af0f..e1d0c82d 100644 --- a/src/lib/dust-direct-cache.ts +++ b/src/engine/rc/dust-direct-cache.ts @@ -14,10 +14,10 @@ import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { deriveDustSeed } from '../engine/rc/derivation.ts'; +import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; +import { deriveDustSeed } from './derivation.ts'; import { type DustRetention } from './dust-direct.ts'; -import { cacheKeyOf, cacheRootDir } from './wallet-cache.ts'; +import { dustCacheDir, getDustCachePath } from '../../lib/reader-cache-files.ts'; // v2 added the retention fields (owned generation indices + frontier) that the // generation-tree collapse needs. v1 caches lack them and are invalidated, so @@ -65,19 +65,6 @@ export function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string { return dustPublicKeyHex(sk.publicKey); } -function dustCacheDir(network: string, cacheDir?: string): string { - const base = cacheRootDir(cacheDir); - return join(base, network); -} - -export function getDustCachePath( - network: string, - pubkeyHex: string, - cacheDir?: string, -): string { - const prefix = cacheKeyOf(pubkeyHex); - return join(dustCacheDir(network, cacheDir), `dust-${prefix}.json`); -} /** * Load a cached DustLocalState for the given (network, dust pubkey). @@ -194,45 +181,3 @@ export function validateDustCacheChainId( return wiped; } -/** - * Remove dust-direct cache files. Scope: - * - (network, pubkeyHex) → single file - * - (network) → all dust-* files in that network dir - * - (neither) → all dust-* files across all networks - */ -export function clearDustDirectCache( - network?: string, - pubkeyHex?: string, - cacheDir?: string, -): void { - const base = cacheRootDir(cacheDir); - - if (network && pubkeyHex) { - const path = getDustCachePath(network, pubkeyHex, cacheDir); - try { unlinkSync(path); } catch { /* not found is ok */ } - return; - } - - const wipeNetworkDir = (dir: string) => { - if (!existsSync(dir)) return; - try { - for (const file of readdirSync(dir)) { - if (file.startsWith('dust-') && file.endsWith('.json')) { - try { unlinkSync(join(dir, file)); } catch { /* best-effort */ } - } - } - } catch { /* best-effort */ } - }; - - if (network) { - wipeNetworkDir(dustCacheDir(network, cacheDir)); - return; - } - - if (!existsSync(base)) return; - try { - for (const net of readdirSync(base)) { - wipeNetworkDir(join(base, net)); - } - } catch { /* best-effort */ } -} diff --git a/src/lib/dust-direct.ts b/src/engine/rc/dust-direct.ts similarity index 98% rename from src/lib/dust-direct.ts rename to src/engine/rc/dust-direct.ts index d08a70d7..084b7079 100644 --- a/src/lib/dust-direct.ts +++ b/src/engine/rc/dust-direct.ts @@ -16,9 +16,9 @@ import { INITIAL_NIGHT_DUST_RATIO, INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from './constants.ts'; -import { subscribeGraphqlWs } from './graphql-ws-subscription.ts'; -import { settings } from './settings.ts'; +} from '../../lib/constants.ts'; +import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; +import { settings } from '../../lib/settings.ts'; // MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): settings().isDustCollapseOff. diff --git a/src/lib/dust-sync-native.ts b/src/engine/rc/dust-sync-native.ts similarity index 87% rename from src/lib/dust-sync-native.ts rename to src/engine/rc/dust-sync-native.ts index b4c6ece7..ac9fc537 100644 --- a/src/lib/dust-sync-native.ts +++ b/src/engine/rc/dust-sync-native.ts @@ -4,7 +4,7 @@ // fails, callers fall back to the WASM path — the sidecar is an optional // accelerator, never a hard dependency. -import { assertEndpointUsable } from './blockfrost.ts'; +import { assertEndpointUsable } from '../../lib/blockfrost.ts'; import { spawn } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; @@ -13,14 +13,15 @@ import { fileURLToPath } from 'node:url'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { deriveDustSeed } from '../engine/rc/derivation.ts'; -import type { NetworkConfig } from './network.ts'; +import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; +import { deriveDustSeed } from './derivation.ts'; +import type { NetworkConfig } from '../../lib/network.ts'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { settings } from './settings.ts'; -import { cacheKeyOf, cacheRootDir } from './wallet-cache.ts'; +import { settings } from '../../lib/settings.ts'; +import { cacheRootDir } from '../../lib/wallet-cache.ts'; +import { nativeCheckpointName } from '../../lib/reader-cache-files.ts'; /** Sidecar checkpoint JSON shape (snake_case — matches the Rust `Checkpoint`). */ export interface SidecarCheckpoint { @@ -124,7 +125,6 @@ function readCheckpointCursor(path: string): number { } /** The sidecar's checkpoint file for a Dust key, beside the other Dust caches. */ -const nativeCheckpointName = (pubkeyHex: string): string => `dust-native-${cacheKeyOf(pubkeyHex)}.json`; function nativeCheckpointPath(networkName: string, pubkeyHex: string, cacheDir?: string): string { const dir = join(cacheRootDir(cacheDir), networkName); @@ -132,32 +132,6 @@ function nativeCheckpointPath(networkName: string, pubkeyHex: string, cacheDir?: return join(dir, nativeCheckpointName(pubkeyHex)); } -/** - * Remove native-sidecar checkpoint files (`dust-native-*.json`). Scope mirrors - * `clearDustDirectCache`: (network, pubkey) → one file; (network) → that network; - * (neither) → all. Called from `mn cache clear` so clearing the cache also forces - * a fresh native sync (and drops a stale checkpoint after a chain reset). - */ -export function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, cacheDir?: string): void { - const base = cacheRootDir(cacheDir); - if (network && pubkeyHex) { - try { unlinkSync(join(base, network, nativeCheckpointName(pubkeyHex))); } catch { /* not found is ok */ } - return; - } - const wipeDir = (dir: string) => { - if (!existsSync(dir)) return; - try { - for (const f of readdirSync(dir)) { - if (f.startsWith('dust-native-') && f.endsWith('.json')) { - try { unlinkSync(join(dir, f)); } catch { /* best-effort */ } - } - } - } catch { /* best-effort */ } - }; - if (network) { wipeDir(join(base, network)); return; } - if (!existsSync(base)) return; - try { for (const net of readdirSync(base)) wipeDir(join(base, net)); } catch { /* best-effort */ } -} /** * Run the native sidecar for a dust sync and adapt to `DustDirectResult`. diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index b3c9aadd..6453ed4d 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -3,6 +3,8 @@ import type { Engine } from '../../lib/engine.ts'; import { blockLimitsOf } from './ledger-parameters.ts'; +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; export const rcEngine: Engine = { @@ -12,6 +14,8 @@ export const rcEngine: Engine = { unshieldedAddresses: deriveAllAddresses, shieldedAddress: deriveShieldedAddressString, shieldedAddresses: deriveAllShieldedAddresses, + dustPublicKeyHex: dustPublicKeyHexFromSeed, + shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, }, ledger: { blockLimits: blockLimitsOf, diff --git a/src/lib/shielded-direct-cache.ts b/src/engine/rc/shielded-direct-cache.ts similarity index 80% rename from src/lib/shielded-direct-cache.ts rename to src/engine/rc/shielded-direct-cache.ts index beb2581c..b0bd000d 100644 --- a/src/lib/shielded-direct-cache.ts +++ b/src/engine/rc/shielded-direct-cache.ts @@ -9,18 +9,18 @@ // Security: the cached state contains owned coins but NOT the secret keys. Same // sensitivity as the wallet file (mode 0o600). -import { bindCachesToIndexer } from './cache-indexer.ts'; +import { bindCachesToIndexer } from '../../lib/cache-indexer.ts'; import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { deriveShieldedSeed } from '../engine/rc/derivation.ts'; +import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; +import { deriveShieldedSeed } from './derivation.ts'; import { readShieldedBalanceDirect, type ShieldedDirectOptions } from './shielded-direct.ts'; -import { fetchEventTip, isCursorBeyondTip } from './event-tip.ts'; -import { cacheKeyOf, cacheRootDir } from './wallet-cache.ts'; +import { fetchEventTip, isCursorBeyondTip } from '../../lib/event-tip.ts'; +import { clearShieldedDirectCache, getShieldedCachePath } from '../../lib/reader-cache-files.ts'; // v2: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis // hash, so the chain-id guard can't keep a ledger-8 cache off a ledger-9 chain. @@ -51,19 +51,6 @@ export function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string { return keys.coinPublicKey; } -function shieldedCacheDir(network: string, cacheDir?: string): string { - const base = cacheRootDir(cacheDir); - return join(base, network); -} - -export function getShieldedCachePath( - network: string, - pubkeyHex: string, - cacheDir?: string, -): string { - const prefix = cacheKeyOf(pubkeyHex); - return join(shieldedCacheDir(network, cacheDir), `shielded-${prefix}.json`); -} /** * Load a cached ZswapLocalState for the given (network, coin pubkey). @@ -135,48 +122,6 @@ export function saveShieldedCache( } } -/** - * Remove shielded-direct cache files. Scope: - * - (network, pubkeyHex) → single file - * - (network) → all shielded-* files in that network dir - * - (neither) → all shielded-* files across all networks - */ -export function clearShieldedDirectCache( - network?: string, - pubkeyHex?: string, - cacheDir?: string, -): void { - const base = cacheRootDir(cacheDir); - - if (network && pubkeyHex) { - const path = getShieldedCachePath(network, pubkeyHex, cacheDir); - try { unlinkSync(path); } catch { /* not found is ok */ } - return; - } - - const wipeNetworkDir = (dir: string) => { - if (!existsSync(dir)) return; - try { - for (const file of readdirSync(dir)) { - if (file.startsWith('shielded-') && file.endsWith('.json')) { - try { unlinkSync(join(dir, file)); } catch { /* best-effort */ } - } - } - } catch { /* best-effort */ } - }; - - if (network) { - wipeNetworkDir(shieldedCacheDir(network, cacheDir)); - return; - } - - if (!existsSync(base)) return; - try { - for (const net of readdirSync(base)) { - wipeNetworkDir(join(base, net)); - } - } catch { /* best-effort */ } -} export interface ShieldedBalanceResult { /** Native (NIGHT) shielded balance in atomic units. */ diff --git a/src/lib/shielded-direct.ts b/src/engine/rc/shielded-direct.ts similarity index 98% rename from src/lib/shielded-direct.ts rename to src/engine/rc/shielded-direct.ts index 1c77f5ec..bf55da57 100644 --- a/src/lib/shielded-direct.ts +++ b/src/engine/rc/shielded-direct.ts @@ -14,7 +14,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; -import { subscribeGraphqlWs } from './graphql-ws-subscription.ts'; +import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; const SUBSCRIPTION_QUERY = ` subscription ZswapLedgerEvents($id: Int) { diff --git a/src/lib/chain-caches.ts b/src/lib/chain-caches.ts index e6a9ae32..a08bdcd3 100644 --- a/src/lib/chain-caches.ts +++ b/src/lib/chain-caches.ts @@ -4,9 +4,9 @@ // `cache clear` clears the same set. import { clearWalletCache } from './wallet-cache.ts'; -import { clearDustDirectCache } from './dust-direct-cache.ts'; -import { clearShieldedDirectCache } from './shielded-direct-cache.ts'; -import { clearNativeDustCheckpoint } from './dust-sync-native.ts'; +import { clearDustDirectCache } from './reader-cache-files.ts'; +import { clearShieldedDirectCache } from './reader-cache-files.ts'; +import { clearNativeDustCheckpoint } from './reader-cache-files.ts'; /** * Clears every wallet cache kept for `network` (all networks when undefined): diff --git a/src/lib/dust-export.ts b/src/lib/dust-export.ts index 5033c6bc..25878b85 100644 --- a/src/lib/dust-export.ts +++ b/src/lib/dust-export.ts @@ -17,7 +17,7 @@ // // Pure logic: returns values, never writes to stdout/stderr or exits. -import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { anyEngine } from './engine.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; import { type NetworkConfig } from './network.ts'; import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; @@ -91,7 +91,7 @@ export async function exportDustSnapshot( networkConfig: NetworkConfig, options: DustExportOptions = {}, ): Promise { - const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); + const pubkeyHex = (await anyEngine()).keys.dustPublicKeyHex(seedBuffer); const repo = options.repository ?? defaultRepository(); const view = await repo.dust(seedBuffer, networkConfig, { diff --git a/src/lib/engine.ts b/src/lib/engine.ts index 7d4bd17a..871a992e 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -19,6 +19,10 @@ export interface EngineKeys { shieldedAddress(seed: Buffer, network: NetworkName): string; /** The shielded address on every network. */ shieldedAddresses(seed: Buffer): Record; + /** The Dust public key, hex: what the Dust reader's cache is named by. */ + dustPublicKeyHex(seed: Buffer): string; + /** The shielded coin public key, hex: what the shielded reader's cache is named by. */ + shieldedCoinPublicKeyHex(seed: Buffer): string; } /** A line of what a transaction is, as an approval prompt shows it. */ diff --git a/src/lib/facade.ts b/src/lib/facade.ts index 57b3970d..9c59aef1 100644 --- a/src/lib/facade.ts +++ b/src/lib/facade.ts @@ -23,7 +23,7 @@ import { FORK_SCHEDULE } from './fork-schedule.ts'; import { getNetworkId } from './network-id.ts'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from '../engine/rc/derivation.ts'; import { type WalletCacheData } from './wallet-cache.ts'; -import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; +import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from '../engine/rc/dust-direct-cache.ts'; import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, diff --git a/src/lib/reader-cache-files.ts b/src/lib/reader-cache-files.ts new file mode 100644 index 00000000..e355d921 --- /dev/null +++ b/src/lib/reader-cache-files.ts @@ -0,0 +1,154 @@ +// Where the Dust and shielded readers keep their caches under the state root, +// and how they are cleared. Plain files, named by network and public key, so +// clearing them needs no SDK: the engine that reads and writes them does. + +import { existsSync, readdirSync, unlinkSync } from 'node:fs'; +import { join } from 'node:path'; +import { cacheKeyOf, cacheRootDir } from './wallet-cache.ts'; + +/** The folder of a network's reader caches. */ +export function dustCacheDir(network: string, cacheDir?: string): string { + const base = cacheRootDir(cacheDir); + return join(base, network); +} + +/** The Dust reader's cache file for a network and Dust public key. */ +export function getDustCachePath( + network: string, + pubkeyHex: string, + cacheDir?: string, +): string { + const prefix = cacheKeyOf(pubkeyHex); + return join(dustCacheDir(network, cacheDir), `dust-${prefix}.json`); +} + +/** + * Remove dust-direct cache files. Scope: + * - (network, pubkeyHex) → single file + * - (network) → all dust-* files in that network dir + * - (neither) → all dust-* files across all networks + */ +export function clearDustDirectCache( + network?: string, + pubkeyHex?: string, + cacheDir?: string, +): void { + const base = cacheRootDir(cacheDir); + + if (network && pubkeyHex) { + const path = getDustCachePath(network, pubkeyHex, cacheDir); + try { unlinkSync(path); } catch { /* not found is ok */ } + return; + } + + const wipeNetworkDir = (dir: string) => { + if (!existsSync(dir)) return; + try { + for (const file of readdirSync(dir)) { + if (file.startsWith('dust-') && file.endsWith('.json')) { + try { unlinkSync(join(dir, file)); } catch { /* best-effort */ } + } + } + } catch { /* best-effort */ } + }; + + if (network) { + wipeNetworkDir(dustCacheDir(network, cacheDir)); + return; + } + + if (!existsSync(base)) return; + try { + for (const net of readdirSync(base)) { + wipeNetworkDir(join(base, net)); + } + } catch { /* best-effort */ } +} + +function shieldedCacheDir(network: string, cacheDir?: string): string { + const base = cacheRootDir(cacheDir); + return join(base, network); +} + +/** The shielded reader's cache file for a network and coin public key. */ +export function getShieldedCachePath( + network: string, + pubkeyHex: string, + cacheDir?: string, +): string { + const prefix = cacheKeyOf(pubkeyHex); + return join(shieldedCacheDir(network, cacheDir), `shielded-${prefix}.json`); +} + +/** + * Remove shielded-direct cache files. Scope: + * - (network, pubkeyHex) → single file + * - (network) → all shielded-* files in that network dir + * - (neither) → all shielded-* files across all networks + */ +export function clearShieldedDirectCache( + network?: string, + pubkeyHex?: string, + cacheDir?: string, +): void { + const base = cacheRootDir(cacheDir); + + if (network && pubkeyHex) { + const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + try { unlinkSync(path); } catch { /* not found is ok */ } + return; + } + + const wipeNetworkDir = (dir: string) => { + if (!existsSync(dir)) return; + try { + for (const file of readdirSync(dir)) { + if (file.startsWith('shielded-') && file.endsWith('.json')) { + try { unlinkSync(join(dir, file)); } catch { /* best-effort */ } + } + } + } catch { /* best-effort */ } + }; + + if (network) { + wipeNetworkDir(shieldedCacheDir(network, cacheDir)); + return; + } + + if (!existsSync(base)) return; + try { + for (const net of readdirSync(base)) { + wipeNetworkDir(join(base, net)); + } + } catch { /* best-effort */ } +} + +/** The native sidecar's checkpoint file for a Dust public key. */ +export const nativeCheckpointName = (pubkeyHex: string): string => `dust-native-${cacheKeyOf(pubkeyHex)}.json`; + +/** + * Remove native-sidecar checkpoint files (`dust-native-*.json`). Scope mirrors + * `clearDustDirectCache`: (network, pubkey) → one file; (network) → that network; + * (neither) → all. Called from `mn cache clear` so clearing the cache also forces + * a fresh native sync (and drops a stale checkpoint after a chain reset). + */ +export function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, cacheDir?: string): void { + const base = cacheRootDir(cacheDir); + if (network && pubkeyHex) { + try { unlinkSync(join(base, network, nativeCheckpointName(pubkeyHex))); } catch { /* not found is ok */ } + return; + } + const wipeDir = (dir: string) => { + if (!existsSync(dir)) return; + try { + for (const f of readdirSync(dir)) { + if (f.startsWith('dust-native-') && f.endsWith('.json')) { + try { unlinkSync(join(dir, f)); } catch { /* best-effort */ } + } + } + } catch { /* best-effort */ } + }; + if (network) { wipeDir(join(base, network)); return; } + if (!existsSync(base)) return; + try { for (const net of readdirSync(base)) wipeDir(join(base, net)); } catch { /* best-effort */ } +} diff --git a/src/lib/wallet-data-repository.ts b/src/lib/wallet-data-repository.ts index 26749044..a884bee3 100644 --- a/src/lib/wallet-data-repository.ts +++ b/src/lib/wallet-data-repository.ts @@ -34,13 +34,8 @@ import { overlayDustDirectSnapshot, } from './facade.ts'; import { isColdStartRace } from './sdk-errors.ts'; -import { - loadDustCache, - saveDustCache, - dustPublicKeyHexFromSeed, - validateDustCacheChainId, - clearDustDirectCache, -} from './dust-direct-cache.ts'; +import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from '../engine/rc/dust-direct-cache.ts'; +import { clearDustDirectCache } from './reader-cache-files.ts'; import { loadWalletCache, saveWalletCache, @@ -51,9 +46,9 @@ import { import { getChainGenesisHash } from './chain-id.ts'; import { assertLedgerSupported, fetchProtocolVersion } from './ledger-guard.ts'; import { checkBalance, type BalanceSummary } from './balance-subscription.ts'; -import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; +import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from '../engine/rc/dust-direct.ts'; import { bindCachesToIndexer, describeIndexerChange } from './cache-indexer.ts'; -import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; +import { nativeDustSyncAvailable, runDustSyncNative } from '../engine/rc/dust-sync-native.ts'; import type { VerboseLog } from './verbose.ts'; import { callNodeRpc } from './node-rpc.ts'; import { deriveDustSeed } from '../engine/rc/derivation.ts'; diff --git a/src/lib/wallet-protector.ts b/src/lib/wallet-protector.ts index b4948bf2..a8cbf80c 100644 --- a/src/lib/wallet-protector.ts +++ b/src/lib/wallet-protector.ts @@ -32,7 +32,7 @@ export type WalletCommandContext = CallContext; /** The shielded coin public key of the wallet `name`, unlocked with mn's passphrase. */ export async function coinKeyOfWallet(name: string): Promise { - // Loaded here, not up front: it brings in the ledger, which the other wallet subcommands don't need. - const { shieldedCoinPublicKeyHexFromSeed } = await import('./shielded-direct-cache.ts'); - return shieldedCoinPublicKeyHexFromSeed(Buffer.from((await unlockWallet(resolveWalletPath(name))).seed, 'hex')); + // The engine loads the SDK, which the other wallet subcommands don't need: loaded here, not up front. + const { anyEngine } = await import('./engine.ts'); + return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(name))).seed, 'hex')); } From a0557b6340b02e71296c498fa08c76dbb384f70b Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:25:31 -0800 Subject: [PATCH 24/88] Engine, part 4: contracts' raw state, addresses, and the stragglers - contract state's raw fallback asks the engine (contracts.rawState), which reads it with its own midnight-js provider and returns plain JSON; the raw-state reader and the provider move into the engine. - A transfer's recipient is checked by the engine (keys.assertAddress); the transfer command still decodes it with the engine's own function until the transfer moves. - grant's private-state password is drawn until the engine's policy (midnight-js's) accepts it, instead of grant importing midnight-js. - test prep reads NIGHT's token id from the engine. - The connector's wire types (error codes, APIError) are owned by its transport, with a test keeping them equal to the DApp Connector API's. Five modules leave the pending list (twelve left). No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.mjs | 5 ---- src/__tests__/account-backup.test.ts | 3 +- src/__tests__/contract-raw-state.test.ts | 2 +- src/__tests__/layering.test.ts | 5 ---- src/__tests__/sealed-account.test.ts | 5 ++-- src/__tests__/ws-rpc-api-types.test.ts | 21 +++++++++++++ src/commands/contract.ts | 13 +++----- src/commands/transfer.ts | 5 ++-- src/engine/rc/addresses.ts | 22 ++++++++++++++ .../rc/contract-providers.ts} | 12 ++++++-- src/engine/rc/index.ts | 17 +++++++++++ src/{lib/contract => engine/rc}/raw-state.ts | 9 ++---- src/lib/engine.ts | 23 +++++++++++++- src/lib/grant/account-backup.ts | 3 +- src/lib/grant/account.ts | 5 +++- src/lib/grant/protect-account.ts | 3 +- src/lib/grant/sealed-account.ts | 24 +++++++-------- src/lib/payer.ts | 4 +-- src/lib/test/prep-runner.ts | 4 +-- src/lib/transfer-request.ts | 30 +++++-------------- src/lib/ws-rpc.ts | 15 +++++++++- 21 files changed, 152 insertions(+), 78 deletions(-) create mode 100644 src/__tests__/ws-rpc-api-types.test.ts create mode 100644 src/engine/rc/addresses.ts rename src/{lib/contract/providers.ts => engine/rc/contract-providers.ts} (51%) rename src/{lib/contract => engine/rc}/raw-state.ts (85%) diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index bdf5c364..274438e0 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -107,19 +107,14 @@ export const PENDING_ENGINE = new Set([ 'commands/balance.ts', 'commands/dust.ts', 'commands/transfer.ts', - 'lib/contract/providers.ts', 'lib/contract/runner.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', 'lib/fork-schedule.ts', - 'lib/grant/sealed-account.ts', 'lib/sign-recipe.ts', - 'lib/test/prep-runner.ts', - 'lib/transfer-request.ts', 'lib/transfer.ts', 'lib/wallet-data-repository.ts', - 'lib/ws-rpc.ts', ]); const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; const SDK_FREE = new Set(['core', 'chain']); diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index 8e4d2e41..e065be2e 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -7,6 +7,7 @@ // passphrase it was made with. import * as fs from 'node:fs'; +import { rcEngine } from '../engine/rc/index.ts'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -60,7 +61,7 @@ beforeEach(async () => { store.writeOwner(RECORD); store.writeRoster(ROSTER); sealedDeviceKeys(fromDir, key).keep(freshOwnerDevice('k1')); - sealedPrivateStatePassword(fromDir, key); + sealedPrivateStatePassword(fromDir, key, rcEngine.contracts.acceptsPrivateStatePassword); await (await privateStateIn(here, fromDir)).privateState.set(PRIVATE_STATE_ID, PRIVATE_STATE as never); }); afterEach(() => { diff --git a/src/__tests__/contract-raw-state.test.ts b/src/__tests__/contract-raw-state.test.ts index 1087e969..f3447c9b 100644 --- a/src/__tests__/contract-raw-state.test.ts +++ b/src/__tests__/contract-raw-state.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { ChargedState, ContractState, StateBoundedMerkleTree, StateMap, StateValue } from '@midnight-ntwrk/compact-runtime'; -import { describeRawState } from '../lib/contract/raw-state.ts'; +import { describeRawState } from '../engine/rc/raw-state.ts'; const atom = (bytes: number[]) => ({ value: [new Uint8Array(bytes)], alignment: [{ tag: 'atom' as const, value: { tag: 'bytes' as const, length: bytes.length } }] }); diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 3d2cda76..32e62da1 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -54,19 +54,14 @@ describe('the layering', () => { 'commands/balance.ts', 'commands/dust.ts', 'commands/transfer.ts', - 'lib/contract/providers.ts', 'lib/contract/runner.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', 'lib/fork-schedule.ts', - 'lib/grant/sealed-account.ts', 'lib/sign-recipe.ts', - 'lib/test/prep-runner.ts', - 'lib/transfer-request.ts', 'lib/transfer.ts', 'lib/wallet-data-repository.ts', - 'lib/ws-rpc.ts', ]); expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); }); diff --git a/src/__tests__/sealed-account.test.ts b/src/__tests__/sealed-account.test.ts index b7bc2349..5e2b25b6 100644 --- a/src/__tests__/sealed-account.test.ts +++ b/src/__tests__/sealed-account.test.ts @@ -7,6 +7,7 @@ // node:test as that suite is written. import { execFileSync } from 'node:child_process'; +import { rcEngine } from '../engine/rc/index.ts'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -101,10 +102,10 @@ describe("the account's owner key", () => { describe("the account's private-state password", () => { it('is made once, meets midnight-js\'s policy, is sealed, and reads back the same', () => { const key = createAccountKey(dir, PASSPHRASE); - const password = sealedPrivateStatePassword(dir, key); + const password = sealedPrivateStatePassword(dir, key, rcEngine.contracts.acceptsPrivateStatePassword); expect(() => validatePassword(password)).not.toThrow(); expect(filesText()).not.toContain(password); - expect(sealedPrivateStatePassword(dir, key)).toBe(password); + expect(sealedPrivateStatePassword(dir, key, rcEngine.contracts.acceptsPrivateStatePassword)).toBe(password); }); }); diff --git a/src/__tests__/ws-rpc-api-types.test.ts b/src/__tests__/ws-rpc-api-types.test.ts new file mode 100644 index 00000000..568374f7 --- /dev/null +++ b/src/__tests__/ws-rpc-api-types.test.ts @@ -0,0 +1,21 @@ +// The connector's wire types are the DApp Connector API specification's: the +// transport owns its copy so no SDK package is imported outside the engine, +// and this test keeps the copy equal to the specification's. + +import { describe, expect, expectTypeOf, it } from 'vitest'; +import { ErrorCodes, type APIError as SpecAPIError, type ErrorCode as SpecErrorCode } from '@midnightntwrk/dapp-connector-api'; +import type { APIError, ErrorCode } from '../lib/ws-rpc.ts'; +import { createApiError } from '../lib/ws-rpc.ts'; + +describe("the connector's API types", () => { + it('name exactly the error codes the specification names', () => { + expectTypeOf().toEqualTypeOf(); + const codes: ErrorCode[] = ['InternalError', 'Rejected', 'InvalidRequest', 'PermissionRejected', 'Disconnected']; + expect([...codes].sort()).toStrictEqual(Object.values(ErrorCodes).sort()); + }); + + it("are the specification's error", () => { + expectTypeOf().toEqualTypeOf(); + expect(createApiError('Rejected', 'no')).toMatchObject({ type: 'DAppConnectorAPIError', code: 'Rejected', reason: 'no', message: 'no' }); + }); +}); diff --git a/src/commands/contract.ts b/src/commands/contract.ts index caaf3216..acdfe298 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -12,7 +12,7 @@ import { type Payer, payerFor, resolvePayingTarget } from '../lib/payer.ts'; import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { validateContractAddress } from '../lib/contract/validate.ts'; -import type { RawStateValue } from '../lib/contract/raw-state.ts'; +import { engineFor, type RawStateValue } from '../lib/engine.ts'; import { resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; import { findContractInfo, @@ -293,18 +293,13 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { // If runner fails (no compiled contract in cwd), fall back to raw state spinner.stop(yellow('⚠') + ' Parsed state unavailable, showing raw'); - const { buildStateProvider } = await import('../lib/contract/providers.ts'); - const publicDataProvider = buildStateProvider(networkConfig); - // The provider's query takes no signal: the call stops waiting for it when cancelled. - const contractState = await untilCancelled(publicDataProvider.queryContractState(address), ctx.signal); + // The engine's query takes no signal: the call stops waiting for it when cancelled. + const raw = await untilCancelled((await engineFor(network)).contracts.rawState(networkConfig, address), ctx.signal); - if (!contractState) { + if (!raw) { throw new Error(`No contract found at address ${address} on ${network}`); } - const { describeRawState } = await import('../lib/contract/raw-state.ts'); - const raw = describeRawState(contractState.data.state); - if (jsonMode) { ctx.output.result({ subcommand: 'state', address, network, raw }); } else { diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 9c3476a0..ef6546d2 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -9,7 +9,8 @@ import { saveShieldedAddress, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides } from '../lib/network.ts'; import { getNetworkId } from '../lib/network-id.ts'; -import { resolveTransferRequest, decodeShieldedRecipient, type TransferRequest } from '../lib/transfer-request.ts'; +import { resolveTransferRequest, type TransferRequest } from '../lib/transfer-request.ts'; +import { decodeShieldedAddress } from '../engine/rc/addresses.ts'; import { executeTransfer, ensureDust } from '../lib/transfer.ts'; import { nightToMicro } from '../lib/amount.ts'; import { defaultRepository } from '../lib/wallet-data-repository.ts'; @@ -136,7 +137,7 @@ async function shieldedTransfer( indexerWS: getFlag(args, 'indexer-ws'), }, networkName); - const decodedRecipient = decodeShieldedRecipient(recipientAddress, networkName); + const decodedRecipient = decodeShieldedAddress(recipientAddress, networkName); ctx.output.stderr('\n' + header('Shielded Transfer') + '\n\n'); ctx.output.stderr(keyValue('Network', networkName) + '\n'); diff --git a/src/engine/rc/addresses.ts b/src/engine/rc/addresses.ts new file mode 100644 index 00000000..5aea5a8d --- /dev/null +++ b/src/engine/rc/addresses.ts @@ -0,0 +1,22 @@ +// Reading bech32m addresses as the SDK's address types, for the network they +// must be on. + +import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; +import { networkIdForName } from '../../lib/network-id.ts'; +import type { NetworkName } from '../../lib/network.ts'; + +/** A shielded address on `network`, as the SDK reads it. Throws when it is not one. */ +export function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress { + return MidnightBech32m.parse(address).decode(ShieldedAddress, networkIdForName(network)); +} + +/** An unshielded address on `network`, as the SDK reads it. Throws when it is not one. */ +export function decodeUnshieldedAddress(address: string, network: NetworkName): UnshieldedAddress { + return MidnightBech32m.parse(address).decode(UnshieldedAddress, networkIdForName(network)); +} + +/** Throws, saying why, unless `address` is an address of that kind on `network`. */ +export function assertAddress(address: string, kind: 'shielded' | 'unshielded', network: NetworkName): void { + if (kind === 'shielded') decodeShieldedAddress(address, network); + else decodeUnshieldedAddress(address, network); +} diff --git a/src/lib/contract/providers.ts b/src/engine/rc/contract-providers.ts similarity index 51% rename from src/lib/contract/providers.ts rename to src/engine/rc/contract-providers.ts index c71ae9db..d3943a95 100644 --- a/src/lib/contract/providers.ts +++ b/src/engine/rc/contract-providers.ts @@ -2,8 +2,10 @@ // Deploy/call use the runner (generated scripts in dApp context) which build their own providers. import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; -import { assertEndpointUsable } from '../blockfrost.ts'; -import type { NetworkConfig } from '../network.ts'; +import { assertEndpointUsable } from '../../lib/blockfrost.ts'; +import type { NetworkConfig } from '../../lib/network.ts'; +import type { RawStateValue } from '../../lib/engine.ts'; +import { describeRawState } from './raw-state.ts'; /** * Build a lightweight indexer-only provider for state queries. @@ -16,3 +18,9 @@ export function buildStateProvider(networkConfig: NetworkConfig) { subscriptionURL: networkConfig.indexerWS ?? networkConfig.indexer.replace('http', 'ws'), }); } + +/** A deployed contract's ledger state as plain JSON, read without its compiled contract; null when no contract is at `address`. */ +export async function rawContractState(networkConfig: NetworkConfig, address: string): Promise { + const found = await buildStateProvider(networkConfig).queryContractState(address); + return found ? describeRawState(found.data.state) : null; +} diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index 6453ed4d..3585a389 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -2,7 +2,11 @@ // release candidates, ledger 9 and midnight-js 5 as mn pins them. import type { Engine } from '../../lib/engine.ts'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { blockLimitsOf } from './ledger-parameters.ts'; +import { rawContractState } from './contract-providers.ts'; +import { assertAddress } from './addresses.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; @@ -16,8 +20,21 @@ export const rcEngine: Engine = { shieldedAddresses: deriveAllShieldedAddresses, dustPublicKeyHex: dustPublicKeyHexFromSeed, shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, + assertAddress, }, ledger: { blockLimits: blockLimitsOf, + nightTokenId: () => ledger.unshieldedToken().raw, + }, + contracts: { + rawState: rawContractState, + acceptsPrivateStatePassword(password) { + try { + validatePassword(password); + return true; + } catch { + return false; + } + }, }, }; diff --git a/src/lib/contract/raw-state.ts b/src/engine/rc/raw-state.ts similarity index 85% rename from src/lib/contract/raw-state.ts rename to src/engine/rc/raw-state.ts index eded9b21..b6798b70 100644 --- a/src/lib/contract/raw-state.ts +++ b/src/engine/rc/raw-state.ts @@ -3,6 +3,8 @@ // layout the fields have no names, so cells show their field-aligned bytes in // hex and maps show their size, as the parsed state does. +import type { RawStateValue } from '../../lib/engine.ts'; + const toHex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); /** The parts of the runtime's `StateValue` read here (the runtime version the indexer decodes with varies). */ @@ -14,13 +16,6 @@ interface StateValueLike { asBoundedMerkleTree(): { height: number; root(): { value: Uint8Array[] } | undefined } | undefined; } -export type RawStateValue = - | { type: 'null' } - | { type: 'cell'; value: string[] } - | { type: 'array'; items: RawStateValue[] } - | { type: 'map'; size: number } - | { type: 'boundedMerkleTree'; height: number; root: string[] | null }; - export function describeRawState(state: StateValueLike): RawStateValue { switch (state.type()) { case 'null': diff --git a/src/lib/engine.ts b/src/lib/engine.ts index 871a992e..346b2262 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -4,7 +4,7 @@ // candidates (rc). The interface grows area by area as code moves behind it. // Loading an engine loads its SDK, so the loader imports it only when asked. -import type { NetworkName } from './network.ts'; +import type { NetworkConfig, NetworkName } from './network.ts'; /** An SDK set mn runs on. */ export type SdkSet = 'rc'; @@ -23,6 +23,8 @@ export interface EngineKeys { dustPublicKeyHex(seed: Buffer): string; /** The shielded coin public key, hex: what the shielded reader's cache is named by. */ shieldedCoinPublicKeyHex(seed: Buffer): string; + /** Throws, saying why, unless `address` is a bech32m address of that kind on `network`. */ + assertAddress(address: string, kind: 'shielded' | 'unshielded', network: NetworkName): void; } /** A line of what a transaction is, as an approval prompt shows it. */ @@ -44,6 +46,24 @@ export interface BlockLimits { export interface EngineLedger { /** The block limits in serialized ledger parameters (hex), as the indexer serves them. Throws when the bytes aren't this set's ledger parameters. */ blockLimits(parametersHex: string): BlockLimits; + /** The raw id of the unshielded NIGHT token, as wallet balances are keyed. */ + nightTokenId(): string; +} + +/** A contract's ledger state read without its compiled contract: cells as their field-aligned bytes in hex, maps by size. */ +export type RawStateValue = + | { type: 'null' } + | { type: 'cell'; value: string[] } + | { type: 'array'; items: RawStateValue[] } + | { type: 'map'; size: number } + | { type: 'boundedMerkleTree'; height: number; root: string[] | null }; + +/** What an engine does with contracts in mn's own process. */ +export interface EngineContracts { + /** A deployed contract's raw ledger state from the indexer; null when no contract is at `address`. */ + rawState(networkConfig: NetworkConfig, address: string): Promise; + /** Whether midnight-js accepts a private-state password (its own policy, which a random draw can miss). */ + acceptsPrivateStatePassword(password: string): boolean; } /** One SDK set, as mn uses it. */ @@ -51,6 +71,7 @@ export interface Engine { readonly set: SdkSet; readonly keys: EngineKeys; readonly ledger: EngineLedger; + readonly contracts: EngineContracts; } /** The SDK set a network runs on. */ diff --git a/src/lib/grant/account-backup.ts b/src/lib/grant/account-backup.ts index 3953e7ef..84755ee4 100644 --- a/src/lib/grant/account-backup.ts +++ b/src/lib/grant/account-backup.ts @@ -10,6 +10,7 @@ // a second device (`midnight grant device add`). import * as fs from 'node:fs'; +import { anyEngine } from '../engine.ts'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { type OwnerRecord, type Roster, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; @@ -96,7 +97,7 @@ export async function exportAccount(dir: string, network: string, passphrase: st roster: sealedOwnerStore(dir, key).readRoster(), ...(forDevice === undefined ? { device: { arm: device.arm, secret: device.secretText(), readSecret: Buffer.from(sealedDeviceReadSecret(dir, key)).toString('hex') } } : {}), devices: [...new Set([...knownDevices(dir, key, device), ...(forDevice === undefined ? [] : [deviceCodeOf(forDevice, forDevice.readKey)])])], - privateStatePassword: sealedPrivateStatePassword(dir, key), + privateStatePassword: sealedPrivateStatePassword(dir, key, (await anyEngine()).contracts.acceptsPrivateStatePassword), privateState: fs.existsSync(database) ? Object.fromEntries(filesUnder(database).map((f) => [f, fs.readFileSync(path.join(database, f)).toString('base64')])) : {}, }; const backup: AccountBackupFile = { diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index f2e47a78..1dcb43aa 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -9,6 +9,7 @@ // midnight-level-db under the store name and password it was first made with. import { notice } from '../notices.ts'; +import { anyEngine } from '../engine.ts'; import { join } from 'node:path'; import { artefactCache } from '@kuiralabs/midnight-account-chain/artefacts'; import { type AccountContext, type ProgressEvent, accountContext, describeProgress, networkOf } from '@kuiralabs/midnight-account-chain/context'; @@ -139,12 +140,14 @@ export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: const network = networkOf({ networkId: ACCOUNT_NETWORK_ID, node: httpOf(networkConfig.node), indexer: networkConfig.indexer, proofServer: networkConfig.proofServer }); const context = accountContext({ network, artefacts: artefactCache(accountArtifactsDir(root), { progress }), progress }); const database = join(recordsDir, PRIVATE_STATE_DATABASE); + // The account's private state is midnight-js's, which the engine's policy checks a new password against. + const { contracts } = await anyEngine(); const sealed = (key: Buffer): GrantAccount => ({ context, store: sealedOwnerStore(recordsDir, key), keys: sealedDeviceKeys(recordsDir, key), - location: { database, store: PRIVATE_STATE_STORE, password: () => sealedPrivateStatePassword(recordsDir, key) }, + location: { database, store: PRIVATE_STATE_STORE, password: () => sealedPrivateStatePassword(recordsDir, key, contracts.acceptsPrivateStatePassword) }, protection: 'sealed', deviceReadSecret: () => sealedDeviceReadSecret(recordsDir, key), ownCode: () => { diff --git a/src/lib/grant/protect-account.ts b/src/lib/grant/protect-account.ts index 6926235d..db8c8629 100644 --- a/src/lib/grant/protect-account.ts +++ b/src/lib/grant/protect-account.ts @@ -13,6 +13,7 @@ // never opened under the public password its private state has left. import * as fs from 'node:fs'; +import { anyEngine } from '../engine.ts'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { changePrivateStatePassword, directoryOwnerStore, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; @@ -72,7 +73,7 @@ export async function protectAccount(dir: string, passphrase: string, coinPublic if (device !== undefined && keys.read() === undefined) keys.keep(device); // 3 - const password = sealedPrivateStatePassword(dir, key); + const password = sealedPrivateStatePassword(dir, key, (await anyEngine()).contracts.acceptsPrivateStatePassword); const location = privateStateLocationOf(dir, () => LEGACY_STORE_PASSWORD); if (record !== undefined && fs.existsSync(location.database)) { await changePrivateStatePassword({ getCoinPublicKey: () => coinPublicKey }, record.contractAddress, location, () => password); diff --git a/src/lib/grant/sealed-account.ts b/src/lib/grant/sealed-account.ts index 97359b1c..8594ed90 100644 --- a/src/lib/grant/sealed-account.ts +++ b/src/lib/grant/sealed-account.ts @@ -29,7 +29,6 @@ import { freshOwnerDevice, ownerDeviceFromSecret, } from '@kuiralabs/midnight-account-chain/owner'; -import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { FILE_MODE } from '../constants.ts'; import { deviceCodeOf, joinCodeOf } from './device-code.ts'; import { UsageError } from '../errors.ts'; @@ -190,19 +189,14 @@ export function sealedDeviceKeys(dir: string, key: Uint8Array): SealedDeviceKeys // The private state's password: random, from an alphabet of all four of // midnight-js's character classes, redrawn until it meets midnight-js's own -// policy (a random draw can still hold a run such as "abcd"). +// policy, which the engine checks (a random draw can still hold a run such as "abcd"). const PASSWORD_LENGTH = 32; const PASSWORD_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789-_.~!@#%^*+='; -const freshPrivateStatePassword = (): string => { +const freshPrivateStatePassword = (accepts: (password: string) => boolean): string => { for (;;) { const password = [...randomBytes(PASSWORD_LENGTH)].map((byte) => PASSWORD_ALPHABET[byte % PASSWORD_ALPHABET.length]).join(''); - try { - validatePassword(password); - return password; - } catch { - // Drawn again. - } + if (accepts(password)) return password; } }; @@ -211,18 +205,22 @@ export function keepPrivateStatePassword(dir: string, key: Uint8Array, password: writeJsonDurably(path.join(dir, PRIVATE_STATE_FILE), { password: sealWithKey(key, Buffer.from(password, 'utf8'), 'private-state-password') }, { exclusive: true }); } -/** The account's private-state password: made on first use, sealed under `key`, the same every time after. */ -export function sealedPrivateStatePassword(dir: string, key: Uint8Array): string { +/** + * The account's private-state password: made on first use, sealed under + * `key`, the same every time after. `accepts` is midnight-js's policy, from + * the engine (an engine's contracts.acceptsPrivateStatePassword). + */ +export function sealedPrivateStatePassword(dir: string, key: Uint8Array, accepts: (password: string) => boolean): string { const file = path.join(dir, PRIVATE_STATE_FILE); const kept = readJsonIfPresent<{ password: KeyedSecret }>(file); if (kept !== undefined) return openWithKey(key, kept.password, 'private-state-password').toString('utf8'); - const password = freshPrivateStatePassword(); + const password = freshPrivateStatePassword(accepts); try { writeJsonDurably(file, { password: sealWithKey(key, Buffer.from(password, 'utf8'), 'private-state-password') }, { exclusive: true }); return password; } catch (error) { // Another run made it first: that one is the account's. - if (error instanceof FileExistsError) return sealedPrivateStatePassword(dir, key); + if (error instanceof FileExistsError) return sealedPrivateStatePassword(dir, key, accepts); throw error; } } diff --git a/src/lib/payer.ts b/src/lib/payer.ts index 43e48e6f..bf0ff15b 100644 --- a/src/lib/payer.ts +++ b/src/lib/payer.ts @@ -4,14 +4,14 @@ // pay with a wallet of its own. import { type ParsedArgs, getFlag } from './argv.ts'; -import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig } from './network.ts'; +import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from './network.ts'; import { resolveNetwork } from './resolve-network.ts'; import type { Spinner } from '../ui/spinner.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; /** The network a command acts on, with its endpoints resolved. */ export interface PayingTarget { - network: string; + network: NetworkName; networkConfig: NetworkConfig; /** The endpoints given as flags, which a server started for the command must use too. */ endpoints: EndpointOverrides; diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index e8f9d4cd..17ed3ed0 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -1,6 +1,5 @@ // Prep runner — execute prep steps defined in dapp.test.json by calling existing lib functions. -import * as ledger from '@midnightntwrk/ledger-v9'; import { join } from 'node:path'; import { bindCachesToIndexer } from '../cache-indexer.ts'; @@ -19,6 +18,7 @@ import { startServeOrReuse } from '../serve-manager.ts'; import { OWN_COMMAND_DUST_WAIT_MS } from '../dust-wait.ts'; import { startBuild } from './build-manager.ts'; import { throwIfCancelled } from '../errors.ts'; +import { engineFor } from '../engine.ts'; /** * Run all prep steps defined in the config, in order. @@ -141,7 +141,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont callbacks.onMessage(`Syncing wallet... (${detail})`); }, }); - const nightToken = ledger.unshieldedToken().raw; + const nightToken = (await engineFor(network)).ledger.nightTokenId(); const balance = state.unshielded.balances[nightToken] ?? 0n; if (balance > 0n) { diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 4b068309..abb6d9de 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -2,12 +2,11 @@ // before syncing, the MCP server before it issues a confirmation token, so a // typo in the amount or the recipient is refused up front. -import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type ParsedArgs, getFlag, hasFlag } from './argv.ts'; import { UsageError } from './errors.ts'; import { loadWalletConfig, resolveWalletPath, type WalletConfig } from './wallet-config.ts'; import { resolveNetworkName } from './resolve-network.ts'; -import { networkIdForName } from './network-id.ts'; +import { engineFor, type EngineKeys } from './engine.ts'; import { shieldedSyncEnabled, shieldedDisabledReason } from './shielded-policy.ts'; import { parseAmount } from './amount.ts'; import type { NetworkName } from './network.ts'; @@ -55,33 +54,20 @@ export async function resolveTransferRequest(args: ParsedArgs): Promise Date: Sun, 1 Nov 2026 18:31:31 -0800 Subject: [PATCH 25/88] Engine, part 5: the contract scripts are the engine's The scripts mn runs in a dApp's folder (deploy, call, state) and the packages they import are set-specific: they move into the rc engine, with the packages found from the engine's own install. What every set's script shares (the failure prelude, mn serve's RPC client, the argument and secret helpers, the witness locations, the indexer's environment names) stays with the runner and reaches the engine as ScriptParts. The runner asks the network's engine for the script and links that engine's packages into the dApp, so its options now name the network. The runner leaves the pending list (eleven left). No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.mjs | 1 - .../contract-runner-endpoints.test.ts | 10 +- src/__tests__/contract-runner.test.ts | 19 +- .../contract-script-packages.test.ts | 25 +- src/__tests__/layering.test.ts | 1 - src/commands/contract.ts | 1 + src/engine/rc/contract-scripts.ts | 348 +++++++++++++++ src/engine/rc/index.ts | 8 + src/lib/contract/call.ts | 1 + src/lib/contract/deploy.ts | 1 + src/lib/contract/runner.ts | 409 +++--------------- src/lib/engine.ts | 55 +++ src/lib/test/actions-runner.ts | 9 +- 13 files changed, 512 insertions(+), 376 deletions(-) create mode 100644 src/engine/rc/contract-scripts.ts diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 274438e0..b3b81b11 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -107,7 +107,6 @@ export const PENDING_ENGINE = new Set([ 'commands/balance.ts', 'commands/dust.ts', 'commands/transfer.ts', - 'lib/contract/runner.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', diff --git a/src/__tests__/contract-runner-endpoints.test.ts b/src/__tests__/contract-runner-endpoints.test.ts index 987508bb..34a331d1 100644 --- a/src/__tests__/contract-runner-endpoints.test.ts +++ b/src/__tests__/contract-runner-endpoints.test.ts @@ -5,7 +5,15 @@ import { describe, expect, it } from 'vitest'; import { BlockfrostProjectIdRequiredError, blockfrostEndpoints } from '../lib/blockfrost.ts'; -import { generateCallScript, generateDeployScript, generateStateScript, indexerEnvironment } from '../lib/contract/runner.ts'; +import { SCRIPT_PARTS, indexerEnvironment } from '../lib/contract/runner.ts'; +import * as rcScripts from '../engine/rc/contract-scripts.ts'; +import type { CallScript, DeployScript, StateScript } from '../lib/engine.ts'; + +// The rc engine's scripts, with the parts the runner gives every engine. +const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); +const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); +const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); + import type { NetworkConfig } from '../lib/network.ts'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index d9e35f20..487a145a 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -25,18 +25,23 @@ import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; import { - PROVIDER_IMPORTS, - walletProviderCode, - providerSetupCode, - generateDeployScript, - generateCallScript, - generateStateScript, + SCRIPT_PARTS, SCRIPT_PRELUDE, indexerEnvironment, runCall, runDeploy, runState, } from '../lib/contract/runner.ts'; +import * as rcScripts from '../engine/rc/contract-scripts.ts'; +import { PROVIDER_IMPORTS, walletProviderCode } from '../engine/rc/contract-scripts.ts'; +import type { CallScript, DeployScript, StateScript } from '../lib/engine.ts'; + +// The rc engine's scripts, with the parts the runner gives every engine. +const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); +const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); +const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); +const providerSetupCode = (networkConfig: Parameters[0], key: string): string => rcScripts.providerSetupCode(networkConfig, key, SCRIPT_PARTS); + import type { NetworkConfig } from '../lib/network.ts'; const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new ( @@ -259,7 +264,7 @@ describe('a cancelled run', () => { it('starts no script for a deploy, a call or a state read whose run was cancelled, and says it was cancelled', async () => { const dappDir = mkdtempSync(join(tmpdir(), 'mn-cancelled-run-')); try { - const common = { dappDir, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; + const common = { dappDir, network: 'undeployed' as const, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; await expect(runDeploy({ ...common, servePort: 9932 })).rejects.toBeInstanceOf(CancelledError); await expect(runCall({ ...common, servePort: 9932, contractAddress: 'ab'.repeat(32), circuit: 'increment' })).rejects.toBeInstanceOf(CancelledError); await expect(runState({ ...common, contractAddress: 'ab'.repeat(32) })).rejects.toBeInstanceOf(CancelledError); diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index bb5502f3..6e7a33b6 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -12,18 +12,27 @@ import * as path from 'node:path'; import { pathToFileURL } from 'node:url'; import { NoNodeRuntimeError, - SCRIPT_PACKAGES, - acquireOverlay, + SCRIPT_PARTS, + acquireOverlay as acquireOverlayFor, executeScript, releaseOverlay, - generateCallScript, - generateDeployScript, - generateStateScript, - overlayScriptPackages, - packageFolder, + overlayScriptPackages as overlayScriptPackagesFor, scriptRuntime, undoOverlay, } from '../lib/contract/runner.ts'; +import * as rcScripts from '../engine/rc/contract-scripts.ts'; +import { SCRIPT_PACKAGES, packageFolder } from '../engine/rc/contract-scripts.ts'; +import { rcEngine } from '../engine/rc/index.ts'; +import type { CallScript, DeployScript, StateScript } from '../lib/engine.ts'; + +// The rc engine's scripts, with the parts the runner gives every engine. +const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); +const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); +const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); +// The overlay of the rc engine's packages. +const overlayScriptPackages = (userNodeModules: string) => overlayScriptPackagesFor(userNodeModules, rcEngine.contracts.scripts); +const acquireOverlay = (dir: string): void => acquireOverlayFor(dir, rcEngine.contracts.scripts); + import { platformPackageBinary } from '../engine/rc/dust-sync-native.ts'; const NETWORK = { indexer: 'http://localhost:28088/api/v4/graphql', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', node: 'ws://localhost:29944', proofServer: 'http://localhost:26300', networkId: 'Undeployed' }; @@ -131,7 +140,7 @@ describe('a dApp laid out unlike ours', () => { }); it('with no Node to run under, refuses before writing anything to the dApp', async () => { - await expect(executeScript({ dir, script: 'console.log(1)', findRuntime: () => { throw new NoNodeRuntimeError(); } })).rejects.toThrow(NoNodeRuntimeError); + await expect(executeScript({ dir, script: 'console.log(1)', packages: rcEngine.contracts.scripts, findRuntime: () => { throw new NoNodeRuntimeError(); } })).rejects.toThrow(NoNodeRuntimeError); expect(fs.readdirSync(dir)).toEqual([]); }); }); diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 32e62da1..7a62ebb7 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -54,7 +54,6 @@ describe('the layering', () => { 'commands/balance.ts', 'commands/dust.ts', 'commands/transfer.ts', - 'lib/contract/runner.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', 'lib/facade.ts', diff --git a/src/commands/contract.ts b/src/commands/contract.ts index acdfe298..3d2d8a04 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -251,6 +251,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { const result = await runState({ dappDir, + network, networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/engine/rc/contract-scripts.ts b/src/engine/rc/contract-scripts.ts new file mode 100644 index 00000000..3f91388e --- /dev/null +++ b/src/engine/rc/contract-scripts.ts @@ -0,0 +1,348 @@ +// The scripts mn runs in a dApp's own folder to deploy, call and read a +// contract with midnight-js, and the packages they import, for this engine's +// SDK set. What every set's script shares (the prelude that reports a +// failure, the client of mn serve's RPC, the argument and secret helpers, +// where the witnesses may be) comes from the runner as ScriptParts. + +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; +import type { CallScript, DeployScript, ScriptParts, StateScript } from '../../lib/engine.ts'; +import type { NetworkConfig } from '../../lib/network.ts'; + +/** + * Every package a generated script imports, and the compact runtime the + * user's compiled contract imports. Each is found by name from this engine's + * location and linked into the dApp by name, so this works wherever the + * packages sit (our checkout, our install, or someone else's hoisted tree). + * A test keeps this list in step with the scripts' imports. + */ +export const SCRIPT_PACKAGES = [ + '@midnight-ntwrk/compact-js', + '@midnight-ntwrk/compact-runtime', + '@midnight-ntwrk/midnight-js-contracts', + '@midnight-ntwrk/midnight-js-http-client-proof-provider', + '@midnight-ntwrk/midnight-js-indexer-public-data-provider', + '@midnight-ntwrk/midnight-js-level-private-state-provider', + '@midnight-ntwrk/midnight-js-network-id', + '@midnight-ntwrk/midnight-js-node-zk-config-provider', + '@midnight-ntwrk/midnight-js-types', + '@midnight-ntwrk/midnight-js-utils', + 'ws', +] as const; + +/** The folder of the installed package `name`, as mn resolves it; null when it isn't installed. */ +export function packageFolder(name: string): string | null { + // node:module's createRequire works in every host (Node, the test runner, + // the bundle); a package exported to `import` only is found through + // import.meta.resolve where the host has it. + let entry: string; + try { + entry = createRequire(import.meta.url).resolve(name); + } catch { + try { + entry = fileURLToPath(import.meta.resolve(name)); + } catch { + return null; + } + } + for (let dir = dirname(entry); ; dir = dirname(dir)) { + const manifest = join(dir, 'package.json'); + if (existsSync(manifest)) { + try { + if ((JSON.parse(readFileSync(manifest, 'utf8')) as { name?: string }).name === name) return dir; + } catch { /* not this one: keep looking up */ } + } + if (dirname(dir) === dir) return null; + } +} + +/** + * SDK imports used by walletProviderCode and providerSetupCode. Kept out of + * those fragments so a test can evaluate a fragment with the same bindings. + */ +export const PROVIDER_IMPORTS = ` +import { createWalletProvider, createMidnightProvider, Transaction } from '@midnight-ntwrk/midnight-js-types'; +import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils'; +import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; +import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; +import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; +import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; +`; + +/** + * walletProvider + midnightProvider backed by mn serve RPC. midnight-js 5 + * passes version-tagged txs ({ version: 'v9', tx }) and refuses providers that + * do not declare `supportedEras`; createWalletProvider/createMidnightProvider + * declare v9 and unwrap/re-tag, so the bodies below see live ledger-v9 txs. + */ +export function walletProviderCode(): string { + return ` +const walletState = await rpcCall('getShieldedAddresses', {}); + +const walletProvider = createWalletProvider({ + getCoinPublicKey: () => walletState.shieldedCoinPublicKey, + getEncryptionPublicKey: () => walletState.shieldedEncryptionPublicKey, + // ttl is ignored: mn serve applies its own TTL when balancing. + async balanceTx(tx) { + const result = await rpcCall('balanceUnsealedTransaction', { tx: toHex(tx.serialize()) }); + return Transaction.deserialize('signature', 'proof', 'binding', fromHex(result.tx)); + }, +}); + +const midnightProvider = createMidnightProvider(async (tx) => { + await rpcCall('submitTransaction', { tx: toHex(tx.serialize()) }); + return tx.identifiers()[0]; +}); +`; +} + +function contractSetupCode(contractName: string, managedDir: string, parts: ScriptParts): string { + return ` +import { pathToFileURL } from 'node:url'; +import { resolve } from 'node:path'; +import { CompiledContract } from '@midnight-ntwrk/compact-js'; + +const MANAGED_DIR = ${JSON.stringify(managedDir)}; + +// Load compiled contract class +const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract', 'index.js')).href); + +// Try to load witnesses and private state factory. +// Both relative-to-cwd locations and contract/<...> locations are checked +// so mn dev (which chdirs into the contract sub-package) and mn contract +// deploy run from a workspace root both work. +const WITNESS_CANDIDATES = ${JSON.stringify(parts.witnessCandidates)}; +let witnesses; +let createPrivateState; +for (const p of WITNESS_CANDIDATES) { + try { + const wMod = await import(pathToFileURL(resolve(p)).href); + if (wMod.witnesses) { witnesses = wMod.witnesses; } + // Look for createInitialPrivateState or create*PrivateState + for (const key of Object.keys(wMod)) { + if (typeof wMod[key] === 'function' && key.startsWith('create') && key.toLowerCase().includes('privatestate')) { + createPrivateState = wMod[key]; + } + } + if (witnesses) break; + } catch {} +} + +// Note: callers (commands/contract.ts, commands/dev.ts) preflight when the +// contract's compiler-info declares witnesses, so a missing module here means +// the contract truly has no witnesses (vacant is correct). The runtime +// warning still names every path we tried — useful when the SDK later +// complains about a specific witness name despite preflight passing. +if (!witnesses) { + process.stderr.write('Warning: No witnesses module found — using vacant witnesses. Searched:\\n'); + for (const p of WITNESS_CANDIDATES) process.stderr.write(' - ' + p + '\\n'); +} + +// Generate initial private state. +// Uses a deterministic seed derived from the wallet so post/takeDown use the same key. +// The private state provider (leveldb) persists between calls, but initialPrivateState +// is the fallback when no stored state exists yet. +${parts.privateStateSecretFn} +function makeInitialPrivateState() { + if (createPrivateState) { + // Secret precedence (see resolvePrivateStateSecretKey, injected above via + // .toString()): an explicit mn --secret-key (from env MN_PRIVATE_STATE_SECRET, + // never on disk) wins, else a deterministic key from the wallet's coin public + // key so post/takeDown reuse it, else random. + const secretKey = resolvePrivateStateSecretKey( + process.env.MN_PRIVATE_STATE_SECRET, + walletState?.shieldedCoinPublicKey, + ); + try { return createPrivateState(secretKey); } catch {} + try { return createPrivateState(); } catch {} + } + return {}; +} + +const compiled = witnesses + ? CompiledContract.make(${JSON.stringify(contractName)}, contractMod.Contract).pipe( + (c) => CompiledContract.withWitnesses(c, witnesses), + (c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR), + ) + : CompiledContract.make(${JSON.stringify(contractName)}, contractMod.Contract).pipe( + CompiledContract.withVacantWitnesses, + (c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR), + ); +`; +} + +/** The `providers` object deploy/call pass to midnight-js-contracts. */ +export function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string, parts: ScriptParts): string { + return ` +const zkConfigProvider = new NodeZkConfigProvider(MANAGED_DIR); + +const providers = { + privateStateProvider: levelPrivateStateProvider({ + privateStateStoreName: ${JSON.stringify(privateStateKey)}, + privateStoragePasswordProvider: () => Promise.resolve('mn-contract-default-pwd-16ch'), + accountId: 'mn-contract-runner', + }), + publicDataProvider: indexerPublicDataProvider({ + queryURL: process.env.${parts.indexerUrlEnv}, + subscriptionURL: process.env.${parts.indexerWsUrlEnv}, + }), + zkConfigProvider, + proofProvider: httpClientProofProvider({ url: ${JSON.stringify(networkConfig.proofServer)}, zkConfigProvider }), + walletProvider, + midnightProvider, +}; +`; +} + +// ── Script generation ── + +export function generateDeployScript(opts: DeployScript, parts: ScriptParts): string { + const privateStateKey = opts.privateStateKey ?? `${opts.contractName}PrivateState`; + // Constructor args are pre-serialized to JSON here (still in our process) + // so the generated script just spreads them. The coerceArg helper inside + // the bridge then upgrades number → BigInt and number[] → Uint8Array, the + // two coercions Compact circuits invariably need. + const argsLiteral = JSON.stringify(opts.args ?? []); + + return `${parts.prelude} +import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; +setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); + +${parts.rpcClientCode(opts.servePort)} +${contractSetupCode(opts.contractName, opts.managedDir, parts)} + +process.stderr.write('Connecting to mn serve...\\n'); +await rpcConnect(); +process.stderr.write('Connected\\n'); + +${PROVIDER_IMPORTS} +${walletProviderCode()} +${providerSetupCode(opts.networkConfig, privateStateKey, parts)} + +import { deployContract } from '@midnight-ntwrk/midnight-js-contracts'; + +${parts.coerceArgFn} +const constructorArgs = (${argsLiteral}).map(coerceArg); +process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n'); +const deployed = await deployContract(providers, { + compiledContract: compiled, + privateStateId: ${JSON.stringify(privateStateKey)}, + initialPrivateState: makeInitialPrivateState(), + args: constructorArgs, +}); + +const address = deployed.deployTxData?.public?.contractAddress ?? 'unknown'; +process.stderr.write('Deploy complete: ' + address + '\\n'); + +console.log(JSON.stringify({ contractAddress: address })); +rpcClose(); +process.exit(0); +`; +} + +export function generateCallScript(opts: CallScript, parts: ScriptParts): string { + const privateStateKey = opts.privateStateKey ?? `${opts.contractName}PrivateState`; + + return `${parts.prelude} +import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; +setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); + +${parts.rpcClientCode(opts.servePort)} +${contractSetupCode(opts.contractName, opts.managedDir, parts)} + +process.stderr.write('Connecting to mn serve...\\n'); +await rpcConnect(); +process.stderr.write('Connected\\n'); + +${PROVIDER_IMPORTS} +${walletProviderCode()} +${providerSetupCode(opts.networkConfig, privateStateKey, parts)} + +import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; + +process.stderr.write('Finding deployed contract...\\n'); +const deployed = await findDeployedContract(providers, { + compiledContract: compiled, + contractAddress: ${JSON.stringify(opts.contractAddress)}, + privateStateId: ${JSON.stringify(privateStateKey)}, + initialPrivateState: makeInitialPrivateState(), +}); + +process.stderr.write('Calling ${opts.circuit}...\\n'); +${parts.coerceArgFn} +const args = (${JSON.stringify(opts.args ?? [])}).map(coerceArg); +await deployed.callTx.${opts.circuit}(...args); + +console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(opts.circuit)} })); +rpcClose(); +process.exit(0); +`; +} + +export function generateStateScript(opts: StateScript, parts: ScriptParts): string { + return `${parts.prelude} +import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; +setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); + +import { pathToFileURL } from 'node:url'; +import { resolve } from 'node:path'; +import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; + +const MANAGED_DIR = ${JSON.stringify(opts.managedDir)}; + +// Load the contract module which exports the ledger() function +const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract', 'index.js')).href); + +if (typeof contractMod.ledger !== 'function') { + fail(new Error('Contract module does not export a ledger() function')); +} + +process.stderr.write('Querying contract state...\\n'); +const provider = indexerPublicDataProvider({ + queryURL: process.env.${parts.indexerUrlEnv}, + subscriptionURL: process.env.${parts.indexerWsUrlEnv}, +}); + +const contractState = await provider.queryContractState(${JSON.stringify(opts.contractAddress)}); +if (!contractState) { + fail(new Error('No contract found at address ${opts.contractAddress}')); +} + +process.stderr.write('Parsing ledger state...\\n'); +// ledger() expects contractState.data (ChargedState), not the full ContractState +const state = contractMod.ledger(contractState.data ?? contractState); + +// Extract scalar fields and map fields +const fields = {}; +const maps = {}; + +for (const key of Object.keys(state)) { + const val = state[key]; + + // Check if it's a map-like (has size() and Symbol.iterator) + if (val && typeof val === 'object' && typeof val.size === 'function') { + try { + maps[key] = { size: val.size().toString() }; + } catch { + maps[key] = { size: '?' }; + } + } else if (typeof val === 'bigint') { + fields[key] = val.toString(); + } else if (typeof val === 'string') { + fields[key] = val; + } else if (typeof val === 'boolean') { + fields[key] = String(val); + } else if (val instanceof Uint8Array) { + fields[key] = Array.from(val).map(b => b.toString(16).padStart(2, '0')).join(''); + } else if (val !== undefined && val !== null) { + try { fields[key] = JSON.stringify(val); } catch { fields[key] = '?'; } + } +} + +console.log(JSON.stringify({ fields, maps })); +process.exit(0); +`; +} + diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index 3585a389..ab7a3650 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -7,6 +7,7 @@ import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { blockLimitsOf } from './ledger-parameters.ts'; import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; +import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; @@ -36,5 +37,12 @@ export const rcEngine: Engine = { return false; } }, + scripts: { + packages: SCRIPT_PACKAGES, + packageFolder, + deploy: generateDeployScript, + call: generateCallScript, + state: generateStateScript, + }, }, }; diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index e44dfa6c..4cdd6dbd 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -35,6 +35,7 @@ export async function callContract({ request, target, wallet, payer, progress, s return withServedWallet({ target, wallet, payer, progress, sdkWarnings, signal }, { running: `Calling ${circuit}...`, done: `${circuit} called`, failed: 'Call failed' }, async (servePort, spinner) => { const result = await runCall({ dappDir, + network: target.network, networkConfig: target.networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index eb6f8bfa..19e34617 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -33,6 +33,7 @@ export async function deployContract({ request, target, wallet, payer, progress, return withServedWallet({ target, wallet, payer, progress, sdkWarnings, signal }, { running: 'Deploying contract...', done: 'Contract deployed', failed: 'Deploy failed' }, async (servePort, spinner) => { const result = await runDeploy({ dappDir, + network: target.network, networkConfig: target.networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 3128865e..1d10171b 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -1,6 +1,9 @@ // Contract runner — execute contract operations in the dApp's own process context. // Uses mn's serve RPC server for wallet operations (balance, sign, submit). // The generated script only needs contract SDK + RPC client — no wallet SDK. +// The engine for the network's SDK set writes the script and names the +// packages it imports; the runner adds what every set's script shares, makes +// those packages resolvable from the dApp, and runs it. import { spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; @@ -9,7 +12,8 @@ import { join, dirname, delimiter } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; import { assertEndpointUsable } from '../blockfrost.ts'; -import type { NetworkConfig } from '../network.ts'; +import type { NetworkConfig, NetworkName } from '../network.ts'; +import { engineFor, type EngineContractScripts, type ScriptParts } from '../engine.ts'; import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; import { coerceArg } from './arg-coerce.ts'; import { resolvePrivateStateSecretKey } from './private-state-secret.ts'; @@ -22,55 +26,11 @@ import { CancelledError, throwIfCancelled } from '../errors.ts'; // the script needs is linked by name into the dApp's node_modules instead, and // Node's normal walk-up from the script finds it there. -/** - * Every package a generated script imports, and the compact runtime the - * user's compiled contract imports. Each is found by name from mn's own - * location and linked into the dApp by name, so this works wherever the - * packages sit (our checkout, our install, or someone else's hoisted tree). - * A test keeps this list in step with the scripts' imports. - */ -export const SCRIPT_PACKAGES = [ - '@midnight-ntwrk/compact-js', - '@midnight-ntwrk/compact-runtime', - '@midnight-ntwrk/midnight-js-contracts', - '@midnight-ntwrk/midnight-js-http-client-proof-provider', - '@midnight-ntwrk/midnight-js-indexer-public-data-provider', - '@midnight-ntwrk/midnight-js-level-private-state-provider', - '@midnight-ntwrk/midnight-js-network-id', - '@midnight-ntwrk/midnight-js-node-zk-config-provider', - '@midnight-ntwrk/midnight-js-types', - '@midnight-ntwrk/midnight-js-utils', - 'ws', -] as const; - -/** The folder of the installed package `name`, as mn resolves it; null when it isn't installed. */ -export function packageFolder(name: string): string | null { - // node:module's createRequire works in every host (Node, the test runner, - // the bundle); a package exported to `import` only is found through - // import.meta.resolve where the host has it. - let entry: string; - try { - entry = createRequire(import.meta.url).resolve(name); - } catch { - try { - entry = fileURLToPath(import.meta.resolve(name)); - } catch { - return null; - } - } - for (let dir = dirname(entry); ; dir = dirname(dir)) { - const manifest = join(dir, 'package.json'); - if (existsSync(manifest)) { - try { - if ((JSON.parse(readFileSync(manifest, 'utf8')) as { name?: string }).name === name) return dir; - } catch { /* not this one: keep looking up */ } - } - if (dirname(dir) === dir) return null; - } -} export interface RunnerOptions { dappDir: string; + /** The network: its engine writes the script. */ + network: NetworkName; networkConfig: NetworkConfig; managedDir: string; contractName: string; @@ -107,6 +67,8 @@ export interface CallOptions extends RunnerOptions { export interface StateOptions { dappDir: string; + /** The network: its engine writes the script. */ + network: NetworkName; networkConfig: NetworkConfig; managedDir: string; contractName: string; @@ -145,8 +107,9 @@ export function indexerEnvironment(networkConfig: NetworkConfig): Record { - const script = generateStateScript(options); - const result = await executeScript({ dir: options.dappDir, script, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); + const { scripts } = (await engineFor(options.network)).contracts; + const script = scripts.state(options, SCRIPT_PARTS); + const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); try { return JSON.parse(result) as StateResult; } catch { @@ -155,14 +118,15 @@ export async function runState(options: StateOptions): Promise { } export async function runDeploy(options: DeployOptions): Promise { - const script = generateDeployScript(options); + const { scripts } = (await engineFor(options.network)).contracts; + const script = scripts.deploy(options, SCRIPT_PARTS); // The private-state secret goes to the subprocess via env (never the on-disk // script) so a caller-chosen owner is not written to the filesystem. const extraEnv = { ...indexerEnvironment(options.networkConfig), ...(options.privateStateSecretKey ? { MN_PRIVATE_STATE_SECRET: options.privateStateSecretKey } : {}), }; - const result = await executeScript({ dir: options.dappDir, script, onMessage: options.onMessage, env: extraEnv, signal: options.signal }); + const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: extraEnv, signal: options.signal }); try { return JSON.parse(result) as DeployResult; } catch { @@ -171,8 +135,9 @@ export async function runDeploy(options: DeployOptions): Promise { } export async function runCall(options: CallOptions): Promise { - const script = generateCallScript(options); - const result = await executeScript({ dir: options.dappDir, script, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); + const { scripts } = (await engineFor(options.network)).contracts; + const script = scripts.call(options, SCRIPT_PARTS); + const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); try { return JSON.parse(result) as CallResult; } catch { @@ -228,149 +193,6 @@ function rpcClose() { `; } -/** - * SDK imports used by walletProviderCode and providerSetupCode. Kept out of - * those fragments so a test can evaluate a fragment with the same bindings. - */ -export const PROVIDER_IMPORTS = ` -import { createWalletProvider, createMidnightProvider, Transaction } from '@midnight-ntwrk/midnight-js-types'; -import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils'; -import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; -import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; -import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; -import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; -`; - -/** - * walletProvider + midnightProvider backed by mn serve RPC. midnight-js 5 - * passes version-tagged txs ({ version: 'v9', tx }) and refuses providers that - * do not declare `supportedEras`; createWalletProvider/createMidnightProvider - * declare v9 and unwrap/re-tag, so the bodies below see live ledger-v9 txs. - */ -export function walletProviderCode(): string { - return ` -const walletState = await rpcCall('getShieldedAddresses', {}); - -const walletProvider = createWalletProvider({ - getCoinPublicKey: () => walletState.shieldedCoinPublicKey, - getEncryptionPublicKey: () => walletState.shieldedEncryptionPublicKey, - // ttl is ignored: mn serve applies its own TTL when balancing. - async balanceTx(tx) { - const result = await rpcCall('balanceUnsealedTransaction', { tx: toHex(tx.serialize()) }); - return Transaction.deserialize('signature', 'proof', 'binding', fromHex(result.tx)); - }, -}); - -const midnightProvider = createMidnightProvider(async (tx) => { - await rpcCall('submitTransaction', { tx: toHex(tx.serialize()) }); - return tx.identifiers()[0]; -}); -`; -} - -// resolvePrivateStateSecretKey serialized for the generated script (same -// .toString()-inlining trick as ARG_COERCE_FN, so makeInitialPrivateState below -// and the test suite share one implementation). -const PRIVATE_STATE_SECRET_FN = `\nconst resolvePrivateStateSecretKey = (${resolvePrivateStateSecretKey.toString()});\n`; - -function contractSetupCode(contractName: string, managedDir: string): string { - return ` -import { pathToFileURL } from 'node:url'; -import { resolve } from 'node:path'; -import { CompiledContract } from '@midnight-ntwrk/compact-js'; - -const MANAGED_DIR = ${JSON.stringify(managedDir)}; - -// Load compiled contract class -const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract', 'index.js')).href); - -// Try to load witnesses and private state factory. -// Both relative-to-cwd locations and contract/<...> locations are checked -// so mn dev (which chdirs into the contract sub-package) and mn contract -// deploy run from a workspace root both work. -const WITNESS_CANDIDATES = ${JSON.stringify(WITNESS_FILE_CANDIDATES)}; -let witnesses; -let createPrivateState; -for (const p of WITNESS_CANDIDATES) { - try { - const wMod = await import(pathToFileURL(resolve(p)).href); - if (wMod.witnesses) { witnesses = wMod.witnesses; } - // Look for createInitialPrivateState or create*PrivateState - for (const key of Object.keys(wMod)) { - if (typeof wMod[key] === 'function' && key.startsWith('create') && key.toLowerCase().includes('privatestate')) { - createPrivateState = wMod[key]; - } - } - if (witnesses) break; - } catch {} -} - -// Note: callers (commands/contract.ts, commands/dev.ts) preflight when the -// contract's compiler-info declares witnesses, so a missing module here means -// the contract truly has no witnesses (vacant is correct). The runtime -// warning still names every path we tried — useful when the SDK later -// complains about a specific witness name despite preflight passing. -if (!witnesses) { - process.stderr.write('Warning: No witnesses module found — using vacant witnesses. Searched:\\n'); - for (const p of WITNESS_CANDIDATES) process.stderr.write(' - ' + p + '\\n'); -} - -// Generate initial private state. -// Uses a deterministic seed derived from the wallet so post/takeDown use the same key. -// The private state provider (leveldb) persists between calls, but initialPrivateState -// is the fallback when no stored state exists yet. -${PRIVATE_STATE_SECRET_FN} -function makeInitialPrivateState() { - if (createPrivateState) { - // Secret precedence (see resolvePrivateStateSecretKey, injected above via - // .toString()): an explicit mn --secret-key (from env MN_PRIVATE_STATE_SECRET, - // never on disk) wins, else a deterministic key from the wallet's coin public - // key so post/takeDown reuse it, else random. - const secretKey = resolvePrivateStateSecretKey( - process.env.MN_PRIVATE_STATE_SECRET, - walletState?.shieldedCoinPublicKey, - ); - try { return createPrivateState(secretKey); } catch {} - try { return createPrivateState(); } catch {} - } - return {}; -} - -const compiled = witnesses - ? CompiledContract.make(${JSON.stringify(contractName)}, contractMod.Contract).pipe( - (c) => CompiledContract.withWitnesses(c, witnesses), - (c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR), - ) - : CompiledContract.make(${JSON.stringify(contractName)}, contractMod.Contract).pipe( - CompiledContract.withVacantWitnesses, - (c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR), - ); -`; -} - -/** The `providers` object deploy/call pass to midnight-js-contracts. */ -export function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string): string { - return ` -const zkConfigProvider = new NodeZkConfigProvider(MANAGED_DIR); - -const providers = { - privateStateProvider: levelPrivateStateProvider({ - privateStateStoreName: ${JSON.stringify(privateStateKey)}, - privateStoragePasswordProvider: () => Promise.resolve('mn-contract-default-pwd-16ch'), - accountId: 'mn-contract-runner', - }), - publicDataProvider: indexerPublicDataProvider({ - queryURL: process.env.${INDEXER_URL_ENV}, - subscriptionURL: process.env.${INDEXER_WS_URL_ENV}, - }), - zkConfigProvider, - proofProvider: httpClientProofProvider({ url: ${JSON.stringify(networkConfig.proofServer)}, zkConfigProvider }), - walletProvider, - midnightProvider, -}; -`; -} - // ── Script generation ── /** @@ -403,6 +225,11 @@ const providers = { */ const ARG_COERCE_FN = `\nconst coerceArg = (${coerceArg.toString()});\n`; +// resolvePrivateStateSecretKey serialized for the generated script (the same +// .toString()-inlining trick as ARG_COERCE_FN, so the script's +// makeInitialPrivateState and the test suite share one implementation). +const PRIVATE_STATE_SECRET_FN = `\nconst resolvePrivateStateSecretKey = (${resolvePrivateStateSecretKey.toString()});\n`; + /** Marks the line a generated script reports its failure on, so mn can tell it from progress and warnings. */ export const SCRIPT_ERROR_MARKER = '__MN_ERROR__'; @@ -429,164 +256,30 @@ export function scriptFailureMessage(stderr: string, exitCode: number | null): s return stderr.trim() || `Script exited with code ${exitCode}`; } -export function generateDeployScript(opts: DeployOptions): string { - const privateStateKey = opts.privateStateKey ?? `${opts.contractName}PrivateState`; - // Constructor args are pre-serialized to JSON here (still in our process) - // so the generated script just spreads them. The coerceArg helper inside - // the bridge then upgrades number → BigInt and number[] → Uint8Array, the - // two coercions Compact circuits invariably need. - const argsLiteral = JSON.stringify(opts.args ?? []); - - return `${SCRIPT_PRELUDE} -import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; -setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); - -${rpcClientCode(opts.servePort)} -${contractSetupCode(opts.contractName, opts.managedDir)} - -process.stderr.write('Connecting to mn serve...\\n'); -await rpcConnect(); -process.stderr.write('Connected\\n'); - -${PROVIDER_IMPORTS} -${walletProviderCode()} -${providerSetupCode(opts.networkConfig, privateStateKey)} - -import { deployContract } from '@midnight-ntwrk/midnight-js-contracts'; - -${ARG_COERCE_FN} -const constructorArgs = (${argsLiteral}).map(coerceArg); -process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n'); -const deployed = await deployContract(providers, { - compiledContract: compiled, - privateStateId: ${JSON.stringify(privateStateKey)}, - initialPrivateState: makeInitialPrivateState(), - args: constructorArgs, -}); - -const address = deployed.deployTxData?.public?.contractAddress ?? 'unknown'; -process.stderr.write('Deploy complete: ' + address + '\\n'); - -console.log(JSON.stringify({ contractAddress: address })); -rpcClose(); -process.exit(0); -`; -} - -export function generateCallScript(opts: CallOptions): string { - const privateStateKey = opts.privateStateKey ?? `${opts.contractName}PrivateState`; - - return `${SCRIPT_PRELUDE} -import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; -setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); - -${rpcClientCode(opts.servePort)} -${contractSetupCode(opts.contractName, opts.managedDir)} - -process.stderr.write('Connecting to mn serve...\\n'); -await rpcConnect(); -process.stderr.write('Connected\\n'); - -${PROVIDER_IMPORTS} -${walletProviderCode()} -${providerSetupCode(opts.networkConfig, privateStateKey)} - -import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; - -process.stderr.write('Finding deployed contract...\\n'); -const deployed = await findDeployedContract(providers, { - compiledContract: compiled, - contractAddress: ${JSON.stringify(opts.contractAddress)}, - privateStateId: ${JSON.stringify(privateStateKey)}, - initialPrivateState: makeInitialPrivateState(), -}); - -process.stderr.write('Calling ${opts.circuit}...\\n'); -${ARG_COERCE_FN} -const args = (${JSON.stringify(opts.args ?? [])}).map(coerceArg); -await deployed.callTx.${opts.circuit}(...args); - -console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(opts.circuit)} })); -rpcClose(); -process.exit(0); -`; -} - -export function generateStateScript(opts: StateOptions): string { - return `${SCRIPT_PRELUDE} -import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; -setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); - -import { pathToFileURL } from 'node:url'; -import { resolve } from 'node:path'; -import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; - -const MANAGED_DIR = ${JSON.stringify(opts.managedDir)}; - -// Load the contract module which exports the ledger() function -const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract', 'index.js')).href); - -if (typeof contractMod.ledger !== 'function') { - fail(new Error('Contract module does not export a ledger() function')); -} - -process.stderr.write('Querying contract state...\\n'); -const provider = indexerPublicDataProvider({ - queryURL: process.env.${INDEXER_URL_ENV}, - subscriptionURL: process.env.${INDEXER_WS_URL_ENV}, -}); - -const contractState = await provider.queryContractState(${JSON.stringify(opts.contractAddress)}); -if (!contractState) { - fail(new Error('No contract found at address ${opts.contractAddress}')); -} - -process.stderr.write('Parsing ledger state...\\n'); -// ledger() expects contractState.data (ChargedState), not the full ContractState -const state = contractMod.ledger(contractState.data ?? contractState); - -// Extract scalar fields and map fields -const fields = {}; -const maps = {}; - -for (const key of Object.keys(state)) { - const val = state[key]; - - // Check if it's a map-like (has size() and Symbol.iterator) - if (val && typeof val === 'object' && typeof val.size === 'function') { - try { - maps[key] = { size: val.size().toString() }; - } catch { - maps[key] = { size: '?' }; - } - } else if (typeof val === 'bigint') { - fields[key] = val.toString(); - } else if (typeof val === 'string') { - fields[key] = val; - } else if (typeof val === 'boolean') { - fields[key] = String(val); - } else if (val instanceof Uint8Array) { - fields[key] = Array.from(val).map(b => b.toString(16).padStart(2, '0')).join(''); - } else if (val !== undefined && val !== null) { - try { fields[key] = JSON.stringify(val); } catch { fields[key] = '?'; } - } -} - -console.log(JSON.stringify({ fields, maps })); -process.exit(0); -`; -} +/** What every SDK set's script shares, for the engine to write it with. */ +export const SCRIPT_PARTS: ScriptParts = { + prelude: SCRIPT_PRELUDE, + rpcClientCode, + coerceArgFn: ARG_COERCE_FN, + privateStateSecretFn: PRIVATE_STATE_SECRET_FN, + witnessCandidates: WITNESS_FILE_CANDIDATES, + indexerUrlEnv: INDEXER_URL_ENV, + indexerWsUrlEnv: INDEXER_WS_URL_ENV, +}; // ── Script execution ── /** What the overlay made, to undo afterwards newest first: a link, or a folder it created. */ type Made = { path: string; kind: 'link' | 'folder' }; -/** The installed copy of each scope SCRIPT_PACKAGES uses (`@midnight-ntwrk`, …), and the node_modules holding them. */ -function installedTrees(): { root: string | null; scopes: Map } { +/** The packages a script imports, and where the engine's install has each. */ +type ScriptPackages = Pick; + +/** The installed copy of each scope the script packages use (`@midnight-ntwrk`, …), and the node_modules holding them. */ +function installedTrees({ packages, packageFolder }: ScriptPackages): { root: string | null; scopes: Map } { const scopes = new Map(); let root: string | null = null; - for (const name of SCRIPT_PACKAGES) { + for (const name of packages) { if (!name.startsWith('@')) continue; const folder = packageFolder(name); if (folder === null) continue; @@ -598,9 +291,9 @@ function installedTrees(): { root: string | null; scopes: Map } } /** - * Make SCRIPT_PACKAGES, and whatever else a dApp's witnesses import from the - * same installed tree, resolvable from `userNodeModules`, finding mn's copy - * by name (never by walking up from this file): + * Make the script packages, and whatever else a dApp's witnesses import from + * the same installed tree, resolvable from `userNodeModules`, finding the + * engine's copy by name (never by walking up from this file): * - a dApp with no node_modules gets a link to the node_modules holding them; * - a dApp without one of their scopes gets a link to that whole scope; * - a package still missing (in a scope the dApp has, or unscoped) is linked @@ -609,7 +302,7 @@ function installedTrees(): { root: string | null; scopes: Map } * shadow. What can't be found or linked is left out, and the script then fails * with Node's clear ERR_MODULE_NOT_FOUND. */ -export function overlayScriptPackages(userNodeModules: string): Made[] { +export function overlayScriptPackages(userNodeModules: string, scriptPackages: ScriptPackages): Made[] { const made: Made[] = []; const link = (target: string, at: string): void => { try { @@ -617,7 +310,7 @@ export function overlayScriptPackages(userNodeModules: string): Made[] { made.push({ path: at, kind: 'link' }); } catch { /* left out: the script reports the missing package */ } }; - const { root, scopes } = installedTrees(); + const { root, scopes } = installedTrees(scriptPackages); if (!existsSync(userNodeModules)) { if (root !== null) link(root, userNodeModules); return made; @@ -626,9 +319,9 @@ export function overlayScriptPackages(userNodeModules: string): Made[] { const at = join(userNodeModules, scope); if (!existsSync(at)) link(folder, at); } - for (const name of SCRIPT_PACKAGES) { + for (const name of scriptPackages.packages) { const at = join(userNodeModules, name); - const target = existsSync(at) ? null : packageFolder(name); + const target = existsSync(at) ? null : scriptPackages.packageFolder(name); if (target !== null) link(target, at); } return made; @@ -658,12 +351,12 @@ const isAlive = (pid: number): boolean => { * removes links another still uses; a run that died leaves its pid, which the * next run drops. */ -export function acquireOverlay(dappDir: string): void { +export function acquireOverlay(dappDir: string, scriptPackages: ScriptPackages): void { const record = join(dappDir, OVERLAY_RECORD); let held: OverlayRecord | null = null; try { held = JSON.parse(readFileSync(record, 'utf8')) as OverlayRecord; } catch { /* none yet */ } const live = (held?.pids ?? []).filter(isAlive); - const made = held !== null ? held.made : overlayScriptPackages(join(dappDir, 'node_modules')); + const made = held !== null ? held.made : overlayScriptPackages(join(dappDir, 'node_modules'), scriptPackages); writeFileSync(record, JSON.stringify({ pids: [...live, process.pid], made } satisfies OverlayRecord)); } @@ -695,6 +388,8 @@ export interface ScriptRun { cwd?: string; /** Make mn's own SDK packages resolvable from `dir` when it lacks them. Default true. */ overlaySdk?: boolean; + /** The packages the script imports, and where the engine's install has each: what the overlay links. */ + packages: ScriptPackages; /** What the script is for: part of its (hidden, removed afterwards) file name. Default "contract". */ label?: string; /** Stops the run when it aborts: the script's process is killed, and the run fails as cancelled. */ @@ -736,7 +431,7 @@ export function scriptRuntime( } /** Runs a generated script and returns what it wrote to stdout. Throws its marked error when it fails. */ -export async function executeScript({ dir: dappDir, script, onMessage, env: extraEnv, cwd, overlaySdk = true, label = 'contract', signal, findRuntime = scriptRuntime }: ScriptRun): Promise { +export async function executeScript({ dir: dappDir, script, packages, onMessage, env: extraEnv, cwd, overlaySdk = true, label = 'contract', signal, findRuntime = scriptRuntime }: ScriptRun): Promise { throwIfCancelled(signal); // ESM resolution walks up from the importing file's location to find // node_modules; NODE_PATH does NOT work for ESM. Three different files @@ -751,7 +446,7 @@ export async function executeScript({ dir: dappDir, script, onMessage, env: extr const runtime = findRuntime(); // Unique to this run, so two at once in one directory never share a script. const scriptPath = join(dappDir, `.mn-${label}-${Date.now()}-${randomBytes(SCRIPT_NAME_RANDOM_BYTES).toString('hex')}.mjs`); - if (overlaySdk) acquireOverlay(dappDir); + if (overlaySdk) acquireOverlay(dappDir, packages); const cleanup = () => { try { unlinkSync(scriptPath); } catch {} // Our share of the overlay goes back; the last run out undoes it (links diff --git a/src/lib/engine.ts b/src/lib/engine.ts index 346b2262..e83e7e86 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -58,12 +58,67 @@ export type RawStateValue = | { type: 'map'; size: number } | { type: 'boundedMerkleTree'; height: number; root: string[] | null }; +/** What every SDK set's contract script shares, which the contract runner gives the engine. */ +export interface ScriptParts { + /** First in every script: reports a failure as one marked line. */ + readonly prelude: string; + /** The client of mn serve's RPC on that port, defining rpcConnect, rpcCall and rpcClose. */ + rpcClientCode(servePort: number): string; + /** Defines coerceArg, which turns a JSON argument into a circuit's runtime value. */ + readonly coerceArgFn: string; + /** Defines resolvePrivateStateSecretKey. */ + readonly privateStateSecretFn: string; + /** Where the dApp's witnesses may be, relative to its folder. */ + readonly witnessCandidates: readonly string[]; + /** The environment variables carrying the indexer's URLs, which never go into a script's text. */ + readonly indexerUrlEnv: string; + readonly indexerWsUrlEnv: string; +} + +/** A compiled contract, as the scripts load it. */ +export interface ScriptContract { + networkConfig: NetworkConfig; + managedDir: string; + contractName: string; +} + +export interface DeployScript extends ScriptContract { + servePort: number; + privateStateKey?: string; + args?: unknown[]; +} + +export interface CallScript extends ScriptContract { + servePort: number; + contractAddress: string; + circuit: string; + args?: unknown[]; + privateStateKey?: string; +} + +export interface StateScript extends ScriptContract { + contractAddress: string; +} + +/** The scripts mn runs in a dApp's folder, and the packages they import, for one SDK set. */ +export interface EngineContractScripts { + /** Every package a script imports, and the compact runtime a compiled contract imports. */ + readonly packages: readonly string[]; + /** The folder of one of them as this engine's install has it; null when it isn't installed. */ + packageFolder(name: string): string | null; + deploy(script: DeployScript, parts: ScriptParts): string; + call(script: CallScript, parts: ScriptParts): string; + state(script: StateScript, parts: ScriptParts): string; +} + /** What an engine does with contracts in mn's own process. */ export interface EngineContracts { /** A deployed contract's raw ledger state from the indexer; null when no contract is at `address`. */ rawState(networkConfig: NetworkConfig, address: string): Promise; /** Whether midnight-js accepts a private-state password (its own policy, which a random draw can miss). */ acceptsPrivateStatePassword(password: string): boolean; + /** The scripts the contract runner runs in a dApp's folder. */ + readonly scripts: EngineContractScripts; } /** One SDK set, as mn uses it. */ diff --git a/src/lib/test/actions-runner.ts b/src/lib/test/actions-runner.ts index c573b408..88569f10 100644 --- a/src/lib/test/actions-runner.ts +++ b/src/lib/test/actions-runner.ts @@ -3,7 +3,7 @@ import { existsSync, readFileSync } from 'node:fs'; import type { TestAction, DappTestConfig } from './types.ts'; -import type { NetworkConfig } from '../network.ts'; +import type { NetworkConfig, NetworkName } from '../network.ts'; import { runDeploy, runCall, runState, type StateResult } from '../contract/runner.ts'; import { findContractInfo, type ContractInfo } from '../contract/inspect.ts'; import { analyzeWitnessDependencies } from './circuit-witness-deps.ts'; @@ -104,6 +104,7 @@ export async function runActions(options: ActionsRunnerOptions): Promise Date: Sun, 1 Nov 2026 18:33:25 -0800 Subject: [PATCH 26/88] Engine, part 6: the wallet core's SDK-free helpers in core Before the wallet core moves behind the engine, what it uses that needs no SDK becomes reachable from an engine (which may use only core and chain): - The connector's wire protocol (the API's errors, the handler types, createApiError) is connector-api.ts in core; ws-rpc keeps the WebSocket server and re-exports them. - The approval prompt, fee limits, transaction hex, data signing, the Dust wait and the Dust balancing and registration plans depend only on core, and now sit there; the transaction segments' reader sits in chain. - dust.ts loses three imports it never used (the ledger, the Dust seed and the Dust key helper), which is all that kept it on the pending list (ten left). No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.mjs | 7 +++--- src/__tests__/layering.test.ts | 1 - src/commands/dust.ts | 3 --- src/lib/connector-api.ts | 43 ++++++++++++++++++++++++++++++++++ src/lib/dapp-connector.ts | 2 +- src/lib/ws-rpc.ts | 42 +++------------------------------ 6 files changed, 50 insertions(+), 48 deletions(-) create mode 100644 src/lib/connector-api.ts diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index b3b81b11..5b0bfff5 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -42,12 +42,12 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], ['chain', /^commands\/status(\.definition)?\.ts$/], - ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription)\.ts$/], + ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription|tx-segments)\.ts$/], ['wallet', /^commands\/(wallet|generate|address|genesis-address|info|balance|transfer|airdrop|dust|cache)(\.definition)?\.ts$/], ['wallet', /^lib\/(derivation|derive-address|wallet-config|seed-resolver|passphrase|facade|wallet-data-repository|transfer|transfer-request|sync-eta|wallet-can-pay|wallet-create|airdrop|wallet-protector|chain-caches|wallet-paths|fork-schedule)\.ts$/], @@ -58,7 +58,7 @@ const HOMES = [ ['contract', /^lib\/chain-params\.ts$/], ['connect', /^commands\/serve(\.definition)?\.ts$/], - ['connect', /^lib\/(dapp-connector|ws-rpc|approval|fee-limits|fee-only-check|sign-data|sign-recipe|tx-inspect|tx-segments|tx-serde|serve-manager|serve-payer)\.ts$/], + ['connect', /^lib\/(dapp-connector|ws-rpc|sign-recipe|serve-manager|serve-payer)\.ts$/], ['dev', /^commands\/(dev|test|localnet)(\.definition)?\.ts$/], ['dev', /^lib\/localnet\.ts$/], @@ -105,7 +105,6 @@ const ENGINE_LOADER = 'lib/engine.ts'; export const PENDING_ENGINE = new Set([ 'commands/airdrop.ts', 'commands/balance.ts', - 'commands/dust.ts', 'commands/transfer.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 7a62ebb7..3dca137f 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -52,7 +52,6 @@ describe('the layering', () => { expect([...PENDING_ENGINE].sort()).toStrictEqual([ 'commands/airdrop.ts', 'commands/balance.ts', - 'commands/dust.ts', 'commands/transfer.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 880d2302..85c45295 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -1,7 +1,6 @@ // dust command — register UTXOs for dust generation, check status, export a snapshot // Usage: midnight dust register | midnight dust status | midnight dust export -import * as ledger from '@midnightntwrk/ledger-v9'; import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites } from '../lib/argv.ts'; import { UsageError, throwIfCancelled } from '../lib/errors.ts'; @@ -9,10 +8,8 @@ import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides, type NetworkConfig } from '../lib/network.ts'; -import { deriveDustSeed } from '../engine/rc/derivation.ts'; import { registerDust } from '../lib/dust-register.ts'; import { checkBalance } from '../lib/balance-subscription.ts'; -import { dustPublicKeyHex } from '../engine/rc/dust-direct-cache.ts'; import { exportDustSnapshot } from '../lib/dust-export.ts'; import { defaultRepository } from '../lib/wallet-data-repository.ts'; import { header, keyValue, divider, formatDust, successMessage, toDust } from '../ui/format.ts'; diff --git a/src/lib/connector-api.ts b/src/lib/connector-api.ts new file mode 100644 index 00000000..ce7a51dd --- /dev/null +++ b/src/lib/connector-api.ts @@ -0,0 +1,43 @@ +// The DApp Connector's wire protocol, as its handlers see it: the API's +// errors and the handler signature. SDK-free and transport-free, so the +// engine's connector and connect's WebSocket server share it. + +/** + * The DApp Connector API's error codes, as its specification names them + * (dapp-connector-api's ErrorCodes; a test keeps the two equal). The wire + * protocol is the same whatever SDK set serves it, so the transport owns it. + */ +export type ErrorCode = 'InternalError' | 'Rejected' | 'InvalidRequest' | 'PermissionRejected' | 'Disconnected'; + +/** The DApp Connector API's error: an Error with its code and reason, told apart by `type` (the specification's APIError). */ +export type APIError = Error & { + type: 'DAppConnectorAPIError'; + code: ErrorCode; + reason: string; +}; + +// ── Handler context & type ── + +/** Per-invocation context passed to each handler (scoped to the calling connection) */ +export interface RpcHandlerContext { + /** Send a JSON-RPC notification to the calling client */ + notify: (method: string, params?: Record) => void; + /** ID of the connection that sent this request (e.g. "conn_1") */ + connectionId: string; + /** JSON-RPC request ID */ + requestId: number | string; + /** Handlers can stash arbitrary data here for onResponse to read */ + metadata: Record; +} + +export type RpcHandler = (params: Record, context: RpcHandlerContext) => Promise; + +// ── APIError factory ── + +export function createApiError(code: ErrorCode, reason: string): APIError { + const error = new Error(reason) as APIError; + error.type = 'DAppConnectorAPIError'; + error.code = code; + error.reason = reason; + return error; +} diff --git a/src/lib/dapp-connector.ts b/src/lib/dapp-connector.ts index 076cb0b6..7e1b5448 100644 --- a/src/lib/dapp-connector.ts +++ b/src/lib/dapp-connector.ts @@ -12,7 +12,7 @@ import { type FacadeBundle, hasDustAvailable } from './facade.ts'; import { LEDGER_9_FORK_VERSION, type NetworkConfig } from './network.ts'; import type { ApprovalOptions } from './approval.ts'; import { promptApproval } from './approval.ts'; -import { createApiError, type RpcHandler, type RpcHandlerContext } from './ws-rpc.ts'; +import { createApiError, type RpcHandler, type RpcHandlerContext } from './connector-api.ts'; import { createPhaseTracker, type PhaseTracker } from './phase-tracker.ts'; import { toHex, fromHex } from './tx-serde.ts'; import { getNetworkId } from './network-id.ts'; diff --git a/src/lib/ws-rpc.ts b/src/lib/ws-rpc.ts index 8be7bac0..344ec842 100644 --- a/src/lib/ws-rpc.ts +++ b/src/lib/ws-rpc.ts @@ -3,20 +3,10 @@ import { WebSocketServer, WebSocket } from 'ws'; import { notice } from './notices.ts'; +import type { APIError, RpcHandler, RpcHandlerContext } from './connector-api.ts'; -/** - * The DApp Connector API's error codes, as its specification names them - * (dapp-connector-api's ErrorCodes; a test keeps the two equal). The wire - * protocol is the same whatever SDK set serves it, so the transport owns it. - */ -export type ErrorCode = 'InternalError' | 'Rejected' | 'InvalidRequest' | 'PermissionRejected' | 'Disconnected'; - -/** The DApp Connector API's error: an Error with its code and reason, told apart by `type` (the specification's APIError). */ -export type APIError = Error & { - type: 'DAppConnectorAPIError'; - code: ErrorCode; - reason: string; -}; +// The wire types the connector's handlers use, from where every package can reach them. +export { createApiError, type APIError, type ErrorCode, type RpcHandler, type RpcHandlerContext } from './connector-api.ts'; // ── JSON-RPC 2.0 types ── @@ -53,22 +43,6 @@ export interface JsonRpcNotification { params?: Record; } -// ── Handler context & type ── - -/** Per-invocation context passed to each handler (scoped to the calling connection) */ -export interface RpcHandlerContext { - /** Send a JSON-RPC notification to the calling client */ - notify: (method: string, params?: Record) => void; - /** ID of the connection that sent this request (e.g. "conn_1") */ - connectionId: string; - /** JSON-RPC request ID */ - requestId: number | string; - /** Handlers can stash arbitrary data here for onResponse to read */ - metadata: Record; -} - -export type RpcHandler = (params: Record, context: RpcHandlerContext) => Promise; - // ── DApp Connector error code → JSON-RPC error code mapping ── const API_ERROR_TO_RPC_CODE: Record = { @@ -373,13 +347,3 @@ export function createRpcServer(options: RpcServerOptions): RpcServer { return { wss, connections, ready, close }; } - -// ── APIError factory ── - -export function createApiError(code: ErrorCode, reason: string): APIError { - const error = new Error(reason) as APIError; - error.type = 'DAppConnectorAPIError'; - error.code = code; - error.reason = reason; - return error; -} From e2d6bb6386c3c8adafaad7e0a70adfcdd69ec23e Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:35:10 -0800 Subject: [PATCH 27/88] Engine, part 7: balance reads keys, NIGHT and shielded balance from the engine balance takes its addresses, NIGHT's token id and the shielded balance (readers.shieldedBalance, mn's own reader, now on the engine) from the engine for its network, and imports no SDK. Nine modules left on the pending list. No behaviour changes: suite and snapshot unchanged. --- scripts/check-layering.mjs | 1 - src/__tests__/layering.test.ts | 1 - src/commands/balance.ts | 16 +++++------- src/engine/rc/index.ts | 5 +++- src/engine/rc/shielded-direct-cache.ts | 23 ++-------------- src/lib/engine.ts | 36 ++++++++++++++++++++++++++ 6 files changed, 48 insertions(+), 34 deletions(-) diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 5b0bfff5..6850e112 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -104,7 +104,6 @@ const ENGINE_LOADER = 'lib/engine.ts'; // list only shrinks (a test pins it), and is empty when the engine is done. export const PENDING_ENGINE = new Set([ 'commands/airdrop.ts', - 'commands/balance.ts', 'commands/transfer.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 3dca137f..c0da6c54 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -51,7 +51,6 @@ describe('the layering', () => { it('has no module importing the SDK outside the engine but those still waiting to move', () => { expect([...PENDING_ENGINE].sort()).toStrictEqual([ 'commands/airdrop.ts', - 'commands/balance.ts', 'commands/transfer.ts', 'lib/dapp-connector.ts', 'lib/dust-wallet.ts', diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 33498422..50cdb7e6 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -1,8 +1,6 @@ // balance command — check unshielded + shielded balance via full wallet sync // For positional address: unshielded only (GraphQL, no facade needed) -import * as ledger from '@midnightntwrk/ledger-v9'; -import { MidnightBech32m } from '@midnightntwrk/wallet-sdk/address-format'; import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '../lib/argv.ts'; import { type NetworkName, isValidNetworkName } from '../lib/network.ts'; import { saveShieldedAddress, findWalletByAddress } from '../lib/wallet-config.ts'; @@ -10,12 +8,10 @@ import { resolveSeedSource } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides } from '../lib/network.ts'; import { shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; -import { getNetworkId } from '../lib/network-id.ts'; import { isNativeToken } from '../lib/balance-subscription.ts'; import { defaultRepository } from '../lib/wallet-data-repository.ts'; -import { readShieldedBalanceCached } from '../engine/rc/shielded-direct-cache.ts'; +import { engineFor } from '../lib/engine.ts'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; -import { deriveShieldedAddress, deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { getChainGenesisHash } from '../lib/chain-id.ts'; import { createEtaEstimator, formatSyncStatus } from '../lib/sync-eta.ts'; import { header, keyValue, divider, formatNight, formatAddress, toNight } from '../ui/format.ts'; @@ -183,7 +179,8 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise ctx.diagnostics.line('balance', `wallet path=${walletPath ?? '(from --seed/MN_SEED)'}`); // Derive the unshielded address from the seed so a --seed/MN_SEED caller (no wallet // file) behaves identically to a named wallet — for a wallet this equals the stored one. - const address = config?.addresses[networkName] ?? deriveUnshieldedAddress(seedBuffer, networkName); + const engine = await engineFor(networkName); + const address = config?.addresses[networkName] ?? engine.keys.unshieldedAddress(seedBuffer, networkName); const shieldedAddrStr = config?.shieldedAddresses?.[networkName] ?? ''; applyEndpointOverrides(networkConfig, { @@ -196,7 +193,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise const stopListening = ctx.sdkWarnings.listen(undefined); const noCache = hasFlag(args, 'no-cache'); const isJson = hasFlag(args, 'json'); - const nightToken = ledger.unshieldedToken().raw; + const nightToken = engine.ledger.nightTokenId(); let activeSpinner: Spinner | null = null; @@ -257,10 +254,9 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise if (shieldedEnabled) { if (!isJson) activeSpinner = ctx.progress.start('Syncing shielded...'); const eta = createEtaEstimator(); - const networkId = getNetworkId(networkConfig.networkId); // Live shielded address is pure key derivation — no facade sync needed. - liveShieldedAddrStr = MidnightBech32m.encode(networkId, deriveShieldedAddress(seedBuffer)).asString(); + liveShieldedAddrStr = engine.keys.shieldedAddress(seedBuffer, networkName); // Cache the shielded address only when there's a backing wallet file (skip for --seed/MN_SEED). if (walletPath) saveShieldedAddress(walletPath, networkName, liveShieldedAddrStr); @@ -272,7 +268,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise await assertLedgerSupported(networkName, networkConfig, fetchProtocolVersion, ctx.signal); // Null when the node can't say (the cache check is then skipped); a cancelled call stops here. const chainId = (await getChainGenesisHash(networkConfig.node, ctx.signal)) ?? undefined; - const shieldedResult = await readShieldedBalanceCached( + const shieldedResult = await engine.readers.shieldedBalance( seedBuffer, networkName, networkConfig.indexerWS, diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index ab7a3650..03013fcd 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -9,7 +9,7 @@ import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; +import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; export const rcEngine: Engine = { @@ -45,4 +45,7 @@ export const rcEngine: Engine = { state: generateStateScript, }, }, + readers: { + shieldedBalance: readShieldedBalanceCached, + }, }; diff --git a/src/engine/rc/shielded-direct-cache.ts b/src/engine/rc/shielded-direct-cache.ts index b0bd000d..e069e606 100644 --- a/src/engine/rc/shielded-direct-cache.ts +++ b/src/engine/rc/shielded-direct-cache.ts @@ -123,27 +123,8 @@ export function saveShieldedCache( } -export interface ShieldedBalanceResult { - /** Native (NIGHT) shielded balance in atomic units. */ - balance: bigint; - /** Number of spendable NIGHT coins. */ - availableCoins: number; - /** Events applied in this run (delta since last cache save). */ - eventCount: number; - /** Latest event id in the saved cache (carried from prior cache if no new events). */ - lastAppliedEventId: number; - /** True if an existing cache was loaded and extended; false if synced from scratch. */ - fromCache: boolean; - /** True if the sync stopped before catching up (timeout/abort) — resume next call. */ - partial: boolean; -} - -export interface ShieldedCachedOptions extends Pick { - /** Ignore any cached state and re-sync from the beginning (honours --no-cache). */ - forceFresh?: boolean; - /** Current chain genesis hash — stored on save and checked on load (chain-reset guard). */ - chainId?: string; -} +export type { ShieldedBalanceResult, ShieldedCachedOptions } from '../../lib/engine.ts'; +import type { ShieldedBalanceResult, ShieldedCachedOptions } from '../../lib/engine.ts'; /** * Read the shielded NIGHT balance for a wallet seed, using (and refreshing) the diff --git a/src/lib/engine.ts b/src/lib/engine.ts index e83e7e86..97f5ba69 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -121,12 +121,48 @@ export interface EngineContracts { readonly scripts: EngineContractScripts; } +/** A wallet's shielded NIGHT, from mn's own reader of the indexer's events. */ +export interface ShieldedBalanceResult { + /** Native (NIGHT) shielded balance in atomic units. */ + balance: bigint; + /** Number of spendable NIGHT coins. */ + availableCoins: number; + /** Events applied in this run (delta since last cache save). */ + eventCount: number; + /** Latest event id in the saved cache (carried from prior cache if no new events). */ + lastAppliedEventId: number; + /** True if an existing cache was loaded and extended; false if synced from scratch. */ + fromCache: boolean; + /** True if the sync stopped before catching up (timeout/abort) — resume next call. */ + partial: boolean; +} + +export interface ShieldedCachedOptions { + /** Called with (eventsApplied, maxIdSeen) whenever a new event arrives. */ + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + /** Stops the read; what was applied is kept for the next. */ + signal?: AbortSignal; + /** Soft ceiling for the whole read, after which it returns what it has (partial). */ + timeoutMs?: number; + /** Ignore any cached state and re-sync from the beginning (honours --no-cache). */ + forceFresh?: boolean; + /** Current chain genesis hash — stored on save and checked on load (chain-reset guard). */ + chainId?: string; +} + +/** mn's own readers of a wallet's chain state, beside the SDK's wallet. */ +export interface EngineReaders { + /** The shielded NIGHT balance of a seed on a network, reading (and extending) its cache. */ + shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options?: ShieldedCachedOptions): Promise; +} + /** One SDK set, as mn uses it. */ export interface Engine { readonly set: SdkSet; readonly keys: EngineKeys; readonly ledger: EngineLedger; readonly contracts: EngineContracts; + readonly readers: EngineReaders; } /** The SDK set a network runs on. */ From 542af21e00e84c3d1b135179b0a7359c64a55624 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 18:44:30 -0800 Subject: [PATCH 28/88] Engine, part 8: the wallet behind the engine; only the engine imports the SDK The wallet core moves into the rc engine: the facade, the Dust wallet, the fork schedule, transfers, the sign recipe, the DApp connector, the wallet repository, Dust registration and export, and the genesis airdrop. Everything else reaches it through engine.wallet, whose methods take and return mn's own types: - balances (unshieldedBalance, dustBalance), transfer, airdrop, registerDust, exportDust: the functions that existed, behind the interface; - shieldedTransfer: the shielded flow transfer and airdrop each ran themselves, once, with their own messages passed in; - prepNightBalance and prepDust: test prep's quick-sync checks; - openConnector: serve-manager's connector for mn's own commands; - serveWallet: mn serve's strictly synced wallet, with its Dust wait, its save (skipped while transactions are pending) and its connector. The wallet's public types (transfer and Dust parameters and results, balance views, the connector's shape and callbacks) are the interface's, in core. The pending list is empty and gone: the layering check now refuses an SDK import anywhere but an engine. No behaviour changes: the suite passes and the snapshot is unchanged. --- scripts/check-layering.d.mts | 2 - scripts/check-layering.mjs | 19 +- scripts/check-process-safety.mjs | 2 +- src/__tests__/dapp-connector.test.ts | 8 +- src/__tests__/dust-export.test.ts | 6 +- src/__tests__/dust-logic.test.ts | 4 +- src/__tests__/dust-wallet.test.ts | 4 +- src/__tests__/facade.test.ts | 12 +- src/__tests__/fee-only-signing.test.ts | 2 +- src/__tests__/helpers/offline-facade.ts | 4 +- src/__tests__/layering.test.ts | 18 +- src/__tests__/network-id.test.ts | 2 +- src/__tests__/read-cancellation.test.ts | 2 +- src/__tests__/sign-recipe.test.ts | 2 +- src/__tests__/transfer-lib.test.ts | 2 +- src/__tests__/verbose-per-call.test.ts | 2 +- src/__tests__/wallet-data-repository.test.ts | 2 +- .../wallet-state-to-restore.live.test.ts | 2 +- src/commands/airdrop.ts | 118 ++----- src/commands/balance.ts | 5 +- src/commands/dust.ts | 20 +- src/commands/serve.ts | 62 ++-- src/commands/transfer.ts | 103 ++---- src/{lib => engine/rc}/airdrop.ts | 5 +- src/{lib => engine/rc}/dapp-connector.ts | 58 ++-- src/{lib => engine/rc}/dust-export.ts | 32 +- src/{lib => engine/rc}/dust-register.ts | 32 +- src/{lib => engine/rc}/dust-wallet.ts | 4 +- src/{lib => engine/rc}/facade.ts | 22 +- src/{lib => engine/rc}/fork-schedule.ts | 0 src/engine/rc/index.ts | 2 + src/{lib => engine/rc}/sign-recipe.ts | 2 +- src/{lib => engine/rc}/transfer.ts | 62 +--- .../rc}/wallet-data-repository.ts | 88 ++---- src/engine/rc/wallet.ts | 299 ++++++++++++++++++ src/lib/balance-subscription.ts | 12 +- src/lib/connector-api.ts | 3 + src/lib/dev/provision-wallets.ts | 8 +- src/lib/engine.ts | 252 +++++++++++++++ src/lib/serve-manager.ts | 91 +----- src/lib/test/prep-runner.ts | 63 +--- src/lib/wallet-can-pay.ts | 8 +- 42 files changed, 806 insertions(+), 640 deletions(-) rename src/{lib => engine/rc}/airdrop.ts (83%) rename src/{lib => engine/rc}/dapp-connector.ts (96%) rename src/{lib => engine/rc}/dust-export.ts (77%) rename src/{lib => engine/rc}/dust-register.ts (61%) rename src/{lib => engine/rc}/dust-wallet.ts (98%) rename src/{lib => engine/rc}/facade.ts (98%) rename src/{lib => engine/rc}/fork-schedule.ts (100%) rename src/{lib => engine/rc}/sign-recipe.ts (98%) rename src/{lib => engine/rc}/transfer.ts (92%) rename src/{lib => engine/rc}/wallet-data-repository.ts (91%) create mode 100644 src/engine/rc/wallet.ts diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 42440370..68074d49 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -4,5 +4,3 @@ export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; export function importRule(fromRel: string, toRel: string): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; -/** Modules that still import the SDK themselves, until each moves behind the engine. */ -export const PENDING_ENGINE: ReadonlySet; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 6850e112..0be081e7 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -99,22 +99,7 @@ const MIDNIGHT_SDK = /^@midnight(-ntwrk|ntwrk)\//; // engine for a network's SDK set when a call needs it. const ENGINE_LOADER = 'lib/engine.ts'; -// Modules that still import the SDK themselves, until each moves behind the -// engine; a module on the list may also import the engine's own files. The -// list only shrinks (a test pins it), and is empty when the engine is done. -export const PENDING_ENGINE = new Set([ - 'commands/airdrop.ts', - 'commands/transfer.ts', - 'lib/dapp-connector.ts', - 'lib/dust-wallet.ts', - 'lib/facade.ts', - 'lib/fork-schedule.ts', - 'lib/sign-recipe.ts', - 'lib/transfer.ts', - 'lib/wallet-data-repository.ts', -]); const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; -const SDK_FREE = new Set(['core', 'chain']); // import ... from 'x', export ... from 'x', import 'x', import('x'). const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; @@ -168,7 +153,7 @@ export function importRule(fromRel, toRel) { const callsCommand = isCommand(toRel) && (!isCommand(fromRel) || targetHome !== home); if (callsCommand && !DISPATCHERS.has(home)) return `${isCommand(fromRel) ? 'command' : 'library'} → ${targetHome} command`; if (targetHome === 'engine' && home !== 'engine') { - return fromRel === ENGINE_LOADER || PENDING_ENGINE.has(fromRel) ? undefined : `${home} → engine (reach it through ${ENGINE_LOADER})`; + return fromRel === ENGINE_LOADER ? undefined : `${home} → engine (reach it through ${ENGINE_LOADER})`; } if (!MAY_IMPORT[home].includes(targetHome)) return `${home} → ${targetHome}`; return undefined; @@ -200,7 +185,7 @@ export function findLayeringProblems() { if (specifier.startsWith('.')) { const rule = importRule(rel, relative(SRC, resolve(dirname(file), specifier))); if (rule !== undefined) violations.push({ home, rule, where, specifier }); - } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine' && (SDK_FREE.has(home) || !PENDING_ENGINE.has(rel))) { + } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine') { violations.push({ home, rule: `${home} → Midnight SDK (only an engine imports it)`, where, specifier }); } else if (home !== 'grant' && ACCOUNT_CHAIN.test(specifier)) { violations.push({ home, rule: `${home} → account chain`, where, specifier }); diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index a4fef87f..5d2f5407 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -84,7 +84,7 @@ export const ALLOWED = { export const ALLOWED_STATE = { // Shared on purpose: none holds a call's state. 'lib/passphrase.ts': { unlocked: 'shared on purpose: the passphrase this process has unlocked, by state root (one prompt per run)' }, - 'lib/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, + 'engine/rc/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/ws-rpc.ts': { connectionCounter: 'shared on purpose: the RPC connection id counter, unique across servers in the process' }, 'lib/engine.ts': { loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)' }, diff --git a/src/__tests__/dapp-connector.test.ts b/src/__tests__/dapp-connector.test.ts index 3ee18ccc..6289ef5a 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/src/__tests__/dapp-connector.test.ts @@ -10,19 +10,19 @@ import { Effect } from 'effect'; // Stub SDK address encoding — MidnightBech32m.encode returns a mock -import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '../lib/dapp-connector.ts'; +import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '../engine/rc/dapp-connector.ts'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; -import { PartlySignedTransactionError } from '../lib/sign-recipe.ts'; +import { PartlySignedTransactionError } from '../engine/rc/sign-recipe.ts'; import { signedMessageBytes } from '../lib/sign-data.ts'; import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { Intent, UnshieldedOffer, verifySignature } from '@midnightntwrk/ledger-v9'; -import type { FacadeBundle } from '../lib/facade.ts'; +import type { FacadeBundle } from '../engine/rc/facade.ts'; import type { NetworkConfig } from '../lib/network.ts'; import type { RpcHandlerContext } from '../lib/ws-rpc.ts'; import { PROOF_TIMEOUT_MS } from '../lib/constants.ts'; import { withDustShortfall } from '../lib/sdk-errors.ts'; import { classifyError } from '../lib/exit-codes.ts'; -import { FORK_SCHEDULE } from '../lib/fork-schedule.ts'; +import { FORK_SCHEDULE } from '../engine/rc/fork-schedule.ts'; import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '../engine/rc/derive-address.ts'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index 832c8610..d34ea55c 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { overlayDustDirectSnapshot } from '../lib/facade.ts'; +import { overlayDustDirectSnapshot } from '../engine/rc/facade.ts'; import type { DustCacheEntry } from '../engine/rc/dust-direct-cache.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; @@ -96,8 +96,8 @@ import { beforeEach, afterEach } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { exportDustSnapshot } from '../lib/dust-export.ts'; -import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; +import { exportDustSnapshot } from '../engine/rc/dust-export.ts'; +import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; import type { NetworkConfig } from '../lib/network.ts'; import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; diff --git a/src/__tests__/dust-logic.test.ts b/src/__tests__/dust-logic.test.ts index 4b565846..a90ef7ab 100644 --- a/src/__tests__/dust-logic.test.ts +++ b/src/__tests__/dust-logic.test.ts @@ -4,9 +4,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import * as rx from 'rxjs'; -import { isDustRelatedError, ensureDust, registerNightUtxos } from '../lib/transfer.ts'; +import { isDustRelatedError, ensureDust, registerNightUtxos } from '../engine/rc/transfer.ts'; import { DustFeeNotGeneratedError } from '../lib/dust-registration-plan.ts'; -import type { FacadeBundle } from '../lib/facade.ts'; +import type { FacadeBundle } from '../engine/rc/facade.ts'; import type { DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; diff --git a/src/__tests__/dust-wallet.test.ts b/src/__tests__/dust-wallet.test.ts index c857571b..3989271e 100644 --- a/src/__tests__/dust-wallet.test.ts +++ b/src/__tests__/dust-wallet.test.ts @@ -10,8 +10,8 @@ import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import { Transacting } from '@midnightntwrk/wallet-sdk/dust/v2'; import { WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk/facade'; import { EitherOps } from '@midnightntwrk/wallet-sdk/utilities'; -import { ConvergingDustTransacting, DustWallet } from '../lib/dust-wallet.ts'; -import { FORK_SCHEDULE } from '../lib/fork-schedule.ts'; +import { ConvergingDustTransacting, DustWallet } from '../engine/rc/dust-wallet.ts'; +import { FORK_SCHEDULE } from '../engine/rc/fork-schedule.ts'; import { dustShortfallOf, isDustShortage } from '../lib/sdk-errors.ts'; import { CAPTURED_AT, type FeeRange, coinsAt, computeArguments, feeRange, paymentToBalance, timeWhenSmallestReaches, transacting, diff --git a/src/__tests__/facade.test.ts b/src/__tests__/facade.test.ts index 90f1a2b5..b0a657ee 100644 --- a/src/__tests__/facade.test.ts +++ b/src/__tests__/facade.test.ts @@ -7,7 +7,7 @@ import { WebSocketServer } from 'ws'; import { SyncProgress } from '@midnightntwrk/wallet-sdk'; import { SyncProgress as UnshieldedSyncProgress } from '@midnightntwrk/wallet-sdk/unshielded/v2'; import type { FacadeState } from '@midnightntwrk/wallet-sdk/facade'; -import { isFacadeSynced, detectStaleCache } from '../lib/facade.ts'; +import { isFacadeSynced, detectStaleCache } from '../engine/rc/facade.ts'; type IndexProgress = ReturnType; type TxProgress = ReturnType; @@ -157,7 +157,7 @@ describe('startAndSyncFacade: starting the wallets exactly once', () => { async function startWith(restoredFromCache: boolean) { const { vi } = await import('vitest'); const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('../lib/facade.ts'); + const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); const seeds = { shielded: new Uint8Array([1]), unshielded: new Uint8Array([2]), dust: new Uint8Array([3]) }; const calls = { facadeStart: vi.fn(async () => {}), @@ -231,7 +231,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { async function syncWith(indexerWsUrl: string) { const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('../lib/facade.ts'); + const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, seeds: {}, @@ -260,7 +260,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const url = await indexerWith({ zswapLedgerEvents: { id: 0, maxId: 384 }, dustLedgerEvents: { id: 0, maxId: 385 } }); const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('../lib/facade.ts'); + const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); const { CancelledError } = await import('../lib/errors.ts'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, @@ -281,7 +281,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { describe('waitForDustAvailable', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const rx = await import('rxjs'); - const { waitForDustAvailable } = await import('../lib/facade.ts'); + const { waitForDustAvailable } = await import('../engine/rc/facade.ts'); const { CancelledError } = await import('../lib/errors.ts'); // A wallet with no Dust, and no later state. const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; @@ -293,7 +293,7 @@ describe('waitForDustAvailable', () => { it('returns the latest state when its timeout passes without Dust, as before', async () => { const rx = await import('rxjs'); - const { waitForDustAvailable } = await import('../lib/facade.ts'); + const { waitForDustAvailable } = await import('../engine/rc/facade.ts'); const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; await expect(waitForDustAvailable(bundle, 50, new AbortController().signal)).resolves.toBe(noDust); diff --git a/src/__tests__/fee-only-signing.test.ts b/src/__tests__/fee-only-signing.test.ts index f9bcffa4..4dd379c9 100644 --- a/src/__tests__/fee-only-signing.test.ts +++ b/src/__tests__/fee-only-signing.test.ts @@ -24,7 +24,7 @@ import { } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; import { feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; -import { signRecipe } from '../lib/sign-recipe.ts'; +import { signRecipe } from '../engine/rc/sign-recipe.ts'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, spend, unsealedBytes, diff --git a/src/__tests__/helpers/offline-facade.ts b/src/__tests__/helpers/offline-facade.ts index 16c7cd39..d0ca50d5 100644 --- a/src/__tests__/helpers/offline-facade.ts +++ b/src/__tests__/helpers/offline-facade.ts @@ -7,11 +7,11 @@ // loopback port. import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; -import { DustWallet } from '../../lib/dust-wallet.ts'; +import { DustWallet } from '../../engine/rc/dust-wallet.ts'; import { WalletFacade, WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk/facade'; import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; import { PublicKey, UnshieldedWallet, createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; -import { FORK_SCHEDULE } from '../../lib/fork-schedule.ts'; +import { FORK_SCHEDULE } from '../../engine/rc/fork-schedule.ts'; import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '../../lib/constants.ts'; import { NETWORK } from './ledger-tx.ts'; diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index c0da6c54..e9ad11b2 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -2,7 +2,7 @@ // has a package, and no import crosses the layering the planned split needs. import { describe, expect, it } from 'vitest'; -import { PENDING_ENGINE, findLayeringProblems, importRule } from '../../scripts/check-layering.mjs'; +import { findLayeringProblems, importRule } from '../../scripts/check-layering.mjs'; describe('the layering', () => { it('holds across src/', () => { @@ -46,20 +46,8 @@ describe('the layering', () => { expect(importRule('engine/rc/index.ts', 'lib/facade.ts')).toBe('engine → wallet'); }); - // Each module here still imports the SDK itself. Taking one off is the - // point of moving it behind the engine; adding one is refused. - it('has no module importing the SDK outside the engine but those still waiting to move', () => { - expect([...PENDING_ENGINE].sort()).toStrictEqual([ - 'commands/airdrop.ts', - 'commands/transfer.ts', - 'lib/dapp-connector.ts', - 'lib/dust-wallet.ts', - 'lib/facade.ts', - 'lib/fork-schedule.ts', - 'lib/sign-recipe.ts', - 'lib/transfer.ts', - 'lib/wallet-data-repository.ts', - ]); + it('lets only an engine import the SDK', () => { + // findLayeringProblems above finds none elsewhere; core, chain and every package are held to it alike. expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); }); }); diff --git a/src/__tests__/network-id.test.ts b/src/__tests__/network-id.test.ts index 23969374..0f4d41b1 100644 --- a/src/__tests__/network-id.test.ts +++ b/src/__tests__/network-id.test.ts @@ -36,7 +36,7 @@ describe('the plain values the base keeps match the SDK', () => { it("keeps the ledger-9 fork at the SDK's version, and the facade's schedule starts there", async () => { const { ProtocolVersion } = await import('@midnightntwrk/wallet-sdk'); const { LEDGER_9_FORK_VERSION } = await import('../lib/network.ts'); - const { FORK_SCHEDULE } = await import('../lib/fork-schedule.ts'); + const { FORK_SCHEDULE } = await import('../engine/rc/fork-schedule.ts'); expect(LEDGER_9_FORK_VERSION).toBe(ProtocolVersion.V9NativeForkVersion); expect(FORK_SCHEDULE.v9).toBe(LEDGER_9_FORK_VERSION); }); diff --git a/src/__tests__/read-cancellation.test.ts b/src/__tests__/read-cancellation.test.ts index 617be8a0..8f0f66f0 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/src/__tests__/read-cancellation.test.ts @@ -17,7 +17,7 @@ import { waitForFirstBlock } from '../lib/node-ready.ts'; import { waitForAddressFunded } from '../lib/indexer-ready.ts'; import { waitForProofServerReady } from '../lib/proof-server-ready.ts'; import { sleep } from '../lib/sleep.ts'; -import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; +import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; import { getNetworkConfig, type NetworkConfig } from '../lib/network.ts'; import type { BalanceSummary } from '../lib/balance-subscription.ts'; diff --git a/src/__tests__/sign-recipe.test.ts b/src/__tests__/sign-recipe.test.ts index 6f692463..97c1b514 100644 --- a/src/__tests__/sign-recipe.test.ts +++ b/src/__tests__/sign-recipe.test.ts @@ -23,7 +23,7 @@ import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/fa import { feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; import { PartlySignedTransactionError, SignedTransactionNeedsUnshieldedError, assertSignable, signRecipe, unshieldedImbalanceSegments, unshieldedSignatures, -} from '../lib/sign-recipe.ts'; +} from '../engine/rc/sign-recipe.ts'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, spend, unsealedBytes, diff --git a/src/__tests__/transfer-lib.test.ts b/src/__tests__/transfer-lib.test.ts index c95b62b2..f67e1591 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/src/__tests__/transfer-lib.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { validateRecipientAddress, isDustRelatedError } from '../lib/transfer.ts'; +import { validateRecipientAddress, isDustRelatedError } from '../engine/rc/transfer.ts'; import { nightToMicro, parseAmount } from '../lib/amount.ts'; import { getNetworkConfig } from '../lib/network.ts'; import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 3f0d7a7a..03f74f07 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -13,7 +13,7 @@ import { callDiagnostics } from '../lib/call-context.ts'; import { parseArgs } from '../lib/argv.ts'; import { setNoticeSink } from '../lib/notices.ts'; import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; -import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; +import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; import type { NetworkConfig } from '../lib/network.ts'; import balanceCommand from '../commands/balance.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index 3d62c3ad..af834a81 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -10,7 +10,7 @@ import { join } from 'node:path'; import { Buffer } from 'node:buffer'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '../lib/wallet-data-repository.ts'; +import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '../engine/rc/wallet-data-repository.ts'; import { UnsupportedLedgerError } from '../lib/ledger-guard.ts'; import type { NetworkConfig } from '../lib/network.ts'; import type { BalanceSummary } from '../lib/balance-subscription.ts'; diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index 54f3da67..7c3bf64e 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -11,7 +11,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { WalletDataRepository } from '../lib/wallet-data-repository.ts'; +import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; import { dustPublicKeyHexFromSeed, saveDustCache } from '../engine/rc/dust-direct-cache.ts'; import type { NetworkConfig } from '../lib/network.ts'; import { parseArgs } from '../lib/argv.ts'; diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 1a240d3b..afc341d5 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -9,23 +9,16 @@ // file required, useful for funding externally-generated addresses. // A shielded address implies --shielded; the flag is optional there. -import * as ledger from '@midnightntwrk/ledger-v9'; import { throwIfCancelled } from '../lib/errors.ts'; -import { MidnightBech32m, ShieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; import { loadWalletConfig, resolveWalletPath, saveShieldedAddress } from '../lib/wallet-config.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '../lib/network.ts'; -import { getNetworkId } from '../lib/network-id.ts'; import { GENESIS_SEED } from '../lib/constants.ts'; -import { deriveShieldedAddress } from '../engine/rc/derive-address.ts'; -import { ensureDust } from '../lib/transfer.ts'; +import { engineFor } from '../lib/engine.ts'; import { parseAmount, nightToMicro } from '../lib/amount.ts'; -import { airdropNight } from '../lib/airdrop.ts'; -import { defaultRepository } from '../lib/wallet-data-repository.ts'; import { header, keyValue, divider, formatAddress, successMessage } from '../ui/format.ts'; import { bold, dim } from '../ui/colors.ts'; -import { trackElapsed } from '../ui/spinner.ts'; import type { CallContext } from '../lib/call-context.ts'; export default async function airdropCommand(args: ParsedArgs, ctx: CallContext): Promise { @@ -84,8 +77,8 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) type UnshieldedDestination = { kind: 'address'; address: string }; type ShieldedDestination = - | { kind: 'address'; raw: ShieldedAddress; bech32m: string } - | { kind: 'wallet'; raw: ShieldedAddress; bech32m: string; walletPath: string }; + | { kind: 'address'; bech32m: string } + | { kind: 'wallet'; bech32m: string; walletPath: string }; function looksLikeBech32mAddress(value: string): boolean { return value.startsWith('mn_addr_') || value.startsWith('mn_shield-addr_'); @@ -100,7 +93,7 @@ async function resolveDestination( const walletFlag = getFlag(args, 'wallet'); if (walletFlag !== undefined && looksLikeBech32mAddress(walletFlag)) { - return resolveAddressDestination(walletFlag, networkName, networkConfig, isShielded); + return resolveAddressDestination(walletFlag, networkName, isShielded); } // Fall back to wallet file (name, path, or active wallet) @@ -109,21 +102,20 @@ async function resolveDestination( if (isShielded) { // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase. - const stored = config.shieldedAddresses?.[networkName as NetworkName]; + const stored = config.shieldedAddresses?.[networkName]; if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${networkName}.`); - const decoded = resolveAddressDestination(stored, networkName, networkConfig, true) as ShieldedDestination; - return { kind: 'wallet', raw: decoded.raw, bech32m: decoded.bech32m, walletPath }; + const decoded = await resolveAddressDestination(stored, networkName, true) as ShieldedDestination; + return { kind: 'wallet', bech32m: decoded.bech32m, walletPath }; } return { kind: 'address', address: config.addresses[networkName] }; } -function resolveAddressDestination( +async function resolveAddressDestination( address: string, networkName: NetworkName, - networkConfig: NetworkConfig, isShielded: boolean, -): UnshieldedDestination | ShieldedDestination { +): Promise { const looksShielded = address.startsWith('mn_shield-addr_'); // The inverse mismatch (shielded address without --shielded) never @@ -149,14 +141,12 @@ function resolveAddressDestination( } if (isShielded) { - const networkId = getNetworkId(networkConfig.networkId); - let raw: ShieldedAddress; try { - raw = MidnightBech32m.parse(address).decode(ShieldedAddress, networkId); + (await engineFor(networkName)).keys.assertAddress(address, 'shielded', networkName); } catch (err: any) { throw new Error(`Invalid shielded address: ${err.message}`); } - return { kind: 'address', raw, bech32m: address }; + return { kind: 'address', bech32m: address }; } return { kind: 'address', address }; @@ -168,7 +158,7 @@ async function unshieldedAirdrop( args: ParsedArgs, destination: UnshieldedDestination, amountNight: number, - networkName: string, + networkName: NetworkName, networkConfig: NetworkConfig, ctx: CallContext, ): Promise { @@ -184,7 +174,7 @@ async function unshieldedAirdrop( const spinner = ctx.progress.start('Starting genesis wallet...'); try { - const result = await airdropNight({ + const result = await (await engineFor(networkName)).wallet.airdrop({ networkConfig, recipientAddress, amountNight, @@ -252,22 +242,20 @@ async function shieldedAirdrop( args: ParsedArgs, destination: ShieldedDestination, amountNight: number, - networkName: string, + networkName: NetworkName, networkConfig: NetworkConfig, ctx: CallContext, ): Promise { const amount = nightToMicro(amountNight); const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); - const nightToken = ledger.unshieldedToken().raw; - const userShieldedAddress = destination.raw; const userShieldedAddrStr = destination.bech32m; // Cache the shielded address into the wallet file so subsequent reads // can short-circuit. Only meaningful when the destination came from a // managed wallet — for a raw address there's nothing to cache. if (destination.kind === 'wallet') { - saveShieldedAddress(destination.walletPath, networkName as NetworkName, userShieldedAddrStr); + saveShieldedAddress(destination.walletPath, networkName, userShieldedAddrStr); } ctx.output.stderr('\n' + header('Shielded Airdrop') + '\n\n'); @@ -282,67 +270,27 @@ async function shieldedAirdrop( const spinner = ctx.progress.start('Syncing genesis wallet...'); try { - const txHash = await defaultRepository().withFacade( - genesisSeedBuffer, + const txHash = await (await engineFor(networkName)).wallet.shieldedTransfer({ + seed: genesisSeedBuffer, + network: networkName, networkConfig, - async ({ bundle, state }) => { - const genesisShieldedBalance = state.shielded.balances[nightToken] ?? 0n; - if (genesisShieldedBalance < amount) { - const available = Number(genesisShieldedBalance) / 1_000_000; - throw new Error( - `Genesis wallet has insufficient shielded balance: ${available.toFixed(6)} NIGHT available, ${amountNight} NIGHT requested` - ); + recipient: userShieldedAddrStr, + amount, + progress: spinner, + waitForDustToCover: false, + insufficient: (available) => + `Genesis wallet has insufficient shielded balance: ${available} NIGHT available, ${amountNight} NIGHT requested`, + log: ctx.diagnostics.line, + signal: ctx.signal, + onStatus: (s) => spinner.update(s), + onSyncProgress: (applied, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + spinner.update(pct >= 100 ? 'Syncing genesis wallet...' : `Syncing genesis wallet... ${pct}%`); } - - spinner.update('Checking dust...'); - await ensureDust(bundle, (status: string) => spinner.update(status)); - - throwIfCancelled(ctx.signal); - - spinner.update('Building shielded transaction...'); - const recipe = await bundle.facade.transferTransaction( - [{ - type: 'shielded' as const, - outputs: [{ type: nightToken, amount, receiverAddress: userShieldedAddress }], - }], - { ttl: new Date(Date.now() + 60 * 60 * 1000) }, - ); - - spinner.update('Signing...'); - const signed = await bundle.facade.signRecipe( - recipe, - bundle.keystore.signDataAsync, - ); - - spinner.update('Generating ZK proof (this may take a few minutes)...'); - const finalized = await bundle.facade.finalizeRecipe(signed); - - // SDK v4 facade.submitTransaction blocks until the chain finalizes - // the block (typically 12 to 30s on hosted networks, ~6 to 12s on - // localnet). trackElapsed updates the spinner once a second so - // users see the wait is alive, not stuck. - const txId = await trackElapsed( - spinner, - 'Submitting and waiting for finalization (typically 12 to 30s)...', - bundle.facade.submitTransaction(finalized), - ); - return String(txId); - }, - { - syncMode: 'full', - log: ctx.diagnostics.line, - requireStrictSync: true, - signal: ctx.signal, - onStatus: (s) => spinner.update(s), - onSyncProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing genesis wallet...' : `Syncing genesis wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => spinner.update(`Syncing genesis wallet... (waiting on: ${detail})`), }, - ); + onSyncDetail: (detail) => spinner.update(`Syncing genesis wallet... (waiting on: ${detail})`), + }); spinner.stop('Transaction submitted'); diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 50cdb7e6..90a19377 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -9,7 +9,6 @@ import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides } from '../lib/network.ts'; import { shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; import { isNativeToken } from '../lib/balance-subscription.ts'; -import { defaultRepository } from '../lib/wallet-data-repository.ts'; import { engineFor } from '../lib/engine.ts'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; import { getChainGenesisHash } from '../lib/chain-id.ts'; @@ -99,7 +98,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise const spinner = ctx.progress.start(`Checking balance on ${networkName}...`); try { - const result = await defaultRepository().unshielded(address, networkConfig, { + const result = await (await engineFor(networkName)).wallet.unshieldedBalance(address, networkConfig, { forceFresh: hasFlag(args, 'no-cache'), signal: ctx.signal, log: ctx.diagnostics.line, @@ -213,7 +212,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise // ── Phase 1: fast unshielded via GraphQL (no facade, no proof server) ── if (!isJson) activeSpinner = ctx.progress.start('Checking unshielded...'); ctx.diagnostics.line('balance', `phase=unshielded forceFresh=${noCache}`); - const unshieldedResult = await defaultRepository().unshielded(address, networkConfig, { + const unshieldedResult = await (await engineFor(networkName)).wallet.unshieldedBalance(address, networkConfig, { forceFresh: noCache, signal: ctx.signal, log: ctx.diagnostics.line, diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 85c45295..473dcd82 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -7,11 +7,9 @@ import { UsageError, throwIfCancelled } from '../lib/errors.ts'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; -import { applyEndpointOverrides, type NetworkConfig } from '../lib/network.ts'; -import { registerDust } from '../lib/dust-register.ts'; +import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '../lib/network.ts'; import { checkBalance } from '../lib/balance-subscription.ts'; -import { exportDustSnapshot } from '../lib/dust-export.ts'; -import { defaultRepository } from '../lib/wallet-data-repository.ts'; +import { engineFor } from '../lib/engine.ts'; import { header, keyValue, divider, formatDust, successMessage, toDust } from '../ui/format.ts'; import { bold, dim, yellow } from '../ui/colors.ts'; @@ -77,7 +75,7 @@ export default async function dustCommand(args: ParsedArgs, ctx: CallContext): P // Registered → read balance directly from indexer (bypasses the dust-wallet // SDK's `isConnected` hang). No facade needed for a read-only query. const useCache = !hasFlag(args, 'no-cache'); - await dustStatusDirect(seedBuffer, networkConfig, preCheck, isJson, minimal, useCache, ctx); + await dustStatusDirect(seedBuffer, networkName, networkConfig, preCheck, isJson, minimal, useCache, ctx); return; } @@ -85,14 +83,14 @@ export default async function dustCommand(args: ParsedArgs, ctx: CallContext): P // The repo's withFacade owns: validate caches, pre-prime dust, build facade, // sync (with retry), save, invalidate, stop. We just provide the work. rejectNoCacheForWrites(args); - await dustRegister(seedBuffer, networkConfig, isJson, ctx); + await dustRegister(seedBuffer, networkName, networkConfig, isJson, ctx); } // export: fast dust-direct sync → emit a facade-restorable snapshot. The snapshot // (the pipeable data) goes to stdout; a summary goes to stderr; --json bundles it all. async function dustExport( seedBuffer: Buffer, - networkName: string, + networkName: NetworkName, networkConfig: NetworkConfig, jsonMode: boolean, minimal: boolean, @@ -100,7 +98,7 @@ async function dustExport( ): Promise { const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); try { - const result = await exportDustSnapshot(seedBuffer, networkName, networkConfig, { + const result = await (await engineFor(networkName)).wallet.exportDust(seedBuffer, networkName, networkConfig, { signal: ctx.signal, log: ctx.diagnostics.line, onProgress: (applied, maxIdSeen) => spinner.update( @@ -246,6 +244,7 @@ function printUnregisteredStatus( async function dustRegister( seedBuffer: Buffer, + network: NetworkName, networkConfig: NetworkConfig, jsonMode: boolean, ctx: CallContext, @@ -257,7 +256,7 @@ async function dustRegister( const spinner = ctx.progress.start('Syncing wallet...'); try { - const result = await registerDust(seedBuffer, networkConfig, { + const result = await (await engineFor(network)).wallet.registerDust(seedBuffer, networkConfig, { signal: ctx.signal, sdkWarnings: ctx.sdkWarnings, log: ctx.diagnostics.line, @@ -299,6 +298,7 @@ async function dustRegister( // invalidation, and force-fresh — see lib/wallet-data-repository.ts. async function dustStatusDirect( seedBuffer: Buffer, + network: NetworkName, networkConfig: NetworkConfig, preCheck: PreCheckResult, jsonMode: boolean, @@ -310,7 +310,7 @@ async function dustStatusDirect( const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); try { - const view = await defaultRepository().dust(seedBuffer, networkConfig, { + const view = await (await engineFor(network)).wallet.dustBalance(seedBuffer, networkConfig, { forceFresh: !useCache, signal: ctx.signal, log: ctx.diagnostics.line, diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 943695cc..410afe73 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -6,10 +6,8 @@ import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../li import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides } from '../lib/network.ts'; -import { hasDustAvailable, isFacadeSynced, waitForDustAvailable } from '../lib/facade.ts'; -import { saveWalletCache } from '../lib/wallet-cache.ts'; -import { defaultRepository } from '../lib/wallet-data-repository.ts'; -import { createDAppConnector, OPERATOR_REJECTED_MESSAGE, type DAppConnectorCallbacks } from '../lib/dapp-connector.ts'; +import { engineFor, type DAppConnector, type DAppConnectorCallbacks } from '../lib/engine.ts'; +import { OPERATOR_REJECTED_MESSAGE } from '../lib/connector-api.ts'; import type { PhaseTiming } from '../lib/phase-tracker.ts'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; import { DEFAULT_SERVE_PORT } from '../lib/constants.ts'; @@ -91,34 +89,42 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): else { ctx.output.stderr(dim(` SDK: ${msg}`) + '\n'); } }); - // ── Build & sync facade via repo.withFacade ── - // The repo owns: validateNetworkCaches → primeDustCache → buildFacade → - // sync (with retry) → stopFacade. We pass `skipAutoSave: true` because - // serve has nuanced save logic (skip on pending txs to avoid persisting - // dust=0 corruption — see `connector.hasPendingTxs()` check below). + // ── Sync the wallet, through the engine for the network ── + // The engine owns validating the caches, priming Dust, building the + // wallet, syncing (with retries) and stopping it. Saving is ours: skipped + // while transactions are pending, to avoid persisting dust=0 (see the + // `connector.hasPendingTxs()` check below). const spinner = ctx.progress.start('Syncing wallet...'); // Skip the (slow) shielded sync where shielded is unusable (no faucet on // preview/preprod). dApps there can only do unshielded + dust anyway. const syncMode = shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded')) ? 'full' : 'lite'; - await defaultRepository().withFacade(seedBuffer, networkConfig, async ({ bundle }) => { + await (await engineFor(networkName)).wallet.serveWallet({ seed: seedBuffer, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, + onStatus: (s) => spinner.update(s), + onSyncProgress: (applied, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); + } + }, + onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), + }, async (served) => { spinner.stop('Wallet synced'); // Wait for dust coins to actually be available before accepting write requests. // On preprod this can take 10-30s after sync completes. const dustSpinner = ctx.progress.start('Waiting for dust...'); - const dustState = await waitForDustAvailable(bundle); - const hasDust = hasDustAvailable(dustState); + const hasDust = await served.waitForDust(); dustSpinner.stop(hasDust ? 'Dust ready' : 'Dust not yet available (writes may fail)'); // Save cache after successful sync (checkpoint before opening RPC). - try { await saveWalletCache(address, networkName, bundle.facade); } catch { /* best-effort */ } + await served.saveState(); throwIfCancelled(ctx.signal); let server: RpcServer | undefined; - let connector: ReturnType | undefined; + let connector: DAppConnector | undefined; try { // ── Create DApp Connector ── @@ -156,16 +162,12 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): }, }; - connector = createDAppConnector({ - bundle, - networkConfig, + // Reads answer from the state the Dust wait ended on, and from every + // later one that is synced by the rule the sync used. + connector = served.connect({ approvalOptions: { approveAll, approveFees, autoApproveReads }, feeLimits, callbacks: phaseCallbacks, - // Reads answer from the state this sync ended on, and from every later - // one that is synced by the rule the sync used. - initialState: dustState, - isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), }); // ── Start WebSocket server ── @@ -266,7 +268,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // The SDK drops pendingDustTokens on serialization, so saving while coins // are locked in pending would persist a corrupted state (dust=0). if (!connector.hasPendingTxs()) { - try { await saveWalletCache(address, networkName, bundle.facade); } catch { /* best-effort */ } + await served.saveState(); } try { await server.close(); } catch { /* best-effort */ } connector.dispose(); @@ -279,22 +281,6 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): connector?.dispose(); throw err; } - }, { - syncMode, - // serve accepts write requests from dApps — must be strictly synced. - requireStrictSync: true, - // Save logic is conditional (skip if pending txs) — done manually above. - skipAutoSave: true, - signal: ctx.signal, - log: ctx.diagnostics.line, - onStatus: (s) => spinner.update(s), - onSyncProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), }).finally(() => { stopListening(); }); diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index ef6546d2..9b66fd9a 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -1,24 +1,17 @@ // transfer command — send NIGHT from my wallet to another address // Usage: midnight transfer [--shielded] -import * as ledger from '@midnightntwrk/ledger-v9'; import { throwIfCancelled } from '../lib/errors.ts'; -import { MidnightBech32m } from '@midnightntwrk/wallet-sdk/address-format'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; import { saveShieldedAddress, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetwork } from '../lib/resolve-network.ts'; import { applyEndpointOverrides } from '../lib/network.ts'; -import { getNetworkId } from '../lib/network-id.ts'; import { resolveTransferRequest, type TransferRequest } from '../lib/transfer-request.ts'; -import { decodeShieldedAddress } from '../engine/rc/addresses.ts'; -import { executeTransfer, ensureDust } from '../lib/transfer.ts'; +import { engineFor } from '../lib/engine.ts'; import { nightToMicro } from '../lib/amount.ts'; -import { defaultRepository } from '../lib/wallet-data-repository.ts'; import { header, keyValue, divider, formatAddress, successMessage } from '../ui/format.ts'; import { bold, dim } from '../ui/colors.ts'; -import { trackElapsed } from '../ui/spinner.ts'; import type { CallContext } from '../lib/call-context.ts'; -import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '../lib/dust-wait.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); @@ -54,7 +47,7 @@ async function unshieldedTransfer( const spinner = ctx.progress.start('Starting wallet...'); try { - const result = await executeTransfer({ + const result = await (await engineFor(networkName)).wallet.transfer({ seedBuffer, networkConfig, recipientAddress, @@ -128,8 +121,6 @@ async function shieldedTransfer( const seedBuffer = Buffer.from((await unlockWallet(walletPath)).seed, 'hex'); const { name: networkName, config: networkConfig } = resolveNetwork({ args }); - const networkId = getNetworkId(networkConfig.networkId); - const nightToken = ledger.unshieldedToken().raw; applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), @@ -137,8 +128,6 @@ async function shieldedTransfer( indexerWS: getFlag(args, 'indexer-ws'), }, networkName); - const decodedRecipient = decodeShieldedAddress(recipientAddress, networkName); - ctx.output.stderr('\n' + header('Shielded Transfer') + '\n\n'); ctx.output.stderr(keyValue('Network', networkName) + '\n'); ctx.output.stderr(keyValue('To', formatAddress(recipientAddress, true)) + '\n'); @@ -151,74 +140,32 @@ async function shieldedTransfer( const spinner = ctx.progress.start('Syncing wallet...'); try { - const txHash = await defaultRepository().withFacade( - seedBuffer, + const txHash = await (await engineFor(networkName)).wallet.shieldedTransfer({ + seed: seedBuffer, + network: networkName, networkConfig, - async ({ bundle, state }) => { - // Cache shielded address in wallet file - const senderShieldedAddr = MidnightBech32m.encode(networkId, state.shielded.address).asString(); - saveShieldedAddress(walletPath, networkName, senderShieldedAddr); - - const shieldedBalance = state.shielded.balances[nightToken] ?? 0n; - if (shieldedBalance < amount) { - const available = Number(shieldedBalance) / 1_000_000; - throw new Error( - `Insufficient shielded balance: ${available.toFixed(6)} NIGHT available, ${amountNight} NIGHT requested.\n` + - `Fund shielded balance: midnight airdrop ${amountNight} --shielded` - ); + recipient: recipientAddress, + amount, + progress: spinner, + // Right after another payment the wallet's Dust can be short of this + // fee: wait when the rest is moments away, else say how long it takes. + waitForDustToCover: true, + // Cache shielded address in wallet file + onSenderShieldedAddress: (address) => saveShieldedAddress(walletPath, networkName, address), + insufficient: (available) => + `Insufficient shielded balance: ${available} NIGHT available, ${amountNight} NIGHT requested.\n` + + `Fund shielded balance: midnight airdrop ${amountNight} --shielded`, + log: ctx.diagnostics.line, + signal: ctx.signal, + onStatus: (s) => spinner.update(s), + onSyncProgress: (applied, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); } - - spinner.update('Checking dust...'); - await ensureDust(bundle, (status: string) => spinner.update(status)); - - throwIfCancelled(ctx.signal); - - spinner.update('Building shielded transaction...'); - // Right after another payment the wallet's Dust can be short of this - // fee: wait when the rest is moments away, else say how long it takes. - const recipe = await payWhenDustCovers( - () => bundle.facade.transferTransaction( - [{ - type: 'shielded' as const, - outputs: [{ type: nightToken, amount, receiverAddress: decodedRecipient }], - }], - { ttl: new Date(Date.now() + 60 * 60 * 1000) }, - ), - state.dust, - { maxWaitMs: DUST_SHORT_WAIT_MS, onStatus: (status) => spinner.update(status), signal: ctx.signal }, - ); - - spinner.update('Signing...'); - const signed = await bundle.facade.signRecipe( - recipe, - bundle.keystore.signDataAsync, - ); - - spinner.update('Generating ZK proof (this may take a few minutes)...'); - const finalized = await bundle.facade.finalizeRecipe(signed); - - const txId = await trackElapsed( - spinner, - 'Submitting and waiting for finalization (typically 12 to 30s)...', - bundle.facade.submitTransaction(finalized), - ); - return String(txId); - }, - { - syncMode: 'full', - log: ctx.diagnostics.line, - requireStrictSync: true, - signal: ctx.signal, - onStatus: (s) => spinner.update(s), - onSyncProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), }, - ); + onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), + }); spinner.stop('Transaction submitted'); diff --git a/src/lib/airdrop.ts b/src/engine/rc/airdrop.ts similarity index 83% rename from src/lib/airdrop.ts rename to src/engine/rc/airdrop.ts index a8c066ae..51fc24cf 100644 --- a/src/lib/airdrop.ts +++ b/src/engine/rc/airdrop.ts @@ -2,10 +2,11 @@ // devnet. `mn airdrop` and `mn dev` both fund wallets through here; the // caller has already checked that the network is the local one. -import { GENESIS_SEED } from './constants.ts'; +import { GENESIS_SEED } from '../../lib/constants.ts'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; +import type { AirdropParams } from '../../lib/engine.ts'; +export type { AirdropParams } from '../../lib/engine.ts'; -export type AirdropParams = Omit; /** Sends `amountNight` NIGHT from genesis to `recipientAddress`. */ export async function airdropNight(params: AirdropParams): Promise { diff --git a/src/lib/dapp-connector.ts b/src/engine/rc/dapp-connector.ts similarity index 96% rename from src/lib/dapp-connector.ts rename to src/engine/rc/dapp-connector.ts index 7e1b5448..1c5250a2 100644 --- a/src/lib/dapp-connector.ts +++ b/src/engine/rc/dapp-connector.ts @@ -2,40 +2,38 @@ // Factory function returns a handler map for ws-rpc.ts to dispatch import * as rx from 'rxjs'; -import { notice } from './notices.ts'; +import { notice } from '../../lib/notices.ts'; import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { TransactionStage, WalletTransaction } from '@midnightntwrk/wallet-sdk'; import type { FacadeState, WalletEntry } from '@midnightntwrk/wallet-sdk/facade'; import type { FinalizedTx } from '@midnightntwrk/wallet-sdk'; import { type FacadeBundle, hasDustAvailable } from './facade.ts'; -import { LEDGER_9_FORK_VERSION, type NetworkConfig } from './network.ts'; -import type { ApprovalOptions } from './approval.ts'; -import { promptApproval } from './approval.ts'; -import { createApiError, type RpcHandler, type RpcHandlerContext } from './connector-api.ts'; -import { createPhaseTracker, type PhaseTracker } from './phase-tracker.ts'; -import { toHex, fromHex } from './tx-serde.ts'; -import { getNetworkId } from './network-id.ts'; -import { isDustShortage } from './sdk-errors.ts'; -import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from './fee-limits.ts'; -import { inspectTxHex } from '../engine/rc/tx-inspect.ts'; -import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from '../engine/rc/fee-only-check.ts'; +import { LEDGER_9_FORK_VERSION, type NetworkConfig } from '../../lib/network.ts'; +import type { ApprovalOptions } from '../../lib/approval.ts'; +import { promptApproval } from '../../lib/approval.ts'; +import { createApiError, type RpcHandler, type RpcHandlerContext } from '../../lib/connector-api.ts'; +import { createPhaseTracker, type PhaseTracker } from '../../lib/phase-tracker.ts'; +import { toHex, fromHex } from '../../lib/tx-serde.ts'; +import { getNetworkId } from '../../lib/network-id.ts'; +import { isDustShortage } from '../../lib/sdk-errors.ts'; +import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '../../lib/fee-limits.ts'; +import { inspectTxHex } from './tx-inspect.ts'; +import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; -import { decodeSignPayload, signedMessageBytes } from './sign-data.ts'; -import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from './dust-wait.ts'; -import { formatWait } from './duration.ts'; -import { fetchPartialSuccessSegments, type SegmentResult } from './tx-segments.ts'; -import { walletsBelowLedger9 } from './ledger-guard.ts'; -import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from './constants.ts'; -import { dim } from '../ui/colors.ts'; -import { roughDust, toDust } from '../ui/format.ts'; +import { decodeSignPayload, signedMessageBytes } from '../../lib/sign-data.ts'; +import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '../../lib/dust-wait.ts'; +import { formatWait } from '../../lib/duration.ts'; +import { fetchPartialSuccessSegments, type SegmentResult } from '../../lib/tx-segments.ts'; +import { walletsBelowLedger9 } from '../../lib/ledger-guard.ts'; +import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '../../lib/constants.ts'; +import { dim } from '../../ui/colors.ts'; +import { roughDust, toDust } from '../../ui/format.ts'; +import type { DAppConnector, DAppConnectorCallbacks } from '../../lib/engine.ts'; +export type { DAppConnector, DAppConnectorCallbacks } from '../../lib/engine.ts'; // ── Types ── -export interface DAppConnectorCallbacks { - onPhaseStart?: (connectionId: string, method: string, phase: string) => void; - onPhaseComplete?: (connectionId: string, method: string, phase: string, durationMs: number) => void; -} export interface DAppConnectorOptions { bundle: FacadeBundle; @@ -69,14 +67,6 @@ export interface DAppConnectorOptions { /** Which token kinds the facade balances a dApp's transaction in. */ export type TokenKindsToBalance = 'all' | Array<'dust' | 'shielded' | 'unshielded'>; -export interface DAppConnector { - handlers: Record; - /** Revert all pending (unsubmitted) transactions for a connection, releasing locked coins. */ - revertPendingTxs(connectionId: string): Promise; - /** True if any connection has a balanced-but-not-submitted transaction. */ - hasPendingTxs(): boolean; - dispose(): void; -} // ── Factory ── @@ -149,8 +139,8 @@ function extractErrorDetail(err: unknown): string { return deduped.join(' → ') || 'Unknown error'; } -/** The error message when the operator declines an approval prompt. */ -export const OPERATOR_REJECTED_MESSAGE = 'User rejected the request'; +export { OPERATOR_REJECTED_MESSAGE } from '../../lib/connector-api.ts'; +import { OPERATOR_REJECTED_MESSAGE } from '../../lib/connector-api.ts'; /** The connector API's history entry for one wallet history entry. */ export type HistoryEntry = { diff --git a/src/lib/dust-export.ts b/src/engine/rc/dust-export.ts similarity index 77% rename from src/lib/dust-export.ts rename to src/engine/rc/dust-export.ts index 25878b85..348a96fa 100644 --- a/src/lib/dust-export.ts +++ b/src/engine/rc/dust-export.ts @@ -17,34 +17,14 @@ // // Pure logic: returns values, never writes to stdout/stderr or exits. -import { anyEngine } from './engine.ts'; +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; -import { type NetworkConfig } from './network.ts'; +import { type NetworkConfig } from '../../lib/network.ts'; import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from './verbose.ts'; +import type { VerboseLog } from '../../lib/verbose.ts'; +import type { DustExportResult } from '../../lib/engine.ts'; +export type { DustExportResult } from '../../lib/engine.ts'; -export interface DustExportResult { - network: string; - /** Dust public key (hex) this snapshot belongs to — derived from the seed. */ - dustPublicKey: string; - /** Last dust event id the snapshot covers; -1 if the wallet has no dust events yet. */ - offset: number; - /** Dust balance encoded in the snapshot, at export time. */ - balance: bigint; - /** Dust events applied during this export's sync (delta since any prior cache). */ - eventCount: number; - /** True if an existing dust-direct cache was extended; false if synced from scratch. */ - fromCache: boolean; - /** - * True iff the sync stopped short of the chain tip. The snapshot is still a - * valid checkpoint — restoring it is strictly better than starting cold — but - * it is NOT current, and a wallet restored from it still has events to catch - * up on. Consumers must not treat a partial export as a warm wallet. - */ - partial: boolean; - /** The facade-restorable dust snapshot — pass as `dustSerializedState`. */ - snapshot: string; -} export interface DustExportOptions { onProgress?: (eventsApplied: number, maxIdSeen: number) => void; @@ -91,7 +71,7 @@ export async function exportDustSnapshot( networkConfig: NetworkConfig, options: DustExportOptions = {}, ): Promise { - const pubkeyHex = (await anyEngine()).keys.dustPublicKeyHex(seedBuffer); + const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); const repo = options.repository ?? defaultRepository(); const view = await repo.dust(seedBuffer, networkConfig, { diff --git a/src/lib/dust-register.ts b/src/engine/rc/dust-register.ts similarity index 61% rename from src/lib/dust-register.ts rename to src/engine/rc/dust-register.ts index 65e65d72..3ea34ed1 100644 --- a/src/lib/dust-register.ts +++ b/src/engine/rc/dust-register.ts @@ -2,36 +2,16 @@ // Dust to spend. `mn dust register` and `mn dev` both register through here. import { waitForLiteSyncedState } from './facade.ts'; -import { throwIfCancelled } from './errors.ts'; +import { throwIfCancelled } from '../../lib/errors.ts'; import { ensureDust } from './transfer.ts'; import { defaultRepository } from './wallet-data-repository.ts'; -import type { NetworkConfig } from './network.ts'; -import type { CallSdkWarnings } from './sdk-warnings.ts'; -import type { VerboseLog } from './verbose.ts'; +import type { NetworkConfig } from '../../lib/network.ts'; +import type { CallSdkWarnings } from '../../lib/sdk-warnings.ts'; +import type { VerboseLog } from '../../lib/verbose.ts'; +import type { DustRegisterOptions, DustRegistration } from '../../lib/engine.ts'; +export type { DustRegisterOptions, DustRegistration } from '../../lib/engine.ts'; -export interface DustRegisterOptions { - signal?: AbortSignal; - /** What the registration is doing now, for a progress line. */ - onStatus?: (status: string) => void; - /** Wallet sync progress, as blocks applied of the highest seen. */ - onSyncProgress?: (applied: number, highest: number) => void; - /** Which wallets the sync still waits on. */ - onSyncDetail?: (detail: string) => void; - /** A transient SDK error the sync is retrying past. */ - onSyncWarning?: (tag: string, message: string) => void; - /** The call's SDK warnings, listened to for the whole registration. */ - sdkWarnings: CallSdkWarnings; - /** The call's verbose lines. */ - log?: VerboseLog; -} -export interface DustRegistration { - /** The wallet had Dust already; nothing was registered. */ - alreadyAvailable: boolean; - txHash?: string; - /** The Dust balance once synced, in its smallest unit. */ - dustBalance: bigint; -} export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log } = options; diff --git a/src/lib/dust-wallet.ts b/src/engine/rc/dust-wallet.ts similarity index 98% rename from src/lib/dust-wallet.ts rename to src/engine/rc/dust-wallet.ts index fc95816b..d0750d3b 100644 --- a/src/lib/dust-wallet.ts +++ b/src/engine/rc/dust-wallet.ts @@ -13,8 +13,8 @@ import { CustomForkingDustWallet, DustWallet as SdkDustWallet, asV8DustParameter import { V1Builder } from '@midnightntwrk/wallet-sdk/dust/v1'; import { Migration, Transacting, V2Builder, WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; import { LedgerOps } from '@midnightntwrk/wallet-sdk/utilities'; -import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from './dust-balancing-plan.ts'; -import { type DustShortfall, withDustShortfall } from './sdk-errors.ts'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '../../lib/dust-balancing-plan.ts'; +import { type DustShortfall, withDustShortfall } from '../../lib/sdk-errors.ts'; type SdkTransacting = Transacting.TransactingCapabilityImplementation; type RecipeArguments = Parameters; diff --git a/src/lib/facade.ts b/src/engine/rc/facade.ts similarity index 98% rename from src/lib/facade.ts rename to src/engine/rc/facade.ts index 9c59aef1..d8b078b0 100644 --- a/src/lib/facade.ts +++ b/src/engine/rc/facade.ts @@ -1,5 +1,5 @@ import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; -import { notice } from './notices.ts'; +import { notice } from '../../lib/notices.ts'; import { UnshieldedWallet, createKeystore, @@ -18,22 +18,22 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import * as rx from 'rxjs'; -import { type NetworkConfig } from './network.ts'; +import { type NetworkConfig } from '../../lib/network.ts'; import { FORK_SCHEDULE } from './fork-schedule.ts'; -import { getNetworkId } from './network-id.ts'; -import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from '../engine/rc/derivation.ts'; -import { type WalletCacheData } from './wallet-cache.ts'; -import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from '../engine/rc/dust-direct-cache.ts'; +import { getNetworkId } from '../../lib/network-id.ts'; +import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; +import { type WalletCacheData } from '../../lib/wallet-cache.ts'; +import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, SYNC_TIMEOUT_MS, PRE_SEND_SYNC_TIMEOUT_MS, -} from './constants.ts'; -import type { VerboseLog } from './verbose.ts'; -import { assertNetworkAnswers } from './endpoint-check.ts'; -import { isStreamEmpty } from './event-tip.ts'; -import { CancelledError, throwIfCancelled } from './errors.ts'; +} from '../../lib/constants.ts'; +import type { VerboseLog } from '../../lib/verbose.ts'; +import { assertNetworkAnswers } from '../../lib/endpoint-check.ts'; +import { isStreamEmpty } from '../../lib/event-tip.ts'; +import { CancelledError, throwIfCancelled } from '../../lib/errors.ts'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust diff --git a/src/lib/fork-schedule.ts b/src/engine/rc/fork-schedule.ts similarity index 100% rename from src/lib/fork-schedule.ts rename to src/engine/rc/fork-schedule.ts diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index 03013fcd..a8703e9e 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -7,6 +7,7 @@ import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { blockLimitsOf } from './ledger-parameters.ts'; import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; +import { rcWallet } from './wallet.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; @@ -48,4 +49,5 @@ export const rcEngine: Engine = { readers: { shieldedBalance: readShieldedBalanceCached, }, + wallet: rcWallet, }; diff --git a/src/lib/sign-recipe.ts b/src/engine/rc/sign-recipe.ts similarity index 98% rename from src/lib/sign-recipe.ts rename to src/engine/rc/sign-recipe.ts index 6d3b174d..65d88789 100644 --- a/src/lib/sign-recipe.ts +++ b/src/engine/rc/sign-recipe.ts @@ -20,7 +20,7 @@ import type { Signature } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { readDAppTransaction, segmentsOf, unshieldedInputs, type FeeCheckTransaction } from '../engine/rc/fee-only-check.ts'; +import { readDAppTransaction, segmentsOf, unshieldedInputs, type FeeCheckTransaction } from './fee-only-check.ts'; export type SignSegment = (data: Uint8Array) => Promise; diff --git a/src/lib/transfer.ts b/src/engine/rc/transfer.ts similarity index 92% rename from src/lib/transfer.ts rename to src/engine/rc/transfer.ts index 3c67b1e1..8e80ea51 100644 --- a/src/lib/transfer.ts +++ b/src/engine/rc/transfer.ts @@ -2,17 +2,17 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { throwIfCancelled } from './errors.ts'; +import { throwIfCancelled } from '../../lib/errors.ts'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; import * as rx from 'rxjs'; -import { type NetworkConfig } from './network.ts'; -import { getNetworkId } from './network-id.ts'; +import { type NetworkConfig } from '../../lib/network.ts'; +import { getNetworkId } from '../../lib/network-id.ts'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; import { defaultRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from './verbose.ts'; -import { nightToMicro } from './amount.ts'; +import type { VerboseLog } from '../../lib/verbose.ts'; +import { nightToMicro } from '../../lib/amount.ts'; import { NATIVE_TOKEN_TYPE, TOKEN_MULTIPLIER, @@ -26,40 +26,10 @@ import { SYNC_ATTEMPT_TIMEOUT_MS, DUST_COST_OVERHEAD, MIN_DUST_FOR_TRANSFER, -} from './constants.ts'; - -export interface TransferParams { - seedBuffer: Buffer; - networkConfig: NetworkConfig; - recipientAddress: string; - amountNight: number; - signal?: AbortSignal; - onSync?: (applied: number, highest: number) => void; - onSyncDetail?: (walletsStillSyncing: string) => void; - onDust?: (status: string) => void; - onProving?: () => void; - onSubmitting?: () => void; - /** Fires every second while waiting for chain finalization. `elapsedMs` - * is the time since the submit started. Use to drive an elapsed-time - * display so users see the wait is alive. - */ - onSubmittingTick?: (elapsedMs: number) => void; - onSyncWarning?: (tag: string, message: string) => void; - /** The call's SDK warnings, listened to for the whole transfer. */ - sdkWarnings: CallSdkWarnings; - /** The call's verbose lines. */ - log?: VerboseLog; -} +} from '../../lib/constants.ts'; + -export interface TransferResult { - txHash: string; - amountMicroNight: bigint; -} -export interface EnsureDustResult { - alreadyAvailable: boolean; - txHash?: string; -} /** * Validate recipient address format (bech32m, matching network). @@ -83,17 +53,19 @@ export function validateRecipientAddress(address: string, networkConfig: Network // SDK error classifiers moved to ./sdk-errors.ts so wallet-data-repository // can import them without a circular dependency. Re-exported for callers // that still import from this module. -export { isDustRelatedError, isSdkInsufficientFundsError } from './sdk-errors.ts'; -import { isColdStartRace, isDustRelatedError } from './sdk-errors.ts'; -import { DustFeeNotGeneratedError, planRegistration } from './dust-registration-plan.ts'; -import { formatWait } from './duration.ts'; -import { assertChainClockCurrent, fetchChainTime } from './chain-clock.ts'; -import { awaitDustForFee, sleep } from './dust-wait.ts'; +export { isDustRelatedError, isSdkInsufficientFundsError } from '../../lib/sdk-errors.ts'; +import { isColdStartRace, isDustRelatedError } from '../../lib/sdk-errors.ts'; +import { DustFeeNotGeneratedError, planRegistration } from '../../lib/dust-registration-plan.ts'; +import { formatWait } from '../../lib/duration.ts'; +import { assertChainClockCurrent, fetchChainTime } from '../../lib/chain-clock.ts'; +import { awaitDustForFee, sleep } from '../../lib/dust-wait.ts'; /** How long the transfer retry waits for Dust to grow when the fee is above the pre-flight threshold. */ const DUST_GROW_WAIT_MS = 10_000; -import { toDust } from '../ui/format.ts'; -import type { CallSdkWarnings } from './sdk-warnings.ts'; +import { toDust } from '../../ui/format.ts'; +import type { CallSdkWarnings } from '../../lib/sdk-warnings.ts'; +import type { EnsureDustResult, TransferParams, TransferResult } from '../../lib/engine.ts'; +export type { EnsureDustResult, TransferParams, TransferResult } from '../../lib/engine.ts'; /** Format milliseconds as "Xs" or "Xm Ys" for human-friendly elapsed display. */ diff --git a/src/lib/wallet-data-repository.ts b/src/engine/rc/wallet-data-repository.ts similarity index 91% rename from src/lib/wallet-data-repository.ts rename to src/engine/rc/wallet-data-repository.ts index a884bee3..b7faec63 100644 --- a/src/lib/wallet-data-repository.ts +++ b/src/engine/rc/wallet-data-repository.ts @@ -18,11 +18,11 @@ // tests against localnet — accepted scope per architecture-deepening.md. import { Buffer } from 'node:buffer'; -import { throwIfCancelled } from './errors.ts'; +import { throwIfCancelled } from '../../lib/errors.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; -import type { NetworkConfig, NetworkName } from './network.ts'; -import { isValidNetworkName } from './network.ts'; +import type { NetworkConfig, NetworkName } from '../../lib/network.ts'; +import { isValidNetworkName } from '../../lib/network.ts'; import { type FacadeState } from '@midnightntwrk/wallet-sdk/facade'; import { buildFacade, @@ -33,66 +33,36 @@ import { type SyncMode, overlayDustDirectSnapshot, } from './facade.ts'; -import { isColdStartRace } from './sdk-errors.ts'; -import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from '../engine/rc/dust-direct-cache.ts'; -import { clearDustDirectCache } from './reader-cache-files.ts'; +import { isColdStartRace } from '../../lib/sdk-errors.ts'; +import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from './dust-direct-cache.ts'; +import { clearDustDirectCache } from '../../lib/reader-cache-files.ts'; import { loadWalletCache, saveWalletCache, clearWalletCache, validateWalletCacheChainId, type WalletCacheData, -} from './wallet-cache.ts'; -import { getChainGenesisHash } from './chain-id.ts'; -import { assertLedgerSupported, fetchProtocolVersion } from './ledger-guard.ts'; -import { checkBalance, type BalanceSummary } from './balance-subscription.ts'; -import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from '../engine/rc/dust-direct.ts'; -import { bindCachesToIndexer, describeIndexerChange } from './cache-indexer.ts'; -import { nativeDustSyncAvailable, runDustSyncNative } from '../engine/rc/dust-sync-native.ts'; -import type { VerboseLog } from './verbose.ts'; -import { callNodeRpc } from './node-rpc.ts'; -import { deriveDustSeed } from '../engine/rc/derivation.ts'; -import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; -import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from './event-tip.ts'; +} from '../../lib/wallet-cache.ts'; +import { getChainGenesisHash } from '../../lib/chain-id.ts'; +import { assertLedgerSupported, fetchProtocolVersion } from '../../lib/ledger-guard.ts'; +import { checkBalance, type BalanceSummary } from '../../lib/balance-subscription.ts'; +import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; +import { bindCachesToIndexer, describeIndexerChange } from '../../lib/cache-indexer.ts'; +import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; +import type { VerboseLog } from '../../lib/verbose.ts'; +import { callNodeRpc } from '../../lib/node-rpc.ts'; +import { deriveDustSeed } from './derivation.ts'; +import { deriveUnshieldedAddress } from './derive-address.ts'; +import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '../../lib/event-tip.ts'; +import type { DustBalance, ReadOptions, UnshieldedView } from '../../lib/engine.ts'; +export type { DustBalance, ReadOptions, UnshieldedView } from '../../lib/engine.ts'; // ── Public types ────────────────────────────────────────── -export interface DustView { +export interface DustView extends DustBalance { state: ledger.DustLocalState; - balance: bigint; - availableCoins: number; - ownedUtxoCount: number; - syncTime: Date; - /** - * True iff any cache layer participated — either an in-memory memo hit, OR a - * disk-cache resume (delta sync from a previous checkpoint). False only for - * a true cold scan from event 0. - */ - fromCache: boolean; - /** Number of events applied by this call (0 on memo hits; delta count on disk-resume; full count on cold). */ - eventsApplied: number; - /** - * Id of the last dust event folded into `state`; -1 when the wallet has no - * dust events on this chain yet. This is the snapshot offset a restoring - * wallet resumes from, and it lives nowhere else in the view. - */ - lastAppliedEventId: number; - /** - * True iff the sync stopped short of the chain tip even after exhausting the - * partial-resume loop — the state is a valid checkpoint but NOT current. - * Callers that hand this state to another wallet (`dust export`) must surface - * it: restoring a short state looks like success and then silently falls back - * to the SDK's cold sync for the remaining events. - */ - partial: boolean; - /** Wall-clock millis when this value was last refreshed from the network. */ - fetchedAt: number; } -export interface UnshieldedView extends BalanceSummary { - fromCache: boolean; - fetchedAt: number; -} /** What the caller borrows during withFacade. SDK type leak is intentional. */ export interface FacadeLease { @@ -110,22 +80,6 @@ export interface InvalidationScope { kinds?: ReadonlyArray<'dust' | 'unshielded' | 'facade'>; } -export interface ReadOptions { - /** Bypass every cache layer and re-fetch from network. */ - forceFresh?: boolean; - signal?: AbortSignal; - /** Status hook for spinner wiring. */ - onStatus?: (s: string) => void; - /** - * Raw progress signal during the underlying network fetch. For dust this - * fires per-chunk (events applied vs max event id); for unshielded it - * fires per-UTXO-batch (current tx vs highest tx id). Callers that already - * have a spinner usually use this to render a percentage. - */ - onProgress?: (current: number, highest: number) => void; - /** The call's verbose lines. */ - log?: VerboseLog; -} export interface FacadeOptions extends ReadOptions { syncMode?: SyncMode; diff --git a/src/engine/rc/wallet.ts b/src/engine/rc/wallet.ts new file mode 100644 index 00000000..b76fc7be --- /dev/null +++ b/src/engine/rc/wallet.ts @@ -0,0 +1,299 @@ +// The rc engine's wallet, as the rest of mn uses it: each operation runs the +// SDK's wallet (the facade) or mn's readers and hands back mn's own types. +// The flows are the ones the commands, the test preparation and mn serve ran +// themselves before the SDK moved behind the engine. + +import * as ledger from '@midnightntwrk/ledger-v9'; +import { MidnightBech32m } from '@midnightntwrk/wallet-sdk/address-format'; +import type { + DAppConnector, + EngineWallet, + OpenedConnector, + PrepWallet, + ServedWalletSession, + ShieldedTransferParams, +} from '../../lib/engine.ts'; +import { throwIfCancelled } from '../../lib/errors.ts'; +import { getNetworkId } from '../../lib/network-id.ts'; +import { bindCachesToIndexer, describeIndexerChange } from '../../lib/cache-indexer.ts'; +import { loadWalletCache, saveWalletCache } from '../../lib/wallet-cache.ts'; +import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '../../lib/dust-wait.ts'; +import { trackElapsed } from '../../ui/spinner.ts'; +import { decodeShieldedAddress } from './addresses.ts'; +import { buildFacade, hasDustAvailable, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; +import { ensureDust, executeTransfer } from './transfer.ts'; +import { airdropNight } from './airdrop.ts'; +import { registerDust } from './dust-register.ts'; +import { exportDustSnapshot } from './dust-export.ts'; +import { defaultRepository } from './wallet-data-repository.ts'; +import { createDAppConnector } from './dapp-connector.ts'; + +const HOUR_MS = 60 * 60 * 1000; + +async function shieldedTransfer(params: ShieldedTransferParams): Promise { + const { seed, network, networkConfig, amount, progress, signal } = params; + const networkId = getNetworkId(networkConfig.networkId); + const nightToken = ledger.unshieldedToken().raw; + const receiverAddress = decodeShieldedAddress(params.recipient, network); + + return defaultRepository().withFacade( + seed, + networkConfig, + async ({ bundle, state }) => { + params.onSenderShieldedAddress?.(MidnightBech32m.encode(networkId, state.shielded.address).asString()); + + const shieldedBalance = state.shielded.balances[nightToken] ?? 0n; + if (shieldedBalance < amount) { + throw new Error(params.insufficient((Number(shieldedBalance) / 1_000_000).toFixed(6))); + } + + progress.update('Checking dust...'); + await ensureDust(bundle, (status: string) => progress.update(status)); + + throwIfCancelled(signal); + + progress.update('Building shielded transaction...'); + const build = () => bundle.facade.transferTransaction( + [{ + type: 'shielded' as const, + outputs: [{ type: nightToken, amount, receiverAddress }], + }], + { ttl: new Date(Date.now() + HOUR_MS) }, + ); + const recipe = params.waitForDustToCover + ? await payWhenDustCovers(build, state.dust, { maxWaitMs: DUST_SHORT_WAIT_MS, onStatus: (status) => progress.update(status), signal }) + : await build(); + + progress.update('Signing...'); + const signed = await bundle.facade.signRecipe(recipe, bundle.keystore.signDataAsync); + + progress.update('Generating ZK proof (this may take a few minutes)...'); + const finalized = await bundle.facade.finalizeRecipe(signed); + + // facade.submitTransaction blocks until the chain finalizes the block + // (typically 12 to 30s on hosted networks, ~6 to 12s on localnet). + // trackElapsed updates the spinner once a second so users see the wait + // is alive, not stuck. + const txId = await trackElapsed( + progress, + 'Submitting and waiting for finalization (typically 12 to 30s)...', + bundle.facade.submitTransaction(finalized), + ); + return String(txId); + }, + { + syncMode: 'full', + log: params.log, + requireStrictSync: true, + signal, + onStatus: params.onStatus, + onSyncProgress: params.onSyncProgress, + onSyncDetail: params.onSyncDetail, + }, + ); +} + +/** The wallet a test's preparation checks, built from its saved state and synced quickly (no shielded sync). */ +async function syncedPrepWallet(wallet: PrepWallet, reportSync: boolean, beforeSync?: () => void) { + bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS); + const bundle = await buildFacade(wallet.seed, wallet.networkConfig, loadWalletCache(wallet.address, wallet.network)); + try { + beforeSync?.(); + const state = await startAndSyncFacade(bundle, { + syncMode: 'lite', + signal: wallet.signal, + ...(reportSync + ? { + onProgress: (applied: number, highest: number) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + wallet.onMessage(`Syncing wallet... ${pct}%`); + } + }, + onSyncDetail: (detail: string) => wallet.onMessage(`Syncing wallet... (${detail})`), + } + : {}), + }); + return { bundle, state }; + } catch (err) { + try { await stopFacade(bundle); } catch { /* best-effort */ } + throw err; + } +} + +async function prepNightBalance(wallet: PrepWallet): Promise { + const { bundle, state } = await syncedPrepWallet(wallet, true); + try { + const balance = state.unshielded.balances[ledger.unshieldedToken().raw] ?? 0n; + if (balance > 0n) { + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + } + return balance; + } finally { + try { await stopFacade(bundle); } catch { /* best-effort */ } + } +} + +async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAvailable: boolean; dustAvailable: boolean }> { + const { bundle } = await syncedPrepWallet(wallet, false, () => wallet.onMessage('Syncing wallet...')); + try { + // Register dust (auto-registers UTXOs if needed, no-op if already available) + wallet.onMessage('Ensuring dust...'); + const result = await ensureDust(bundle, (status) => wallet.onMessage(`Dust: ${status}`)); + if (result.alreadyAvailable) { + wallet.onMessage('Dust already available'); + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + return { alreadyAvailable: true, dustAvailable: true }; + } + + // Dust was just registered: wait for coins to actually appear on chain. + // This must use the same facade to get real-time state updates. + wallet.onMessage('Dust registered. Waiting for coins to become available...'); + const dustAvailable = hasDustAvailable(await waitForDustAvailable(bundle, waitMs, wallet.signal)); + if (dustAvailable) { + wallet.onMessage('Dust is available'); + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + } + return { alreadyAvailable: false, dustAvailable }; + } finally { + try { await stopFacade(bundle); } catch { /* best-effort */ } + } +} + +const openConnector: EngineWallet['openConnector'] = async (options): Promise => { + const { seed, network, networkConfig, address, syncMode, signal, onMessage } = options; + // A failure before the connector is handed back stops what was started, so + // the facade doesn't keep syncing. + let bundle: Awaited> | undefined; + let connector: DAppConnector; + try { + // Build & sync facade + onMessage('Building wallet facade...'); + const indexerChange = bindCachesToIndexer(network, networkConfig.indexerWS); + if (indexerChange) onMessage(describeIndexerChange(network, indexerChange)); + // As the repository's own borrowers do: warm the Dust checkpoint, then + // restore from it when there is no saved wallet, instead of the SDK + // replaying the chain's whole Dust history (minutes on a hosted network). + const repo = defaultRepository(); + // Best-effort, as there: a failed warm-up leaves the sync below to do it. + try { + await repo.dust(seed, networkConfig, { signal, onStatus: onMessage }); + } catch { + throwIfCancelled(signal); // a cancel is not a failed warm-up + } + const cache = await repo.walletStateToRestore(seed, networkConfig, network); + const built = await buildFacade(seed, networkConfig, cache); + bundle = built; + + onMessage('Syncing wallet...'); + await startAndSyncFacade(built, { + syncMode, + signal, + onProgress: (applied, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + onMessage(`Syncing wallet... ${pct}%`); + } + }, + }); + onMessage('Wallet synced'); + + // Wait for dust + onMessage('Waiting for dust...'); + const syncedState = await waitForDustAvailable(built, undefined, signal); + onMessage('Dust ready'); + + // Save cache after sync + try { await saveWalletCache(address, network, built.facade); } catch { /* best-effort */ } + + // Create DApp Connector — approve-all mode for tests + connector = createDAppConnector({ + bundle: built, + networkConfig, + approvalOptions: { approveAll: true, autoApproveReads: true }, + // Reads answer from the state this sync ended on, and from every later + // one that is synced by the rule the sync used. + initialState: syncedState, + isCurrent: (state) => isFacadeSynced(state, syncMode, built.emptyStreams), + dustWaitMs: options.dustWaitMs, + callbacks: { + onPhaseStart: (_connId, _method, phase) => { + onMessage(`${phase}...`); + }, + onPhaseComplete: (_connId, _method, phase, durationMs) => { + onMessage(`${phase} ${Math.round(durationMs)}ms`); + }, + }, + }); + } catch (err) { + if (bundle !== undefined) { try { await stopFacade(bundle); } catch { /* best-effort */ } } + throw err; + } + const started = bundle; + return { + connector, + async stop() { + connector.dispose(); + try { await stopFacade(started); } catch { /* best-effort */ } + }, + }; +}; + +const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { + const { seed, networkConfig, network, address, syncMode } = options; + // The repository owns validating the caches, priming Dust, building the + // facade, syncing (with retries) and stopping it. Its save is skipped: mn + // serve saves only when no transaction is pending, since the SDK drops + // pending Dust on serialization and would persist dust=0. + return defaultRepository().withFacade(seed, networkConfig, async ({ bundle }) => { + let lastState: Awaited> | undefined; + const session: ServedWalletSession = { + async waitForDust() { + lastState = await waitForDustAvailable(bundle); + return hasDustAvailable(lastState); + }, + async saveState() { + try { await saveWalletCache(address, network, bundle.facade); } catch { /* best-effort */ } + }, + connect: ({ approvalOptions, feeLimits, callbacks }) => createDAppConnector({ + bundle, + networkConfig, + approvalOptions, + feeLimits, + callbacks, + // Reads answer from the state this sync ended on, and from every later + // one that is synced by the rule the sync used. + initialState: lastState, + isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), + }), + }; + return serve(session); + }, { + syncMode, + // serve accepts write requests from dApps — must be strictly synced. + requireStrictSync: true, + skipAutoSave: true, + signal: options.signal, + log: options.log, + onStatus: options.onStatus, + onSyncProgress: options.onSyncProgress, + onSyncDetail: options.onSyncDetail, + }); +}; + +export const rcWallet: EngineWallet = { + unshieldedBalance: (address, networkConfig, options) => defaultRepository().unshielded(address, networkConfig, options), + async dustBalance(seed, networkConfig, options) { + const { state: _state, ...balance } = await defaultRepository().dust(seed, networkConfig, options); + return balance; + }, + transfer: executeTransfer, + airdrop: airdropNight, + shieldedTransfer, + registerDust, + exportDust: (seed, network, networkConfig, options) => exportDustSnapshot(seed, network, networkConfig, options), + prepNightBalance, + prepDust, + openConnector, + serveWallet, +}; diff --git a/src/lib/balance-subscription.ts b/src/lib/balance-subscription.ts index 455a2259..d8f50752 100644 --- a/src/lib/balance-subscription.ts +++ b/src/lib/balance-subscription.ts @@ -3,16 +3,8 @@ import { assertEndpointUsable, endpointRefusalFromWsError } from './blockfrost.t import { NATIVE_TOKEN_TYPE, BALANCE_CHECK_TIMEOUT_MS } from './constants.ts'; import { CancelledError } from './errors.ts'; -export interface BalanceSummary { - balances: Map; - utxoCount: number; - txCount: number; - highestTxId: number; - /** Count of unspent native-token UTXOs registered for dust generation. */ - registeredUtxos: number; - /** Count of unspent native-token UTXOs NOT registered for dust generation. */ - unregisteredUtxos: number; -} +export type { BalanceSummary } from './engine.ts'; +import type { BalanceSummary } from './engine.ts'; interface Utxo { value: string; diff --git a/src/lib/connector-api.ts b/src/lib/connector-api.ts index ce7a51dd..8da92187 100644 --- a/src/lib/connector-api.ts +++ b/src/lib/connector-api.ts @@ -41,3 +41,6 @@ export function createApiError(code: ErrorCode, reason: string): APIError { error.reason = reason; return error; } + +/** The error message when the operator declines an approval prompt. */ +export const OPERATOR_REJECTED_MESSAGE = 'User rejected the request'; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index f3f1038c..0e5c2a32 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -7,9 +7,8 @@ import { existsSync } from 'node:fs'; import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet } from '../wallet-config.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; import { passphraseForNewSecret } from '../passphrase.ts'; -import { airdropNight } from '../airdrop.ts'; +import { engineFor } from '../engine.ts'; import { checkBalance } from '../balance-subscription.ts'; -import { registerDust } from '../dust-register.ts'; import { resolveNetwork } from '../resolve-network.ts'; import type { NetworkConfig } from '../network.ts'; import type { CallSdkWarnings } from '../sdk-warnings.ts'; @@ -153,7 +152,8 @@ async function generateWallet(name: string, signal?: AbortSignal): Promise async function airdropToWallet(network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { const recipientAddress = (await loadWalletConfig(resolveWalletPath(name))).addresses.undeployed; - await airdropNight({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings }); + // dev's wallets live on the local chain. + await (await engineFor('undeployed')).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings }); } async function walletNeedsDust(network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { @@ -164,5 +164,5 @@ async function walletNeedsDust(network: NetworkConfig, name: string, signal: Abo async function registerWalletDust(network: NetworkConfig, name: string, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { const { seed } = await unlockWallet(resolveWalletPath(name)); - await registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings }); + await (await engineFor('undeployed')).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings }); } diff --git a/src/lib/engine.ts b/src/lib/engine.ts index 97f5ba69..411ab183 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -5,6 +5,12 @@ // Loading an engine loads its SDK, so the loader imports it only when asked. import type { NetworkConfig, NetworkName } from './network.ts'; +import type { CallSdkWarnings } from './sdk-warnings.ts'; +import type { VerboseLog } from './verbose.ts'; +import type { ApprovalOptions } from './approval.ts'; +import type { FeeLimits } from './fee-limits.ts'; +import type { RpcHandler } from './connector-api.ts'; +import type { Spinner } from '../ui/spinner.ts'; /** An SDK set mn runs on. */ export type SdkSet = 'rc'; @@ -156,6 +162,251 @@ export interface EngineReaders { shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options?: ShieldedCachedOptions): Promise; } +// ── The wallet ── + +/** An address's unshielded balances, as the indexer's UTXOs give them. */ +export interface BalanceSummary { + balances: Map; + utxoCount: number; + txCount: number; + highestTxId: number; + /** Count of unspent native-token UTXOs registered for dust generation. */ + registeredUtxos: number; + /** Count of unspent native-token UTXOs NOT registered for dust generation. */ + unregisteredUtxos: number; +} + +export interface TransferParams { + seedBuffer: Buffer; + networkConfig: NetworkConfig; + recipientAddress: string; + amountNight: number; + signal?: AbortSignal; + onSync?: (applied: number, highest: number) => void; + onSyncDetail?: (walletsStillSyncing: string) => void; + onDust?: (status: string) => void; + onProving?: () => void; + onSubmitting?: () => void; + /** Fires every second while waiting for chain finalization. `elapsedMs` + * is the time since the submit started. Use to drive an elapsed-time + * display so users see the wait is alive. + */ + onSubmittingTick?: (elapsedMs: number) => void; + onSyncWarning?: (tag: string, message: string) => void; + /** The call's SDK warnings, listened to for the whole transfer. */ + sdkWarnings: CallSdkWarnings; + /** The call's verbose lines. */ + log?: VerboseLog; +} + +export interface TransferResult { + txHash: string; + amountMicroNight: bigint; +} + +export interface EnsureDustResult { + alreadyAvailable: boolean; + txHash?: string; +} + +export type AirdropParams = Omit; + +export interface DustRegisterOptions { + signal?: AbortSignal; + /** What the registration is doing now, for a progress line. */ + onStatus?: (status: string) => void; + /** Wallet sync progress, as blocks applied of the highest seen. */ + onSyncProgress?: (applied: number, highest: number) => void; + /** Which wallets the sync still waits on. */ + onSyncDetail?: (detail: string) => void; + /** A transient SDK error the sync is retrying past. */ + onSyncWarning?: (tag: string, message: string) => void; + /** The call's SDK warnings, listened to for the whole registration. */ + sdkWarnings: CallSdkWarnings; + /** The call's verbose lines. */ + log?: VerboseLog; +} + +export interface DustRegistration { + /** The wallet had Dust already; nothing was registered. */ + alreadyAvailable: boolean; + txHash?: string; + /** The Dust balance once synced, in its smallest unit. */ + dustBalance: bigint; +} + +export interface DustExportResult { + network: string; + /** Dust public key (hex) this snapshot belongs to — derived from the seed. */ + dustPublicKey: string; + /** Last dust event id the snapshot covers; -1 if the wallet has no dust events yet. */ + offset: number; + /** Dust balance encoded in the snapshot, at export time. */ + balance: bigint; + /** Dust events applied during this export's sync (delta since any prior cache). */ + eventCount: number; + /** True if an existing dust-direct cache was extended; false if synced from scratch. */ + fromCache: boolean; + /** + * True iff the sync stopped short of the chain tip. The snapshot is still a + * valid checkpoint — restoring it is strictly better than starting cold — but + * it is NOT current, and a wallet restored from it still has events to catch + * up on. Consumers must not treat a partial export as a warm wallet. + */ + partial: boolean; + /** The facade-restorable dust snapshot — pass as `dustSerializedState`. */ + snapshot: string; +} + +export interface UnshieldedView extends BalanceSummary { + fromCache: boolean; + fetchedAt: number; +} + +export interface ReadOptions { + /** Bypass every cache layer and re-fetch from network. */ + forceFresh?: boolean; + signal?: AbortSignal; + /** Status hook for spinner wiring. */ + onStatus?: (s: string) => void; + /** + * Raw progress signal during the underlying network fetch. For dust this + * fires per-chunk (events applied vs max event id); for unshielded it + * fires per-UTXO-batch (current tx vs highest tx id). Callers that already + * have a spinner usually use this to render a percentage. + */ + onProgress?: (current: number, highest: number) => void; + /** The call's verbose lines. */ + log?: VerboseLog; +} + +/** A wallet's Dust, as mn's reader found it. */ +export interface DustBalance { + balance: bigint; + availableCoins: number; + ownedUtxoCount: number; + syncTime: Date; + /** + * True iff any cache layer participated — either an in-memory memo hit, OR a + * disk-cache resume (delta sync from a previous checkpoint). False only for + * a true cold scan from event 0. + */ + fromCache: boolean; + /** Number of events applied by this call (0 on memo hits; delta count on disk-resume; full count on cold). */ + eventsApplied: number; + /** + * Id of the last dust event folded into `state`; -1 when the wallet has no + * dust events on this chain yet. This is the snapshot offset a restoring + * wallet resumes from, and it lives nowhere else in the view. + */ + lastAppliedEventId: number; + /** + * True iff the sync stopped short of the chain tip even after exhausting the + * partial-resume loop — the state is a valid checkpoint but NOT current. + * Callers that hand this state to another wallet (`dust export`) must surface + * it: restoring a short state looks like success and then silently falls back + * to the SDK's cold sync for the remaining events. + */ + partial: boolean; + /** Wall-clock millis when this value was last refreshed from the network. */ + fetchedAt: number; +} + +/** What a wallet operation reports while it syncs the wallet. */ +export interface WalletSyncHooks { + signal?: AbortSignal; + log?: VerboseLog; + onStatus?: (status: string) => void; + onSyncProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; +} + +/** A shielded payment of NIGHT from a seed's wallet. */ +export interface ShieldedTransferParams extends WalletSyncHooks { + seed: Buffer; + network: NetworkName; + networkConfig: NetworkConfig; + /** The recipient's shielded address on `network`. */ + recipient: string; + /** In NIGHT's smallest unit. */ + amount: bigint; + /** Says each step, and the time the submit has taken. */ + progress: Spinner; + /** The refusal when the wallet holds less shielded NIGHT than `amount`, given what it holds, in NIGHT. */ + insufficient: (availableNight: string) => string; + /** Right after another payment the wallet's Dust can be short of this fee: wait when the rest is moments away. */ + waitForDustToCover: boolean; + /** The paying wallet's own shielded address, once synced. */ + onSenderShieldedAddress?: (address: string) => void; +} + +/** A wallet a test's preparation checks, by its seed and its saved address. */ +export interface PrepWallet { + seed: Buffer; + network: NetworkName; + networkConfig: NetworkConfig; + address: string; + signal?: AbortSignal; + onMessage: (message: string) => void; +} + +export interface DAppConnectorCallbacks { + onPhaseStart?: (connectionId: string, method: string, phase: string) => void; + onPhaseComplete?: (connectionId: string, method: string, phase: string, durationMs: number) => void; +} + +/** A wallet's DApp connector: the API's methods as RPC handlers. */ +export interface DAppConnector { + handlers: Record; + /** Revert all pending (unsubmitted) transactions for a connection, releasing locked coins. */ + revertPendingTxs(connectionId: string): Promise; + /** True if any connection has a balanced-but-not-submitted transaction. */ + hasPendingTxs(): boolean; + dispose(): void; +} + +/** The connector over a synced wallet, in --approve-all mode, for a command of mn's own; stop() stops both. */ +export interface OpenedConnector { + connector: DAppConnector; + stop(): Promise; +} + +/** A wallet synced for mn serve, while the serve runs. */ +export interface ServedWalletSession { + /** Waits for the wallet's Dust coins to be available (on preprod 10 to 30 s after a sync); whether they are. */ + waitForDust(): Promise; + /** Saves the wallet's state for the next start; best-effort. */ + saveState(): Promise; + /** The DApp connector over the wallet, reading from the state the last wait ended on. */ + connect(options: { approvalOptions: ApprovalOptions; feeLimits?: FeeLimits; callbacks?: DAppConnectorCallbacks }): DAppConnector; +} + +/** A wallet, through the SDK's wallet and mn's readers. */ +export interface EngineWallet { + /** The unshielded balance of an address, through mn's cache. */ + unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + /** A seed's Dust, through mn's reader and its cache. */ + dustBalance(seed: Buffer, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + /** An unshielded payment of NIGHT. */ + transfer(params: TransferParams): Promise; + /** NIGHT from the genesis wallet (a local chain only). */ + airdrop(params: AirdropParams): Promise; + /** A shielded payment of NIGHT; its transaction hash. */ + shieldedTransfer(params: ShieldedTransferParams): Promise; + /** Registers a seed's NIGHT for Dust, unless it has Dust already. */ + registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; + /** A seed's Dust as a snapshot another wallet restores from. */ + exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options?: { signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void }): Promise; + /** A test wallet's unshielded NIGHT after a quick sync; its state is saved when it holds some. */ + prepNightBalance(wallet: PrepWallet): Promise; + /** Makes sure a test wallet has Dust, registering and then waiting up to `waitMs` for it. */ + prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAvailable: boolean; dustAvailable: boolean }>; + /** The connector over a seed's wallet, synced and its Dust ready, for a command of mn's own. */ + openConnector(options: { seed: Buffer; network: NetworkName; networkConfig: NetworkConfig; address: string; syncMode: 'full' | 'lite'; dustWaitMs?: number; signal?: AbortSignal; onMessage: (message: string) => void }): Promise; + /** Syncs a seed's wallet strictly for mn serve and runs `serve` with it; the wallet stops when `serve` ends. */ + serveWallet(options: { seed: Buffer; networkConfig: NetworkConfig; network: NetworkName; address: string; syncMode: 'full' | 'lite' } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; +} + /** One SDK set, as mn uses it. */ export interface Engine { readonly set: SdkSet; @@ -163,6 +414,7 @@ export interface Engine { readonly ledger: EngineLedger; readonly contracts: EngineContracts; readonly readers: EngineReaders; + readonly wallet: EngineWallet; } /** The SDK set a network runs on. */ diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index dc0c5813..3abbfb6d 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -8,14 +8,9 @@ import { loadWalletConfig, resolveWalletPath, unlockWallet } from './wallet-conf import { resolveNetwork } from './resolve-network.ts'; import { assertLedgerSupported } from './ledger-guard.ts'; import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from './network.ts'; -import { buildFacade, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; -import { bindCachesToIndexer, describeIndexerChange } from './cache-indexer.ts'; -import { saveWalletCache } from './wallet-cache.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; -import { createDAppConnector, type DAppConnectorCallbacks } from './dapp-connector.ts'; +import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from './engine.ts'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; import { DEFAULT_SERVE_PORT } from './constants.ts'; -import type { FacadeBundle } from './facade.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; import { CancelledError, throwIfCancelled } from './errors.ts'; @@ -219,10 +214,8 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise; - stop(): Promise; -} +/** The connector over a synced wallet; stop() stops both. */ +export type { OpenedConnector } from './engine.ts'; /** * The wallet's DApp connector in this process, in --approve-all mode, with no @@ -248,83 +241,29 @@ export async function openConnector(options: ServeManagerOptions): Promise> | undefined; - let connector: ReturnType; + // the listener doesn't outlive this call and the wallet doesn't keep syncing. + let opened: OpenedConnector; try { - // Build & sync facade - onMessage('Building wallet facade...'); - const indexerChange = bindCachesToIndexer(networkName, networkConfig.indexerWS); - if (indexerChange) onMessage(describeIndexerChange(networkName, indexerChange)); - // As the repository's own borrowers do: warm the Dust checkpoint, then - // restore from it when there is no saved wallet, instead of the SDK - // replaying the chain's whole Dust history (minutes on a hosted network). - const repo = defaultRepository(); - // Best-effort, as there: a failed warm-up leaves the sync below to do it. - try { - await repo.dust(seedBuffer, networkConfig, { signal, onStatus: onMessage }); - } catch { - throwIfCancelled(signal); // a cancel is not a failed warm-up - } - const cache = await repo.walletStateToRestore(seedBuffer, networkConfig, networkName); - const built = await buildFacade(seedBuffer, networkConfig, cache); - bundle = built; - - // As `mn serve` does: skip the slow shielded sync where shielded is unusable (no faucet). - const syncMode = shieldedSyncEnabled(networkName) ? 'full' : 'lite'; - onMessage('Syncing wallet...'); - await startAndSyncFacade(built, { - syncMode, - signal, - onProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - onMessage(`Syncing wallet... ${pct}%`); - } - }, - }); - onMessage('Wallet synced'); - - // Wait for dust - onMessage('Waiting for dust...'); - const syncedState = await waitForDustAvailable(built, undefined, signal); - onMessage('Dust ready'); - - // Save cache after sync - try { await saveWalletCache(address, networkName, built.facade); } catch { /* best-effort */ } - - // Create DApp Connector — approve-all mode for tests - connector = createDAppConnector({ - bundle: built, + opened = await (await engineFor(networkName)).wallet.openConnector({ + seed: seedBuffer, + network: networkName, networkConfig, - approvalOptions: { approveAll: true, autoApproveReads: true }, - // Reads answer from the state this sync ended on, and from every later - // one that is synced by the rule the sync used. - initialState: syncedState, - isCurrent: (state) => isFacadeSynced(state, syncMode, built.emptyStreams), + address, + // As `mn serve` does: skip the slow shielded sync where shielded is unusable (no faucet). + syncMode: shieldedSyncEnabled(networkName) ? 'full' : 'lite', dustWaitMs: options.dustWaitMs, - callbacks: { - onPhaseStart: (_connId, _method, phase) => { - onMessage(`${phase}...`); - }, - onPhaseComplete: (_connId, _method, phase, durationMs) => { - onMessage(`${phase} ${Math.round(durationMs)}ms`); - }, - }, + signal, + onMessage, }); } catch (err) { stopListening(); - if (bundle !== undefined) { try { await stopFacade(bundle); } catch { /* best-effort */ } } throw err; } - const started = bundle; - return { - connector, + connector: opened.connector, async stop() { - connector.dispose(); stopListening(); - try { await stopFacade(started); } catch { /* best-effort */ } + await opened.stop(); }, }; } diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index 17ed3ed0..e8bd0757 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -2,16 +2,11 @@ import { join } from 'node:path'; -import { bindCachesToIndexer } from '../cache-indexer.ts'; import { clearWalletCache } from '../wallet-cache.ts'; import { resolveWalletPath, unlockWallet } from '../wallet-config.ts'; import { resolveNetwork } from '../resolve-network.ts'; import type { NetworkConfig, NetworkName } from '../network.ts'; import { assertLedger9StackReachable, assertLedgerSupported } from '../ledger-guard.ts'; -import { buildFacade, hasDustAvailable, startAndSyncFacade, stopFacade, waitForDustAvailable } from '../facade.ts'; -import { loadWalletCache, saveWalletCache } from '../wallet-cache.ts'; -import { ensureDust } from '../transfer.ts'; -import { airdropNight } from '../airdrop.ts'; import type { DappTestConfig, PrepStepId, PrepStepResult, PrepContext, PrepCallbacks } from './types.ts'; import { startServeOrReuse } from '../serve-manager.ts'; @@ -120,38 +115,18 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont // Check current balance — use fresh cache since localnet may have restarted callbacks.onMessage('Checking balance...'); - bindCachesToIndexer(network, networkConfig.indexerWS); - const cache = loadWalletCache(address, network); + const engine = await engineFor(network); const stopListening = ctx.sdkWarnings.listen((_tag, msg) => { callbacks.onMessage(`SDK: ${msg}`); }); - const bundle = await buildFacade(seedBuffer, networkConfig, cache).catch((err: unknown) => { stopListening(); throw err; }); - try { - const state = await startAndSyncFacade(bundle, { - syncMode: 'lite', - signal: ctx.signal, - onProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - callbacks.onMessage(`Syncing wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => { - callbacks.onMessage(`Syncing wallet... (${detail})`); - }, - }); - const nightToken = (await engineFor(network)).ledger.nightTokenId(); - const balance = state.unshielded.balances[nightToken] ?? 0n; - + const balance = await engine.wallet.prepNightBalance({ seed: seedBuffer, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }); if (balance > 0n) { callbacks.onMessage(`Balance OK: ${balance}`); - try { await saveWalletCache(address, network, bundle.facade); } catch {} return; } } finally { stopListening(); - try { await stopFacade(bundle); } catch {} } // Balance is zero @@ -166,7 +141,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont // Undeployed (localnet) — auto-airdrop from genesis callbacks.onMessage(`Balance is 0. Airdropping ${amount} NIGHT from genesis...`); // The same genesis airdrop `mn airdrop` and `mn dev` fund through. - await airdropNight({ + await engine.wallet.airdrop({ networkConfig, recipientAddress: address, amountNight: amount, @@ -195,33 +170,13 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre const address = walletConfig.addresses[network as NetworkName]; // Keep the SDK's transient errors and RPC noise off the terminal while this runs. - bindCachesToIndexer(network, networkConfig.indexerWS); - const cache = loadWalletCache(address, network); const stopListening = ctx.sdkWarnings.listen(undefined); - const bundle = await buildFacade(seedBuffer, networkConfig, cache).catch((err: unknown) => { stopListening(); throw err; }); - try { - callbacks.onMessage('Syncing wallet...'); - await startAndSyncFacade(bundle, { syncMode: 'lite', signal: ctx.signal }); - - // Register dust (auto-registers UTXOs if needed, no-op if already available) - callbacks.onMessage('Ensuring dust...'); - const result = await ensureDust(bundle, (status) => callbacks.onMessage(`Dust: ${status}`)); - - if (result.alreadyAvailable) { - callbacks.onMessage('Dust already available'); - try { await saveWalletCache(address, network, bundle.facade); } catch {} - return; - } - - // Dust was just registered — wait for coins to actually appear on-chain. - // This MUST use the same facade to get real-time state updates. - callbacks.onMessage('Dust registered. Waiting for coins to become available...'); - const dustState = await waitForDustAvailable(bundle, DUST_WAIT_TIMEOUT_MS, ctx.signal); - + const { dustAvailable } = await (await engineFor(network)).wallet.prepDust( + { seed: seedBuffer, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }, + DUST_WAIT_TIMEOUT_MS, + ); // Verify dust is actually available — don't trust silent timeouts - const dustAvailable = hasDustAvailable(dustState); - if (!dustAvailable) { if (network !== 'undeployed') { throw new Error( @@ -232,12 +187,8 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre } throw new Error(`Dust not available after ${DUST_WAIT_TIMEOUT_MS / 1000}s. The chain may be slow — try again.`); } - - callbacks.onMessage('Dust is available'); - try { await saveWalletCache(address, network, bundle.facade); } catch {} } finally { stopListening(); - try { await stopFacade(bundle); } catch {} } } diff --git a/src/lib/wallet-can-pay.ts b/src/lib/wallet-can-pay.ts index 9f5baef3..66940c83 100644 --- a/src/lib/wallet-can-pay.ts +++ b/src/lib/wallet-can-pay.ts @@ -21,14 +21,14 @@ export async function assertWalletCanPay({ network, networkConfig }: PayingTarge const walletConfig = await unlockWallet(resolveWalletPath(wallet)); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; - const { defaultRepository } = await import('./wallet-data-repository.ts'); - const repo = defaultRepository(); + const { engineFor } = await import('./engine.ts'); + const { wallet: repo } = await engineFor(network); try { // Two cheap reads through the repo: no facade, no proof server, no strict // sync. Its tip-aware memo makes the next check in the same MCP session // nearly free. - const balanceView = await repo.unshielded(address, networkConfig, { signal }); + const balanceView = await repo.unshieldedBalance(address, networkConfig, { signal }); const nightBalance = balanceView.balances.get(NATIVE_TOKEN_TYPE) ?? 0n; if (nightBalance === 0n) { @@ -43,7 +43,7 @@ export async function assertWalletCanPay({ network, networkConfig }: PayingTarge ); } - const dustView = await repo.dust(seedBuffer, networkConfig, { signal, onStatus: (s) => progress.update(s) }); + const dustView = await repo.dustBalance(seedBuffer, networkConfig, { signal, onStatus: (s) => progress.update(s) }); if (dustView.balance === 0n && dustView.availableCoins === 0) { progress.fail('No dust available'); throw new Error( From 8f8d89d02f600494047a2c8ddab81e21eea167a3 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:09:17 -0800 Subject: [PATCH 29/88] The engine loader is the host's: the shell installs the engines it ships core's engineFor loaded the rc engine by relative path, which a core package can't. Now the host installs a loader at start, as it does the settings and the state root: the shell's installed-engines.ts lists the engines this build ships, and only it may import one. Tests install the same loader. No behaviour changes: suite and snapshot unchanged. --- scripts/check-layering.mjs | 8 ++++---- scripts/check-process-safety.mjs | 5 ++++- src/__tests__/helpers/shell-settings.ts | 9 +++++++-- src/__tests__/layering.test.ts | 11 ++++++----- src/lib/cli-host.ts | 6 +++++- src/lib/engine.ts | 17 +++++++++++++++-- src/lib/installed-engines.ts | 13 +++++++++++++ 7 files changed, 54 insertions(+), 15 deletions(-) create mode 100644 src/lib/installed-engines.ts diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 0be081e7..7e2a7773 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -29,7 +29,7 @@ const HOMES = [ ['shell', /^wallet\.ts$/], // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], - ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|command-dispatch|agent-manual|readme-commands)\.ts$/], + ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], @@ -95,9 +95,9 @@ const DISPATCHERS = new Set(['shell', 'mcp']); const MIDNIGHT_SDK = /^@midnight(-ntwrk|ntwrk)\//; -// The one module that may import an engine: core's loader, which imports the -// engine for a network's SDK set when a call needs it. -const ENGINE_LOADER = 'lib/engine.ts'; +// The one module that may import an engine: the shell's list of the engines +// it ships, which the host installs as core's engine loader. +const ENGINE_LOADER = 'lib/installed-engines.ts'; const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 5d2f5407..3c615c29 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -87,7 +87,10 @@ export const ALLOWED_STATE = { 'engine/rc/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/ws-rpc.ts': { connectionCounter: 'shared on purpose: the RPC connection id counter, unique across servers in the process' }, - 'lib/engine.ts': { loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)' }, + 'lib/engine.ts': { + loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)', + loader: 'shared on purpose: the host sets the engine loader once', + }, 'lib/wallet-config.ts': { warnedPlain: 'shared on purpose: each plain-text wallet is warned about once per run' }, // The host sources, set once by the host at start (handlers see them through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, diff --git a/src/__tests__/helpers/shell-settings.ts b/src/__tests__/helpers/shell-settings.ts index 24a397f1..26895bc1 100644 --- a/src/__tests__/helpers/shell-settings.ts +++ b/src/__tests__/helpers/shell-settings.ts @@ -1,12 +1,17 @@ // The test run stands in for the shell: libraries read the environment the -// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, and keep their state -// under the home the tests set (HOME), as the CLI gives them. +// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, keep their state under +// the home the tests set (HOME), and load the engines the CLI ships, as the +// CLI gives them. import { homedir } from 'node:os'; import { join } from 'node:path'; import { setSettingsSource, settingsFromEnvironment } from '../../lib/settings.ts'; import { setHostPathsSource } from '../../lib/state-root.ts'; import { MIDNIGHT_DIR } from '../../lib/constants.ts'; +import { setEngineLoader } from '../../lib/engine.ts'; +import { loadInstalledEngine } from '../../lib/installed-engines.ts'; setSettingsSource(() => settingsFromEnvironment(process.env)); setHostPathsSource(() => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() })); +// And the engines this build ships, as the CLI gives them. +setEngineLoader(loadInstalledEngine); diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index e9ad11b2..f3a23f32 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -38,16 +38,17 @@ describe('the layering', () => { expect(importRule('commands/dev.ts', 'commands/contract.ts')).toBe('command → contract command'); }); - it('lets only core\'s loader reach an engine, and an engine reach only core and chain', () => { - expect(importRule('lib/engine.ts', 'engine/rc/index.ts')).toBeUndefined(); - expect(importRule('commands/address.ts', 'engine/rc/derive-address.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); - expect(importRule('lib/wallet-create.ts', 'engine/rc/index.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); + it('lets only the shell\'s list of engines reach an engine, and an engine reach only core and chain', () => { + expect(importRule('lib/installed-engines.ts', 'engine/rc/index.ts')).toBeUndefined(); + expect(importRule('lib/engine.ts', 'engine/rc/index.ts')).toBe('core → engine (reach it through lib/installed-engines.ts)'); + expect(importRule('commands/address.ts', 'engine/rc/derive-address.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); + expect(importRule('lib/wallet-create.ts', 'engine/rc/index.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); expect(importRule('engine/rc/derive-address.ts', 'lib/network.ts')).toBeUndefined(); expect(importRule('engine/rc/index.ts', 'lib/facade.ts')).toBe('engine → wallet'); }); it('lets only an engine import the SDK', () => { // findLayeringProblems above finds none elsewhere; core, chain and every package are held to it alike. - expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/engine.ts)'); + expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); }); }); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 5328daf2..47cf6628 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -5,7 +5,8 @@ // calls it runs, whose SDK warnings go to the call that raised them; // - a notice sink: stderr; // - settings, read from the environment as each is needed; -// - the state root, ~/.midnight, read as each path is built. +// - the state root, ~/.midnight, read as each path is built; +// - the SDK engines this build ships. // The prompter is the CLI's alone: the MCP server has no terminal to ask at. import { homedir } from 'node:os'; @@ -15,6 +16,8 @@ import { setNoticeSink } from './notices.ts'; import { setSettingsSource, settingsFromEnvironment } from './settings.ts'; import { setHostPathsSource } from './state-root.ts'; import { MIDNIGHT_DIR } from './constants.ts'; +import { setEngineLoader } from './engine.ts'; +import { loadInstalledEngine } from './installed-engines.ts'; import type { SdkWarningCalls } from './sdk-warnings.ts'; /** What the host gives its runners. */ @@ -28,5 +31,6 @@ export function installCliHost(): CliHost { setNoticeSink((line) => process.stderr.write(line + '\n')); setSettingsSource(() => settingsFromEnvironment(process.env)); setHostPathsSource(() => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() })); + setEngineLoader(loadInstalledEngine); return { sdkWarnings }; } diff --git a/src/lib/engine.ts b/src/lib/engine.ts index 411ab183..2e12cf65 100644 --- a/src/lib/engine.ts +++ b/src/lib/engine.ts @@ -1,7 +1,8 @@ // The Midnight SDK, behind one interface. Everything that touches an SDK set // is an engine's; the rest of mn reaches it through the engine for its // network, and names no SDK type. One engine today, for the SDK's release -// candidates (rc). The interface grows area by area as code moves behind it. +// candidates (rc). Which engines there are is the host's: it installs a +// loader at start (the shell, the engines it ships), as it does the settings. // Loading an engine loads its SDK, so the loader imports it only when asked. import type { NetworkConfig, NetworkName } from './network.ts'; @@ -422,12 +423,24 @@ export function sdkSetOf(_network: NetworkName): SdkSet { return 'rc'; } +/** Loads the engine for an SDK set: the host's, which knows the engines it ships. */ +export type EngineLoader = (set: SdkSet) => Promise; + +let loader: EngineLoader | undefined; + // The engine this process has loaded: one per process, since two SDK sets' // WASM ledgers can't share one. let loaded: Promise | undefined; +/** The host's loader of engines, set once at start; a new loader forgets the engine an old one loaded. */ +export function setEngineLoader(next: EngineLoader): void { + loader = next; + loaded = undefined; +} + function loadEngine(set: SdkSet): Promise { - loaded ??= import('../engine/rc/index.ts').then((module) => module.rcEngine); + if (loader === undefined) throw new Error('No SDK engine is installed: the host sets an engine loader at start (setEngineLoader)'); + loaded ??= loader(set); return loaded.then((engine) => { if (engine.set !== set) throw new Error(`This process runs the ${engine.set} SDK set and can't load the ${set} one`); return engine; diff --git a/src/lib/installed-engines.ts b/src/lib/installed-engines.ts new file mode 100644 index 00000000..a7586b39 --- /dev/null +++ b/src/lib/installed-engines.ts @@ -0,0 +1,13 @@ +// A shell concern: the SDK engines this build of mn ships, which the host +// gives the libraries as their engine loader. Each loads its SDK, so each is +// imported only when a call needs it. + +import type { Engine, SdkSet } from './engine.ts'; + +/** The engine for an SDK set, as this build ships it. */ +export async function loadInstalledEngine(set: SdkSet): Promise { + switch (set) { + case 'rc': + return (await import('../engine/rc/index.ts')).rcEngine; + } +} From c33df153212a167a8f3ec212c4abe5a96d795e3e Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:19:03 -0800 Subject: [PATCH 30/88] core is a package: @kuiralabs/midnight-cli-core (phase E, EJ) An engine is its own package (Y32) and uses core, which has to be one copy shared with the shell (Y33). So core's modules (arguments, typed errors and exit codes, JSON output, config and its command, the state root, network endpoints, terminal formatting, the registry contract, the payer and the engine interface) move to packages/cli-core, a workspace package mn depends on, 0.1.0-rc.0. Everything else imports them by name. - In this repository the package runs from its source, under the midnight-cli-source export condition (tsc, vitest, and NODE_OPTIONS for what tests start; the tsx scripts pass it). Published, its exports resolve to its build (tsc to dist, with declarations), which mn's build makes first. - The layering and process-safety checks read the package's source as they read src/, and refuse a relative import out of a package. - The clean-install check packs the workspace packages mn depends on, installs them with it, and checks there is one copy of each. - The SDK-free checks no longer count our own packages as SDK. - A stale path in scripts/measure-preprod-dust.ts is fixed. No behaviour changes: suite (2255) and snapshot unchanged, clean install works. Publishing @kuiralabs/midnight-cli-core comes before the next mn release. --- package-lock.json | 16 ++++++- package.json | 14 +++--- packages/cli-core/package.json | 32 +++++++++++++ .../src}/commands/config.definition.ts | 0 .../cli-core/src}/commands/config.ts | 0 .../cli-core/src}/commands/core.guidance.ts | 0 .../cli-core/src}/lib/agent-guidance.ts | 0 {src => packages/cli-core/src}/lib/amount.ts | 0 .../cli-core/src}/lib/approval.ts | 0 {src => packages/cli-core/src}/lib/argv.ts | 0 .../cli-core/src}/lib/blockfrost.ts | 0 .../cli-core/src}/lib/cache-indexer.ts | 0 .../cli-core/src}/lib/call-context.ts | 0 .../cli-core/src}/lib/cli-config.ts | 0 .../cli-core/src}/lib/command-definition.ts | 0 .../cli-core/src}/lib/command-flags.ts | 0 .../cli-core/src}/lib/connector-api.ts | 0 .../cli-core/src}/lib/constants.ts | 0 .../cli-core/src}/lib/durable-file.ts | 0 .../cli-core/src}/lib/duration.ts | 0 .../cli-core/src}/lib/dust-balancing-plan.ts | 0 .../src}/lib/dust-registration-plan.ts | 0 .../cli-core/src}/lib/dust-wait.ts | 0 {src => packages/cli-core/src}/lib/engine.ts | 0 .../cli-core/src}/lib/error-trim.ts | 0 {src => packages/cli-core/src}/lib/errors.ts | 0 .../cli-core/src}/lib/exec-program.ts | 0 .../cli-core/src}/lib/exit-codes.ts | 0 .../cli-core/src}/lib/fee-limits.ts | 0 .../cli-core/src}/lib/json-output.ts | 0 .../cli-core/src}/lib/keystore.ts | 0 .../cli-core/src}/lib/network-id.ts | 0 {src => packages/cli-core/src}/lib/network.ts | 0 {src => packages/cli-core/src}/lib/notices.ts | 0 {src => packages/cli-core/src}/lib/payer.ts | 0 .../cli-core/src}/lib/phase-tracker.ts | 0 .../cli-core/src}/lib/prompter.ts | 0 .../cli-core/src}/lib/reader-cache-files.ts | 0 .../cli-core/src}/lib/resolve-network.ts | 0 .../cli-core/src}/lib/sdk-errors.ts | 0 .../cli-core/src}/lib/sdk-warnings.ts | 0 .../cli-core/src}/lib/settings.ts | 0 .../cli-core/src}/lib/sign-data.ts | 0 {src => packages/cli-core/src}/lib/sleep.ts | 0 .../cli-core/src}/lib/state-root.ts | 0 .../cli-core/src}/lib/tx-serde.ts | 0 {src => packages/cli-core/src}/lib/verbose.ts | 0 .../cli-core/src}/lib/wallet-cache.ts | 0 {src => packages/cli-core/src}/ui/colors.ts | 0 {src => packages/cli-core/src}/ui/format.ts | 0 {src => packages/cli-core/src}/ui/spinner.ts | 0 .../cli-core/src}/ui/terminal-prompter.ts | 0 packages/cli-core/tsconfig.build.json | 19 ++++++++ scripts/behaviour-snapshot.mjs | 2 +- scripts/check-layering.d.mts | 5 +++ scripts/check-layering.mjs | 45 +++++++++++++++---- scripts/check-process-safety.mjs | 4 +- scripts/fresh-install-check.mjs | 16 ++++++- scripts/measure-preprod-dust.ts | 6 +-- src/__tests__/account-backup.test.ts | 4 +- src/__tests__/address-command.test.ts | 2 +- src/__tests__/agent-guidance.test.ts | 4 +- src/__tests__/airdrop-command.test.ts | 4 +- src/__tests__/approval.test.ts | 8 ++-- src/__tests__/argv.test.ts | 4 +- src/__tests__/balance-command.live.test.ts | 6 +-- src/__tests__/balance-command.test.ts | 4 +- src/__tests__/balance-subscription.test.ts | 2 +- src/__tests__/blockfrost.test.ts | 6 +-- src/__tests__/cache-indexer.test.ts | 2 +- src/__tests__/call-context.test.ts | 12 ++--- src/__tests__/chain-clock.test.ts | 2 +- src/__tests__/chain-reset-clearing.test.ts | 6 +-- src/__tests__/cli-config.test.ts | 2 +- src/__tests__/colors.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 8 ++-- src/__tests__/command-flags.test.ts | 21 +++++---- src/__tests__/command-registry.test.ts | 41 +++++++++-------- src/__tests__/config-command.test.ts | 6 +-- src/__tests__/contract-deploy.test.ts | 10 ++--- src/__tests__/contract-request.test.ts | 4 +- .../contract-runner-endpoints.test.ts | 6 +-- src/__tests__/contract-runner.test.ts | 6 +-- .../contract-script-packages.test.ts | 2 +- src/__tests__/contract-validate.test.ts | 2 +- src/__tests__/dapp-connector.test.ts | 16 +++---- src/__tests__/derive-address.test.ts | 2 +- src/__tests__/device-code.test.ts | 2 +- src/__tests__/dust-balancing-plan.test.ts | 2 +- src/__tests__/dust-command.test.ts | 2 +- src/__tests__/dust-direct-cache.test.ts | 2 +- src/__tests__/dust-export.test.ts | 2 +- src/__tests__/dust-logic.test.ts | 2 +- src/__tests__/dust-registration-plan.test.ts | 6 +-- src/__tests__/dust-wait.test.ts | 4 +- src/__tests__/dust-wallet.test.ts | 2 +- src/__tests__/endpoint-check.test.ts | 2 +- src/__tests__/endpoint-refusals.test.ts | 2 +- src/__tests__/engine.test.ts | 4 +- src/__tests__/error-trim.test.ts | 2 +- src/__tests__/exec-program.test.ts | 4 +- src/__tests__/exit-codes.test.ts | 8 ++-- src/__tests__/facade.test.ts | 4 +- src/__tests__/fee-limits.test.ts | 4 +- src/__tests__/format.test.ts | 2 +- src/__tests__/generate-command.test.ts | 2 +- src/__tests__/genesis-address-command.test.ts | 2 +- src/__tests__/grant-account.test.ts | 4 +- src/__tests__/grant-deploy-cost.test.ts | 2 +- src/__tests__/grant-owner-commands.test.ts | 2 +- src/__tests__/grant-prepare.test.ts | 4 +- src/__tests__/grant-request.test.ts | 4 +- src/__tests__/graphql-ws-subscription.test.ts | 2 +- src/__tests__/heap-guard.test.ts | 2 +- src/__tests__/help-agent.test.ts | 4 +- src/__tests__/help.test.ts | 2 +- src/__tests__/helpers/cli-call.ts | 6 +-- src/__tests__/helpers/dust-balancing-case.ts | 2 +- src/__tests__/helpers/offline-facade.ts | 2 +- src/__tests__/helpers/own-call.ts | 2 +- src/__tests__/helpers/plain-wallet.ts | 4 +- src/__tests__/helpers/shell-settings.ts | 8 ++-- src/__tests__/helpers/stand-in-indexer.ts | 2 +- src/__tests__/helpers/state-root-in.ts | 2 +- src/__tests__/info-command.test.ts | 2 +- src/__tests__/inspect-cost-command.test.ts | 2 +- src/__tests__/json-fields.test.ts | 4 +- src/__tests__/json-output.test.ts | 10 ++--- src/__tests__/keystore.test.ts | 2 +- src/__tests__/ledger-guard.test.ts | 2 +- src/__tests__/local-stacks.test.ts | 18 ++++---- src/__tests__/localnet-cancellation.test.ts | 6 +-- src/__tests__/localnet-command.test.ts | 4 +- src/__tests__/localnet-docker-probe.test.ts | 2 +- src/__tests__/manual-command.test.ts | 2 +- src/__tests__/mcp-registry-tools.test.ts | 6 +-- .../mcp-server-concurrent-calls.test.ts | 2 +- src/__tests__/mcp-server.test.ts | 2 +- src/__tests__/multi-wallet.test.ts | 4 +- src/__tests__/network-cancellation.test.ts | 4 +- src/__tests__/network-id.test.ts | 6 +-- src/__tests__/network.test.ts | 2 +- src/__tests__/node-version.test.ts | 2 +- src/__tests__/notices.test.ts | 2 +- src/__tests__/passphrase.test.ts | 6 +-- src/__tests__/payer.test.ts | 12 ++--- src/__tests__/phase-tracker.test.ts | 2 +- .../prep-runner-cancellation.test.ts | 4 +- src/__tests__/protect-account.test.ts | 2 +- src/__tests__/read-cancellation.test.ts | 4 +- src/__tests__/resolve-network.test.ts | 6 +-- src/__tests__/run-command.test.ts | 10 ++--- src/__tests__/sdk-errors.test.ts | 6 +-- src/__tests__/sdk-free-base.test.ts | 4 +- src/__tests__/sdk-warnings.test.ts | 2 +- src/__tests__/sealed-account.test.ts | 2 +- src/__tests__/sealed-wallet.test.ts | 4 +- src/__tests__/seed-resolver.test.ts | 2 +- src/__tests__/serve-command.test.ts | 6 +-- src/__tests__/serve-manager.test.ts | 2 +- src/__tests__/settings.test.ts | 6 +-- src/__tests__/shielded-direct-cache.test.ts | 2 +- src/__tests__/sign-data.test.ts | 2 +- src/__tests__/sleep.test.ts | 4 +- src/__tests__/state-root.test.ts | 14 +++--- src/__tests__/terminal-prompter.test.ts | 6 +-- src/__tests__/transfer-command.test.ts | 4 +- src/__tests__/transfer-lib.test.ts | 10 ++--- src/__tests__/transfer-request.test.ts | 8 ++-- src/__tests__/tx-serde.test.ts | 2 +- src/__tests__/verbose-per-call.test.ts | 8 ++-- src/__tests__/verbose.test.ts | 2 +- src/__tests__/wallet-cache.test.ts | 4 +- src/__tests__/wallet-config.test.ts | 2 +- src/__tests__/wallet-data-repository.test.ts | 2 +- src/__tests__/wallet-protect.test.ts | 2 +- .../wallet-state-to-restore.live.test.ts | 6 +-- src/commands/address.definition.ts | 2 +- src/commands/address.ts | 12 ++--- src/commands/airdrop.definition.ts | 2 +- src/commands/airdrop.ts | 20 ++++----- src/commands/balance.definition.ts | 2 +- src/commands/balance.ts | 18 ++++---- src/commands/cache.definition.ts | 2 +- src/commands/cache.ts | 16 +++---- src/commands/chain.guidance.ts | 2 +- src/commands/connect.guidance.ts | 2 +- src/commands/contract.definition.ts | 2 +- src/commands/contract.guidance.ts | 2 +- src/commands/contract.ts | 18 ++++---- src/commands/dev.definition.ts | 2 +- src/commands/dev.guidance.ts | 2 +- src/commands/dev.ts | 10 ++--- src/commands/dust.definition.ts | 2 +- src/commands/dust.ts | 16 +++---- src/commands/generate.definition.ts | 2 +- src/commands/generate.ts | 14 +++--- src/commands/genesis-address.definition.ts | 2 +- src/commands/genesis-address.ts | 14 +++--- src/commands/grant.definition.ts | 2 +- src/commands/grant.guidance.ts | 2 +- src/commands/grant.ts | 18 ++++---- src/commands/help.definition.ts | 2 +- src/commands/help.ts | 12 ++--- src/commands/info.definition.ts | 2 +- src/commands/info.ts | 12 ++--- src/commands/inspect-cost.definition.ts | 2 +- src/commands/inspect-cost.ts | 12 ++--- src/commands/localnet.definition.ts | 2 +- src/commands/localnet.ts | 18 ++++---- src/commands/manual.definition.ts | 2 +- src/commands/manual.ts | 6 +-- src/commands/serve.definition.ts | 2 +- src/commands/serve.ts | 28 ++++++------ src/commands/status.definition.ts | 2 +- src/commands/status.ts | 20 ++++----- src/commands/test.definition.ts | 2 +- src/commands/test.ts | 16 +++---- src/commands/transfer.definition.ts | 2 +- src/commands/transfer.ts | 18 ++++---- src/commands/wallet.definition.ts | 2 +- src/commands/wallet.guidance.ts | 2 +- src/commands/wallet.ts | 14 +++--- src/engine/rc/addresses.ts | 4 +- src/engine/rc/airdrop.ts | 6 +-- src/engine/rc/contract-providers.ts | 6 +-- src/engine/rc/contract-scripts.ts | 4 +- src/engine/rc/dapp-connector.ts | 40 ++++++++--------- src/engine/rc/derive-address.ts | 4 +- src/engine/rc/dust-balance-direct.ts | 2 +- src/engine/rc/dust-direct-cache.ts | 4 +- src/engine/rc/dust-direct.ts | 4 +- src/engine/rc/dust-export.ts | 8 ++-- src/engine/rc/dust-register.ts | 12 ++--- src/engine/rc/dust-sync-native.ts | 12 ++--- src/engine/rc/dust-wallet.ts | 4 +- src/engine/rc/facade.ts | 14 +++--- src/engine/rc/index.ts | 2 +- src/engine/rc/ledger-parameters.ts | 2 +- src/engine/rc/raw-state.ts | 2 +- src/engine/rc/shielded-direct-cache.ts | 10 ++--- src/engine/rc/transfer.ts | 30 ++++++------- src/engine/rc/tx-inspect.ts | 2 +- src/engine/rc/wallet-data-repository.ts | 20 ++++----- src/engine/rc/wallet.ts | 14 +++--- src/lib/agent-manual.ts | 4 +- src/lib/balance-subscription.ts | 10 ++--- src/lib/chain-caches.ts | 8 ++-- src/lib/chain-clock.ts | 2 +- src/lib/chain-id.ts | 2 +- src/lib/cli-host.ts | 12 ++--- src/lib/command-dispatch.ts | 14 +++--- src/lib/contract/call.ts | 6 +-- src/lib/contract/deploy.ts | 6 +-- src/lib/contract/request.ts | 4 +- src/lib/contract/runner.ts | 8 ++-- src/lib/contract/served-wallet.ts | 8 ++-- src/lib/contract/validate.ts | 2 +- src/lib/dev/deploy.ts | 8 ++-- src/lib/dev/localnet-ready.ts | 2 +- src/lib/dev/provision-wallets.ts | 10 ++--- src/lib/endpoint-check.ts | 4 +- src/lib/grant/account-backup.ts | 8 ++-- src/lib/grant/account-records.ts | 4 +- src/lib/grant/account.ts | 10 ++--- src/lib/grant/deploy-cost.ts | 2 +- src/lib/grant/device-code.ts | 2 +- src/lib/grant/fee-wallet.ts | 8 ++-- src/lib/grant/owner-commands.ts | 2 +- src/lib/grant/prepare.ts | 6 +-- src/lib/grant/protect-account.ts | 2 +- src/lib/grant/request.ts | 6 +-- src/lib/grant/sealed-account.ts | 8 ++-- src/lib/graphql-ws-subscription.ts | 4 +- src/lib/heap-guard.ts | 2 +- src/lib/indexer-graphql.ts | 4 +- src/lib/indexer-ready.ts | 4 +- src/lib/installed-commands.ts | 6 +-- src/lib/installed-engines.ts | 2 +- src/lib/ledger-guard.ts | 6 +-- src/lib/localnet.ts | 10 ++--- src/lib/mcp/known-params.ts | 2 +- src/lib/mcp/registry-tools.ts | 6 +-- src/lib/mcp/skills.ts | 4 +- src/lib/node-ready.ts | 4 +- src/lib/node-rpc.ts | 4 +- src/lib/output-redaction.ts | 2 +- src/lib/passphrase.ts | 12 ++--- src/lib/proof-server-ready.ts | 4 +- src/lib/readme-commands.ts | 2 +- src/lib/run-command.ts | 10 ++--- src/lib/sdk-noise.ts | 2 +- src/lib/seed-resolver.ts | 6 +-- src/lib/serve-manager.ts | 14 +++--- src/lib/serve-payer.ts | 10 ++--- src/lib/shielded-policy.ts | 2 +- src/lib/test/actions-runner.ts | 2 +- src/lib/test/ai-scaffold.ts | 2 +- src/lib/test/browser-test.ts | 2 +- src/lib/test/prep-runner.ts | 12 ++--- src/lib/test/types.ts | 2 +- src/lib/transfer-request.ts | 12 ++--- src/lib/wallet-can-pay.ts | 14 +++--- src/lib/wallet-config.ts | 18 ++++---- src/lib/wallet-create.ts | 4 +- src/lib/wallet-paths.ts | 6 +-- src/lib/wallet-protector.ts | 4 +- src/lib/ws-rpc.ts | 6 +-- src/mcp-server.ts | 8 ++-- src/ui/animate.ts | 2 +- src/ui/dev-keys.ts | 2 +- src/ui/test-create-prompt.ts | 2 +- src/wallet.ts | 20 ++++----- tsconfig.json | 4 +- vitest.config.ts | 5 ++- vitest.live.config.ts | 1 + 316 files changed, 910 insertions(+), 787 deletions(-) create mode 100644 packages/cli-core/package.json rename {src => packages/cli-core/src}/commands/config.definition.ts (100%) rename {src => packages/cli-core/src}/commands/config.ts (100%) rename {src => packages/cli-core/src}/commands/core.guidance.ts (100%) rename {src => packages/cli-core/src}/lib/agent-guidance.ts (100%) rename {src => packages/cli-core/src}/lib/amount.ts (100%) rename {src => packages/cli-core/src}/lib/approval.ts (100%) rename {src => packages/cli-core/src}/lib/argv.ts (100%) rename {src => packages/cli-core/src}/lib/blockfrost.ts (100%) rename {src => packages/cli-core/src}/lib/cache-indexer.ts (100%) rename {src => packages/cli-core/src}/lib/call-context.ts (100%) rename {src => packages/cli-core/src}/lib/cli-config.ts (100%) rename {src => packages/cli-core/src}/lib/command-definition.ts (100%) rename {src => packages/cli-core/src}/lib/command-flags.ts (100%) rename {src => packages/cli-core/src}/lib/connector-api.ts (100%) rename {src => packages/cli-core/src}/lib/constants.ts (100%) rename {src => packages/cli-core/src}/lib/durable-file.ts (100%) rename {src => packages/cli-core/src}/lib/duration.ts (100%) rename {src => packages/cli-core/src}/lib/dust-balancing-plan.ts (100%) rename {src => packages/cli-core/src}/lib/dust-registration-plan.ts (100%) rename {src => packages/cli-core/src}/lib/dust-wait.ts (100%) rename {src => packages/cli-core/src}/lib/engine.ts (100%) rename {src => packages/cli-core/src}/lib/error-trim.ts (100%) rename {src => packages/cli-core/src}/lib/errors.ts (100%) rename {src => packages/cli-core/src}/lib/exec-program.ts (100%) rename {src => packages/cli-core/src}/lib/exit-codes.ts (100%) rename {src => packages/cli-core/src}/lib/fee-limits.ts (100%) rename {src => packages/cli-core/src}/lib/json-output.ts (100%) rename {src => packages/cli-core/src}/lib/keystore.ts (100%) rename {src => packages/cli-core/src}/lib/network-id.ts (100%) rename {src => packages/cli-core/src}/lib/network.ts (100%) rename {src => packages/cli-core/src}/lib/notices.ts (100%) rename {src => packages/cli-core/src}/lib/payer.ts (100%) rename {src => packages/cli-core/src}/lib/phase-tracker.ts (100%) rename {src => packages/cli-core/src}/lib/prompter.ts (100%) rename {src => packages/cli-core/src}/lib/reader-cache-files.ts (100%) rename {src => packages/cli-core/src}/lib/resolve-network.ts (100%) rename {src => packages/cli-core/src}/lib/sdk-errors.ts (100%) rename {src => packages/cli-core/src}/lib/sdk-warnings.ts (100%) rename {src => packages/cli-core/src}/lib/settings.ts (100%) rename {src => packages/cli-core/src}/lib/sign-data.ts (100%) rename {src => packages/cli-core/src}/lib/sleep.ts (100%) rename {src => packages/cli-core/src}/lib/state-root.ts (100%) rename {src => packages/cli-core/src}/lib/tx-serde.ts (100%) rename {src => packages/cli-core/src}/lib/verbose.ts (100%) rename {src => packages/cli-core/src}/lib/wallet-cache.ts (100%) rename {src => packages/cli-core/src}/ui/colors.ts (100%) rename {src => packages/cli-core/src}/ui/format.ts (100%) rename {src => packages/cli-core/src}/ui/spinner.ts (100%) rename {src => packages/cli-core/src}/ui/terminal-prompter.ts (100%) create mode 100644 packages/cli-core/tsconfig.build.json diff --git a/package-lock.json b/package-lock.json index 450b19c9..7456892c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,11 +9,13 @@ "version": "0.6.0-rc.10", "license": "Apache-2.0", "workspaces": [ - "packages/connector" + "packages/connector", + "packages/cli-core" ], "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", @@ -674,6 +676,10 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@kuiralabs/midnight-cli-core": { + "resolved": "packages/cli-core", + "link": true + }, "node_modules/@midnight-ntwrk/compact-js": { "version": "3.0.0-rc.3", "resolved": "https://registry.npmjs.org/@midnight-ntwrk/compact-js/-/compact-js-3.0.0-rc.3.tgz", @@ -5693,6 +5699,14 @@ "zod": "^3.25 || ^4" } }, + "packages/cli-core": { + "name": "@kuiralabs/midnight-cli-core", + "version": "0.1.0-rc.0", + "license": "Apache-2.0", + "engines": { + "node": ">=22" + } + }, "packages/connector": { "name": "midnight-wallet-connector", "version": "0.0.6", diff --git a/package.json b/package.json index 3d545bbe..583058b3 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,8 @@ "ai-agent" ], "workspaces": [ - "packages/connector" + "packages/connector", + "packages/cli-core" ], "bin": { "midnight": "dist/wallet.js", @@ -44,21 +45,22 @@ "bun": ">=1.3.0" }, "scripts": { - "wallet": "tsx src/wallet.ts", - "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", - "mcp": "tsx src/mcp-server.ts", + "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", + "build": "npm run build -w @kuiralabs/midnight-cli-core && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", "test": "vitest run", "test:live": "vitest run --config vitest.live.config.ts", "test:watch": "vitest", "typecheck": "tsc --noEmit", - "skill-docs": "tsx scripts/write-skill-docs.ts", - "readme-commands": "tsx scripts/write-readme-commands.ts" + "skill-docs": "tsx --conditions=midnight-cli-source scripts/write-skill-docs.ts", + "readme-commands": "tsx --conditions=midnight-cli-source scripts/write-readme-commands.ts" }, "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", diff --git a/packages/cli-core/package.json b/packages/cli-core/package.json new file mode 100644 index 00000000..fca327ea --- /dev/null +++ b/packages/cli-core/package.json @@ -0,0 +1,32 @@ +{ + "name": "@kuiralabs/midnight-cli-core", + "version": "0.1.0-rc.0", + "type": "module", + "description": "The base of the Midnight CLI packages: arguments, typed errors and exit codes, JSON output, config, the state root, network endpoints, terminal formatting, the command registry contract, the payer and the SDK engine interface", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/cli-core" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + "./*": { + "midnight-cli-source": "./src/*.ts", + "types": "./dist/*.d.ts", + "default": "./dist/*.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + } +} diff --git a/src/commands/config.definition.ts b/packages/cli-core/src/commands/config.definition.ts similarity index 100% rename from src/commands/config.definition.ts rename to packages/cli-core/src/commands/config.definition.ts diff --git a/src/commands/config.ts b/packages/cli-core/src/commands/config.ts similarity index 100% rename from src/commands/config.ts rename to packages/cli-core/src/commands/config.ts diff --git a/src/commands/core.guidance.ts b/packages/cli-core/src/commands/core.guidance.ts similarity index 100% rename from src/commands/core.guidance.ts rename to packages/cli-core/src/commands/core.guidance.ts diff --git a/src/lib/agent-guidance.ts b/packages/cli-core/src/lib/agent-guidance.ts similarity index 100% rename from src/lib/agent-guidance.ts rename to packages/cli-core/src/lib/agent-guidance.ts diff --git a/src/lib/amount.ts b/packages/cli-core/src/lib/amount.ts similarity index 100% rename from src/lib/amount.ts rename to packages/cli-core/src/lib/amount.ts diff --git a/src/lib/approval.ts b/packages/cli-core/src/lib/approval.ts similarity index 100% rename from src/lib/approval.ts rename to packages/cli-core/src/lib/approval.ts diff --git a/src/lib/argv.ts b/packages/cli-core/src/lib/argv.ts similarity index 100% rename from src/lib/argv.ts rename to packages/cli-core/src/lib/argv.ts diff --git a/src/lib/blockfrost.ts b/packages/cli-core/src/lib/blockfrost.ts similarity index 100% rename from src/lib/blockfrost.ts rename to packages/cli-core/src/lib/blockfrost.ts diff --git a/src/lib/cache-indexer.ts b/packages/cli-core/src/lib/cache-indexer.ts similarity index 100% rename from src/lib/cache-indexer.ts rename to packages/cli-core/src/lib/cache-indexer.ts diff --git a/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts similarity index 100% rename from src/lib/call-context.ts rename to packages/cli-core/src/lib/call-context.ts diff --git a/src/lib/cli-config.ts b/packages/cli-core/src/lib/cli-config.ts similarity index 100% rename from src/lib/cli-config.ts rename to packages/cli-core/src/lib/cli-config.ts diff --git a/src/lib/command-definition.ts b/packages/cli-core/src/lib/command-definition.ts similarity index 100% rename from src/lib/command-definition.ts rename to packages/cli-core/src/lib/command-definition.ts diff --git a/src/lib/command-flags.ts b/packages/cli-core/src/lib/command-flags.ts similarity index 100% rename from src/lib/command-flags.ts rename to packages/cli-core/src/lib/command-flags.ts diff --git a/src/lib/connector-api.ts b/packages/cli-core/src/lib/connector-api.ts similarity index 100% rename from src/lib/connector-api.ts rename to packages/cli-core/src/lib/connector-api.ts diff --git a/src/lib/constants.ts b/packages/cli-core/src/lib/constants.ts similarity index 100% rename from src/lib/constants.ts rename to packages/cli-core/src/lib/constants.ts diff --git a/src/lib/durable-file.ts b/packages/cli-core/src/lib/durable-file.ts similarity index 100% rename from src/lib/durable-file.ts rename to packages/cli-core/src/lib/durable-file.ts diff --git a/src/lib/duration.ts b/packages/cli-core/src/lib/duration.ts similarity index 100% rename from src/lib/duration.ts rename to packages/cli-core/src/lib/duration.ts diff --git a/src/lib/dust-balancing-plan.ts b/packages/cli-core/src/lib/dust-balancing-plan.ts similarity index 100% rename from src/lib/dust-balancing-plan.ts rename to packages/cli-core/src/lib/dust-balancing-plan.ts diff --git a/src/lib/dust-registration-plan.ts b/packages/cli-core/src/lib/dust-registration-plan.ts similarity index 100% rename from src/lib/dust-registration-plan.ts rename to packages/cli-core/src/lib/dust-registration-plan.ts diff --git a/src/lib/dust-wait.ts b/packages/cli-core/src/lib/dust-wait.ts similarity index 100% rename from src/lib/dust-wait.ts rename to packages/cli-core/src/lib/dust-wait.ts diff --git a/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts similarity index 100% rename from src/lib/engine.ts rename to packages/cli-core/src/lib/engine.ts diff --git a/src/lib/error-trim.ts b/packages/cli-core/src/lib/error-trim.ts similarity index 100% rename from src/lib/error-trim.ts rename to packages/cli-core/src/lib/error-trim.ts diff --git a/src/lib/errors.ts b/packages/cli-core/src/lib/errors.ts similarity index 100% rename from src/lib/errors.ts rename to packages/cli-core/src/lib/errors.ts diff --git a/src/lib/exec-program.ts b/packages/cli-core/src/lib/exec-program.ts similarity index 100% rename from src/lib/exec-program.ts rename to packages/cli-core/src/lib/exec-program.ts diff --git a/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts similarity index 100% rename from src/lib/exit-codes.ts rename to packages/cli-core/src/lib/exit-codes.ts diff --git a/src/lib/fee-limits.ts b/packages/cli-core/src/lib/fee-limits.ts similarity index 100% rename from src/lib/fee-limits.ts rename to packages/cli-core/src/lib/fee-limits.ts diff --git a/src/lib/json-output.ts b/packages/cli-core/src/lib/json-output.ts similarity index 100% rename from src/lib/json-output.ts rename to packages/cli-core/src/lib/json-output.ts diff --git a/src/lib/keystore.ts b/packages/cli-core/src/lib/keystore.ts similarity index 100% rename from src/lib/keystore.ts rename to packages/cli-core/src/lib/keystore.ts diff --git a/src/lib/network-id.ts b/packages/cli-core/src/lib/network-id.ts similarity index 100% rename from src/lib/network-id.ts rename to packages/cli-core/src/lib/network-id.ts diff --git a/src/lib/network.ts b/packages/cli-core/src/lib/network.ts similarity index 100% rename from src/lib/network.ts rename to packages/cli-core/src/lib/network.ts diff --git a/src/lib/notices.ts b/packages/cli-core/src/lib/notices.ts similarity index 100% rename from src/lib/notices.ts rename to packages/cli-core/src/lib/notices.ts diff --git a/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts similarity index 100% rename from src/lib/payer.ts rename to packages/cli-core/src/lib/payer.ts diff --git a/src/lib/phase-tracker.ts b/packages/cli-core/src/lib/phase-tracker.ts similarity index 100% rename from src/lib/phase-tracker.ts rename to packages/cli-core/src/lib/phase-tracker.ts diff --git a/src/lib/prompter.ts b/packages/cli-core/src/lib/prompter.ts similarity index 100% rename from src/lib/prompter.ts rename to packages/cli-core/src/lib/prompter.ts diff --git a/src/lib/reader-cache-files.ts b/packages/cli-core/src/lib/reader-cache-files.ts similarity index 100% rename from src/lib/reader-cache-files.ts rename to packages/cli-core/src/lib/reader-cache-files.ts diff --git a/src/lib/resolve-network.ts b/packages/cli-core/src/lib/resolve-network.ts similarity index 100% rename from src/lib/resolve-network.ts rename to packages/cli-core/src/lib/resolve-network.ts diff --git a/src/lib/sdk-errors.ts b/packages/cli-core/src/lib/sdk-errors.ts similarity index 100% rename from src/lib/sdk-errors.ts rename to packages/cli-core/src/lib/sdk-errors.ts diff --git a/src/lib/sdk-warnings.ts b/packages/cli-core/src/lib/sdk-warnings.ts similarity index 100% rename from src/lib/sdk-warnings.ts rename to packages/cli-core/src/lib/sdk-warnings.ts diff --git a/src/lib/settings.ts b/packages/cli-core/src/lib/settings.ts similarity index 100% rename from src/lib/settings.ts rename to packages/cli-core/src/lib/settings.ts diff --git a/src/lib/sign-data.ts b/packages/cli-core/src/lib/sign-data.ts similarity index 100% rename from src/lib/sign-data.ts rename to packages/cli-core/src/lib/sign-data.ts diff --git a/src/lib/sleep.ts b/packages/cli-core/src/lib/sleep.ts similarity index 100% rename from src/lib/sleep.ts rename to packages/cli-core/src/lib/sleep.ts diff --git a/src/lib/state-root.ts b/packages/cli-core/src/lib/state-root.ts similarity index 100% rename from src/lib/state-root.ts rename to packages/cli-core/src/lib/state-root.ts diff --git a/src/lib/tx-serde.ts b/packages/cli-core/src/lib/tx-serde.ts similarity index 100% rename from src/lib/tx-serde.ts rename to packages/cli-core/src/lib/tx-serde.ts diff --git a/src/lib/verbose.ts b/packages/cli-core/src/lib/verbose.ts similarity index 100% rename from src/lib/verbose.ts rename to packages/cli-core/src/lib/verbose.ts diff --git a/src/lib/wallet-cache.ts b/packages/cli-core/src/lib/wallet-cache.ts similarity index 100% rename from src/lib/wallet-cache.ts rename to packages/cli-core/src/lib/wallet-cache.ts diff --git a/src/ui/colors.ts b/packages/cli-core/src/ui/colors.ts similarity index 100% rename from src/ui/colors.ts rename to packages/cli-core/src/ui/colors.ts diff --git a/src/ui/format.ts b/packages/cli-core/src/ui/format.ts similarity index 100% rename from src/ui/format.ts rename to packages/cli-core/src/ui/format.ts diff --git a/src/ui/spinner.ts b/packages/cli-core/src/ui/spinner.ts similarity index 100% rename from src/ui/spinner.ts rename to packages/cli-core/src/ui/spinner.ts diff --git a/src/ui/terminal-prompter.ts b/packages/cli-core/src/ui/terminal-prompter.ts similarity index 100% rename from src/ui/terminal-prompter.ts rename to packages/cli-core/src/ui/terminal-prompter.ts diff --git a/packages/cli-core/tsconfig.build.json b/packages/cli-core/tsconfig.build.json new file mode 100644 index 00000000..cb6aadd5 --- /dev/null +++ b/packages/cli-core/tsconfig.build.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": ["ES2022"], + "moduleResolution": "bundler", + "customConditions": ["midnight-cli-source"], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": ["node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/scripts/behaviour-snapshot.mjs b/scripts/behaviour-snapshot.mjs index 8fe60ecf..7bb23d60 100644 --- a/scripts/behaviour-snapshot.mjs +++ b/scripts/behaviour-snapshot.mjs @@ -162,7 +162,7 @@ function sdkLoads(home) { "import { appendFileSync } from 'node:fs';", `const log = ${JSON.stringify(log)};`, 'export async function resolve(specifier, context, next) {', - ' const m = specifier.match(/^(@midnight(?:-ntwrk|ntwrk)\\/[^/]+|@kuiralabs\\/[^/]+)/);', + ' const m = specifier.match(/^(@midnight(?:-ntwrk|ntwrk)\\/[^/]+|@kuiralabs\\/midnight-account[^/]*)/);', " if (m) appendFileSync(log, m[1] + '\\n');", ' return next(specifier, context);', '}', diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 68074d49..046be4fb 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -4,3 +4,8 @@ export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; export function importRule(fromRel: string, toRel: string): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; + +/** The workspace packages carved out of src/: their names and source folders. */ +export const WORKSPACE_PACKAGES: readonly { name: string; dir: string }[]; +/** A file's path as the homes read it: under its package's source folder, or under src/. */ +export function relOf(file: string): string; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 7e2a7773..64118e08 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -104,7 +104,27 @@ const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; // import ... from 'x', export ... from 'x', import 'x', import('x'). const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; -export function sourceFiles(dir = SRC) { +// The workspace packages carved out of src/, each with its source folder and +// the home it is. A file's path in a package (lib/argv.ts) reads as it did +// under src/, so the homes and rules above apply to it unchanged. +export const WORKSPACE_PACKAGES = [ + { name: '@kuiralabs/midnight-cli-core', dir: join(ROOT, 'packages', 'cli-core', 'src') }, +]; + +/** The package source folder a file is in, or undefined for one under src/. */ +const packageOf = (file) => WORKSPACE_PACKAGES.find((pkg) => file.startsWith(pkg.dir + '/')); + +/** A file's path as the homes read it: under its package's source folder, or under src/. */ +export function relOf(file) { + return relative(packageOf(file)?.dir ?? SRC, file); +} + +/** Where a file is, for a report: from the repository's root. */ +const shown = (file) => relative(ROOT, file); + +/** The source files of src/ and of every workspace package, tests left out; or those under `dir`. */ +export function sourceFiles(dir) { + if (dir === undefined) return [SRC, ...WORKSPACE_PACKAGES.map((pkg) => pkg.dir)].flatMap((d) => sourceFiles(d)); const files = []; for (const name of readdirSync(dir)) { const path = join(dir, name); @@ -118,7 +138,7 @@ export function sourceFiles(dir = SRC) { } export function homeOf(file) { - const rel = relative(SRC, file); + const rel = relOf(file); return HOMES.find(([, pattern]) => pattern.test(rel))?.[0]; } @@ -173,17 +193,24 @@ function importsOf(file) { export function findLayeringProblems() { const unhomed = []; const violations = []; - for (const file of sourceFiles(SRC)) { - const rel = relative(SRC, file); + for (const file of sourceFiles()) { + const rel = relOf(file); const home = homeOf(file); if (home === undefined) { - unhomed.push(rel); + unhomed.push(shown(file)); continue; } for (const { specifier, line } of importsOf(file)) { - const where = `src/${rel}:${line}`; - if (specifier.startsWith('.')) { - const rule = importRule(rel, relative(SRC, resolve(dirname(file), specifier))); + const where = `${shown(file)}:${line}`; + const pkg = WORKSPACE_PACKAGES.find((p) => specifier.startsWith(p.name + '/')); + const from = packageOf(file); + if (specifier.startsWith('.') && from !== undefined && packageOf(resolve(dirname(file), specifier)) !== from) { + violations.push({ home, rule: `${home} package → outside it (a package imports another only by name)`, where, specifier }); + continue; + } + if (specifier.startsWith('.') || pkg !== undefined) { + const target = pkg !== undefined ? `${specifier.slice(pkg.name.length + 1)}.ts` : relOf(resolve(dirname(file), specifier)); + const rule = importRule(rel, target); if (rule !== undefined) violations.push({ home, rule, where, specifier }); } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine') { violations.push({ home, rule: `${home} → Midnight SDK (only an engine imports it)`, where, specifier }); @@ -196,7 +223,7 @@ export function findLayeringProblems() { } function report({ unhomed, violations }) { - for (const rel of unhomed) process.stdout.write(`no package: src/${rel}\n`); + for (const file of unhomed) process.stdout.write(`no package: ${file}\n`); const byRule = (list) => { const groups = new Map(); diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 3c615c29..6a09e813 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -27,7 +27,7 @@ import { readFileSync } from 'node:fs'; import { relative, resolve, dirname, join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { homeOf, sourceFiles } from './check-layering.mjs'; +import { homeOf, relOf, sourceFiles } from './check-layering.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const SRC = join(ROOT, 'src'); @@ -262,7 +262,7 @@ const isCommand = (rel) => rel.startsWith('commands/'); export function findViolations(files = sourceFiles(), allowed = ALLOWED, allowedState = ALLOWED_STATE, src = SRC) { const found = []; for (const file of files) { - const rel = relative(src, file); + const rel = src === SRC ? relOf(file) : relative(src, file); const source = readFileSync(file, 'utf8'); const code = codeOnly(source); const lines = code.split('\n'); diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 7263b090..0bc7493f 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -92,13 +92,27 @@ const check = (what, ok, detail = '') => { const work = mkdtempSync(join(tmpdir(), 'mn-fresh-install-')); try { const tarball = run('npm', ['pack', '--pack-destination', work], repo).trim().split('\n').pop(); + // The workspace packages mn depends on, packed from this checkout too (until + // they are published, a consumer's npm finds them nowhere else), and + // installed beside it so they satisfy its dependencies. + const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); + const workspaceTarballs = manifest.workspaces + .map((dir) => ({ dir, name: JSON.parse(readFileSync(join(repo, dir, 'package.json'), 'utf-8')).name })) + .filter(({ name }) => manifest.dependencies[name] !== undefined) + .map(({ dir }) => run('npm', ['pack', '--pack-destination', work], join(repo, dir)).trim().split('\n').pop()); writeFileSync(join(work, 'package.json'), JSON.stringify({ name: 'fresh-install-check', private: true })); - run('npm', ['install', '--no-audit', '--no-fund', join(work, tarball)], work); + run('npm', ['install', '--no-audit', '--no-fund', ...workspaceTarballs.map((t) => join(work, t)), join(work, tarball)], work); const version = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')).version; const mn = join(work, 'node_modules', '.bin', 'mn'); check('the installed mn runs', run(mn, ['--version'], work).trim() === version, version); + // One copy of each workspace package: a second copy of core's module state (its settings, its typed errors) splits the process. + for (const tarball of workspaceTarballs) { + const name = JSON.parse(run('tar', ['-xOzf', join(work, tarball), 'package/package.json'], work)).name; + const copies = copiesOf(work, name); + check(`one copy of ${name}`, copies.length === 1, copies.join(', ')); + } // One copy each: an object made by one copy of a WASM package is refused by another. for (const name of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/ledger-v8', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { const copies = copiesOf(work, name); diff --git a/scripts/measure-preprod-dust.ts b/scripts/measure-preprod-dust.ts index ab999800..e11b3714 100644 --- a/scripts/measure-preprod-dust.ts +++ b/scripts/measure-preprod-dust.ts @@ -25,8 +25,8 @@ import { join } from 'node:path'; import { homedir } from 'node:os'; import { execSync } from 'node:child_process'; -import { WalletDataRepository, defaultRepository } from '../src/lib/wallet-data-repository.ts'; -import { getNetworkConfig, type NetworkName } from '../src/lib/network.ts'; +import { WalletDataRepository, defaultRepository } from '../src/engine/rc/wallet-data-repository.ts'; +import { getNetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { unlockWallet, resolveWalletPath } from '../src/lib/wallet-config.ts'; const WALLET = (process.env.WALLET ?? 'alice') as string; @@ -62,7 +62,7 @@ async function main() { // memo doesn't leak. Disk cache from #1 still present. const disk = Number(execSync( `npx tsx -e " - import('./src/lib/wallet-data-repository.ts').then(async (repo) => { + import('./src/engine/rc/wallet-data-repository.ts').then(async (repo) => { const { Buffer } = await import('node:buffer'); const { getNetworkConfig } = await import('./src/lib/network.ts'); const { unlockWallet, resolveWalletPath } = await import('./src/lib/wallet-config.ts'); diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index e065be2e..0dd9b277 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -13,9 +13,9 @@ import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { type FeeWallet, accountProviders, freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_ID } from '@kuiralabs/midnight-account-chain/contract'; -import { WrongPassphraseError } from '../lib/keystore.ts'; +import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig } from '../lib/network.ts'; +import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { exportAccount, importAccount } from '../lib/grant/account-backup.ts'; import { createPendingDevice, openAccountKey, ownDeviceCode, sealedDeviceList } from '../lib/grant/sealed-account.ts'; diff --git a/src/__tests__/address-command.test.ts b/src/__tests__/address-command.test.ts index 9d6ebf52..e74e1a26 100644 --- a/src/__tests__/address-command.test.ts +++ b/src/__tests__/address-command.test.ts @@ -3,7 +3,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import addressCommand from '../commands/address.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index 0c56d6d2..23551ce8 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -14,8 +14,8 @@ import { type CommandDefinition, type CommandPackage, type CommandRegistry, -} from '../lib/command-definition.ts'; -import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '../lib/agent-guidance.ts'; +} from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; import { AGENT_MANUAL_SECTIONS, TOOL_GROUPS, agentManual } from '../lib/agent-manual.ts'; import { SKILL_CORE_SECTIONS, SKILL_FULL_SECTIONS, skillCore, skillFull } from '../lib/mcp/skills.ts'; import { listedTools } from '../lib/mcp/registry-tools.ts'; diff --git a/src/__tests__/airdrop-command.test.ts b/src/__tests__/airdrop-command.test.ts index 96b5d3b9..e99ba27c 100644 --- a/src/__tests__/airdrop-command.test.ts +++ b/src/__tests__/airdrop-command.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import airdropCommand from '../commands/airdrop.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/approval.test.ts b/src/__tests__/approval.test.ts index 96b536ab..b9c6b78f 100644 --- a/src/__tests__/approval.test.ts +++ b/src/__tests__/approval.test.ts @@ -1,6 +1,6 @@ -import { createTerminalPrompter } from '../ui/terminal-prompter.ts'; -import { setPrompter } from '../lib/prompter.ts'; -import { setNoticeSink } from '../lib/notices.ts'; +import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; +import { setPrompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { PassThrough } from 'node:stream'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { @@ -11,7 +11,7 @@ import { promptApproval, type ApprovalOptions, type ApprovalRequest, -} from '../lib/approval.ts'; +} from '@kuiralabs/midnight-cli-core/lib/approval'; // Strip ANSI codes for content assertions const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ''); diff --git a/src/__tests__/argv.test.ts b/src/__tests__/argv.test.ts index 32740787..053115ff 100644 --- a/src/__tests__/argv.test.ts +++ b/src/__tests__/argv.test.ts @@ -1,6 +1,6 @@ -import { UsageError } from '../lib/errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { describe, it, expect } from 'vitest'; -import { parseArgs, getFlag, hasFlag, isVerbose, requireFlag, type ParsedArgs } from '../lib/argv.ts'; +import { parseArgs, getFlag, hasFlag, isVerbose, requireFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; describe('parseArgs', () => { it('parses command from first positional', () => { diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index bede333c..57f0a992 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; @@ -55,7 +55,7 @@ afterEach(() => { }); beforeAll(async () => { - const { resolveNetwork } = await import('../lib/resolve-network.ts'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); const { indexer } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']) }).config; const answered = await fetch(indexer, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: '{ block { height } }' }), signal: AbortSignal.timeout(5_000) }) .then((r) => r.ok, () => false); diff --git a/src/__tests__/balance-command.test.ts b/src/__tests__/balance-command.test.ts index 7f2f3f61..843b9622 100644 --- a/src/__tests__/balance-command.test.ts +++ b/src/__tests__/balance-command.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/balance-subscription.test.ts b/src/__tests__/balance-subscription.test.ts index 2ae1687d..8cceadf3 100644 --- a/src/__tests__/balance-subscription.test.ts +++ b/src/__tests__/balance-subscription.test.ts @@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; import { EventEmitter } from 'events'; -import { NATIVE_TOKEN_TYPE } from '../lib/constants.ts'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; type FakeWs = EventEmitter & { send: ReturnType; diff --git a/src/__tests__/blockfrost.test.ts b/src/__tests__/blockfrost.test.ts index 3d28d620..21c0a9d0 100644 --- a/src/__tests__/blockfrost.test.ts +++ b/src/__tests__/blockfrost.test.ts @@ -8,9 +8,9 @@ import { BlockfrostLimitError, BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, assertEndpointUsable, blockfrostEndpoints, checkProjectId, endpointRefusal, endpointRefusalFromWsError, isBlockfrostUrl, maskProjectId, mayHoldProjectId, networkOfProjectId, redactProjectId, usesBlockfrost, -} from '../lib/blockfrost.ts'; -import { UsageError } from '../lib/errors.ts'; -import { ERROR_CODES, EXIT_NETWORK_ERROR, classifyError } from '../lib/exit-codes.ts'; +} from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { ERROR_CODES, EXIT_NETWORK_ERROR, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const WITH_ID = blockfrostEndpoints('preprod', ID); diff --git a/src/__tests__/cache-indexer.test.ts b/src/__tests__/cache-indexer.test.ts index f028652c..1bf021d8 100644 --- a/src/__tests__/cache-indexer.test.ts +++ b/src/__tests__/cache-indexer.test.ts @@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { bindCachesToIndexer, describeIndexerChange, indexerIdentity } from '../lib/cache-indexer.ts'; +import { bindCachesToIndexer, describeIndexerChange, indexerIdentity } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; const BLOCKFROST = 'wss://midnight-preprod.blockfrost.io/api/v0/ws?project_id=nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const OLD_PREPROD = 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws'; diff --git a/src/__tests__/call-context.test.ts b/src/__tests__/call-context.test.ts index f0631fd4..f2678dce 100644 --- a/src/__tests__/call-context.test.ts +++ b/src/__tests__/call-context.test.ts @@ -11,12 +11,12 @@ import { createCallContext, runHandler, type CallContext, -} from '../lib/call-context.ts'; -import { CancelledError } from '../lib/errors.ts'; -import { parseArgs } from '../lib/argv.ts'; -import { hostPaths } from '../lib/state-root.ts'; -import { settings } from '../lib/settings.ts'; -import type { Payer } from '../lib/payer.ts'; +} from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { hostPaths } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; const recordingSink = () => { const seen: string[] = []; diff --git a/src/__tests__/chain-clock.test.ts b/src/__tests__/chain-clock.test.ts index 65fa4e43..2d2ee292 100644 --- a/src/__tests__/chain-clock.test.ts +++ b/src/__tests__/chain-clock.test.ts @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { ChainClockBehindError, CHAIN_CLOCK_TOLERANCE_MS, assertChainClockCurrent, fetchChainTime } from '../lib/chain-clock.ts'; -import { classifyError, EXIT_NETWORK_ERROR } from '../lib/exit-codes.ts'; +import { classifyError, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; const LAGGING_BLOCK = 1_791_116_964_002; // 2026-10-04T12:29:24.002Z diff --git a/src/__tests__/chain-reset-clearing.test.ts b/src/__tests__/chain-reset-clearing.test.ts index 9f89e99b..d335e4aa 100644 --- a/src/__tests__/chain-reset-clearing.test.ts +++ b/src/__tests__/chain-reset-clearing.test.ts @@ -7,9 +7,9 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { clearChainCaches } from '../lib/chain-caches.ts'; -import { getCachePath } from '../lib/wallet-cache.ts'; -import { getDustCachePath } from '../lib/reader-cache-files.ts'; -import { getShieldedCachePath } from '../lib/reader-cache-files.ts'; +import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; import { PRIVATE_STATE_DATABASE, clearDappPrivateState } from '../lib/contract/private-state.ts'; let dir: string; diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index 3df47c2c..572413d1 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -10,7 +10,7 @@ import { unsetConfigValue, getValidConfigKeys, getBlockfrostProjectId, -} from '../lib/cli-config.ts'; +} from '@kuiralabs/midnight-cli-core/lib/cli-config'; const TEST_DIR = path.join(os.tmpdir(), `midnight-cli-config-test-${process.pid}`); diff --git a/src/__tests__/colors.test.ts b/src/__tests__/colors.test.ts index d2bddc47..c2a1370f 100644 --- a/src/__tests__/colors.test.ts +++ b/src/__tests__/colors.test.ts @@ -6,7 +6,7 @@ import { midnightBlue, white, gray, TEAL, PURPLE, RED_CODE, GREEN_CODE, YELLOW_CODE, MIDNIGHT_BLUE, WHITE_CODE, DIM_GRAY, -} from '../ui/colors.ts'; +} from '@kuiralabs/midnight-cli-core/ui/colors'; const ESC = '\x1b['; const RESET = '\x1b[0m'; diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index b4ca31e1..6a46eba3 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -14,16 +14,16 @@ import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { Buffer } from 'node:buffer'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; -import { setPrompter, type Prompter } from '../lib/prompter.ts'; +import { setPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { establishPassphrase, isPassphraseSet } from '../lib/passphrase.ts'; import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; -import { getCachePath } from '../lib/wallet-cache.ts'; +import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { loadWalletConfig, protectAllWallets } from '../lib/wallet-config.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import type { WalletProtector } from '../lib/wallet-protector.ts'; -import type { CommandHandler } from '../lib/call-context.ts'; +import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import balanceCommand from '../commands/balance.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; import statusCommand from '../commands/status.ts'; diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 4a735771..dd38dedd 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -5,13 +5,15 @@ // accepted flags in lockstep with the flags each command's code really reads. import { describe, it, expect } from 'vitest'; -import { readFileSync, readdirSync } from 'node:fs'; +import { readFileSync } from 'node:fs'; +import { basename } from 'node:path'; +import { sourceFiles } from '../../scripts/check-layering.mjs'; import { join } from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; -import { findUnknownFlags as findUnknownFlagsIn, findMisplacedFlags as findMisplacedFlagsIn, assertKnownFlags as assertKnownFlagsIn } from '../lib/command-flags.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { findUnknownFlags as findUnknownFlagsIn, findMisplacedFlags as findMisplacedFlagsIn, assertKnownFlags as assertKnownFlagsIn } from '@kuiralabs/midnight-cli-core/lib/command-flags'; import { installedCommands } from '../lib/installed-commands.ts'; -import type { ParsedArgs } from '../lib/argv.ts'; +import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; // The refusal reads the installed commands' registry, as the CLI's does. const findUnknownFlags = (args: ParsedArgs) => findUnknownFlagsIn(args, installedCommands); @@ -93,7 +95,6 @@ describe('the accepted flags match the code', () => { // though it works; a registry entry no code reads would be accepted and // silently ignored (the bug this guards against). Derive each command's // flags from its source and require equality. - const COMMANDS_DIR = join(import.meta.dirname, '..', 'commands'); const LITERAL_READ = /(?:getFlag|hasFlag|requireFlag)\(\s*\w+\s*,\s*['"]([a-z0-9-]+)['"]/g; // Shared helpers that read flags on the command's behalf. const HELPER_FLAGS: Record = { @@ -127,14 +128,18 @@ describe('the accepted flags match the code', () => { // A command's definition (.definition.ts) sits beside it and is not a // command, nor is a package's agent guidance (.guidance.ts). - const commandFiles = readdirSync(COMMANDS_DIR).filter((f) => f.endsWith('.ts') && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts')); + // Commands sit in commands/ under src/ or a workspace package. + const commandPaths = new Map(sourceFiles() + .filter((f) => /\/commands\/[^/]+\.ts$/.test(f) && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts')) + .map((f) => [basename(f), f])); + const commandFiles = [...commandPaths.keys()]; it('has an entry for every command file, and no entry without one', () => { expect(installedCommands.commands.map((c) => c.name).sort()).toEqual(commandFiles.map((f) => f.replace(/\.ts$/, '')).sort()); }); it.each(commandFiles.map((f) => f.replace(/\.ts$/, '')))('%s: registry equals the flags its code reads', (command) => { - const source = readFileSync(join(COMMANDS_DIR, `${command}.ts`), 'utf-8'); + const source = readFileSync(commandPaths.get(`${command}.ts`)!, 'utf-8'); expect(installedCommands.find(command)!.flags.map((f) => f.name).sort()).toEqual([...flagsReadBy(source)].sort()); }); }); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 1f2ee3c0..91a06af5 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -8,6 +8,7 @@ import { describe, expect, it } from 'vitest'; import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; +import { WORKSPACE_PACKAGES, sourceFiles } from '../../scripts/check-layering.mjs'; import { installedCommands } from '../lib/installed-commands.ts'; import { CommandDefinitionError, @@ -21,18 +22,18 @@ import { NETWORK_PARAM, type CommandDefinition, type ToolDefinition, -} from '../lib/command-definition.ts'; -import { getValidNetworkNames } from '../lib/network.ts'; +} from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { CONFIRM_TOOL, listedTools } from '../lib/mcp/registry-tools.ts'; import { commandNeedsWalletSdk, dispatchCommand, type ShellProvisions } from '../lib/command-dispatch.ts'; -import { FULL_FLAG, parseArgs, type ParsedArgs } from '../lib/argv.ts'; -import { CancelledError, isUsageError } from '../lib/errors.ts'; -import { classifyError, EXIT_CANCELLED } from '../lib/exit-codes.ts'; -import type { CallContext, CommandOutcome } from '../lib/call-context.ts'; -import { hostPaths } from '../lib/state-root.ts'; -import { settings } from '../lib/settings.ts'; -import type { Payer } from '../lib/payer.ts'; -import { createSdkWarningRouter, sdkWarningCallsOn } from '../lib/sdk-warnings.ts'; +import { FULL_FLAG, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { CancelledError, isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError, EXIT_CANCELLED } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import type { CallContext, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { hostPaths } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { createSdkWarningRouter, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { WalletProtector } from '../lib/wallet-protector.ts'; const SRC = join(import.meta.dirname, '..'); @@ -60,7 +61,10 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => it('loads each handler from its own command\'s module', async () => { for (const c of registry.commands.filter((c) => c.shell.unavailable === undefined)) { - const fromModule = await import(`../commands/${c.name}.ts`); + // A command's module sits in commands/, under src/ or a workspace package, which is imported by name. + const file = sourceFiles().find((f) => f.endsWith(`/commands/${c.name}.ts`))!; + const pkg = WORKSPACE_PACKAGES.find((p) => file.startsWith(p.dir + '/')); + const fromModule = await import(pkg === undefined ? file : `${pkg.name}/commands/${c.name}`); expect((await c.load()).default, c.name).toBe(fromModule.default); } }, 120_000); @@ -201,17 +205,12 @@ describe('the accepted flags', () => { it('a flag takes a value exactly when the code reads one for it', () => { // getFlag/requireFlag read a value, hasFlag a bare switch, wherever in src/ a flag is read. const kinds = new Map>(); - const scan = (dir: string): void => { - for (const entry of readdirSync(dir, { withFileTypes: true })) { - const path = join(dir, entry.name); - if (entry.isDirectory()) { if (entry.name !== '__tests__') scan(path); continue; } - if (!entry.name.endsWith('.ts')) continue; - for (const m of readFileSync(path, 'utf8').matchAll(/(getFlag|requireFlag|hasFlag)\(\s*\w+\s*,\s*['"]([a-z0-9-]+)['"]/g)) { - kinds.set(m[2]!, (kinds.get(m[2]!) ?? new Set()).add(m[1] !== 'hasFlag')); - } + // src/ and the workspace packages, tests left out. + for (const path of sourceFiles()) { + for (const m of readFileSync(path, 'utf8').matchAll(/(getFlag|requireFlag|hasFlag)\(\s*\w+\s*,\s*['"]([a-z0-9-]+)['"]/g)) { + kinds.set(m[2]!, (kinds.get(m[2]!) ?? new Set()).add(m[1] !== 'hasFlag')); } - }; - scan(SRC); + } // The grant request's limits are read in a loop over their names (LIMIT_FLAGS in lib/grant/request.ts), as values. for (const limit of ['cap', 'per-call', 'max-coin', 'expires-in']) kinds.set(limit, new Set([true])); for (const command of registry.commands) { diff --git a/src/__tests__/config-command.test.ts b/src/__tests__/config-command.test.ts index 8b4797cf..10182cc1 100644 --- a/src/__tests__/config-command.test.ts +++ b/src/__tests__/config-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import configCommand from '../commands/config.ts'; -import { parseArgs } from '../lib/argv.ts'; -import { loadCliConfig } from '../lib/cli-config.ts'; +import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 0e4105d7..0ac2f420 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -6,14 +6,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveContractDeployRequest } from '../lib/contract/request.ts'; import { deployContract } from '../lib/contract/deploy.ts'; -import { resolvePayingTarget } from '../lib/payer.ts'; +import { resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { servePayerAt } from '../lib/serve-payer.ts'; -import { silentSpinner } from '../ui/spinner.ts'; -import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; -import { CancelledError } from '../lib/errors.ts'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; diff --git a/src/__tests__/contract-request.test.ts b/src/__tests__/contract-request.test.ts index 1238f67d..97ff314f 100644 --- a/src/__tests__/contract-request.test.ts +++ b/src/__tests__/contract-request.test.ts @@ -6,8 +6,8 @@ import { mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { resolveContractCallRequest, resolveContractDeployRequest } from '../lib/contract/request.ts'; -import { parseArgs } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; const UINT = { 'type-name': 'Uint', maxval: 255 }; const ADDRESS = 'cb5230e1ac98e07520d3b330016743a05fec38dd8fe894ae5b9ac3f71cac5190'; diff --git a/src/__tests__/contract-runner-endpoints.test.ts b/src/__tests__/contract-runner-endpoints.test.ts index 34a331d1..833526e0 100644 --- a/src/__tests__/contract-runner-endpoints.test.ts +++ b/src/__tests__/contract-runner-endpoints.test.ts @@ -4,17 +4,17 @@ // them in its text. import { describe, expect, it } from 'vitest'; -import { BlockfrostProjectIdRequiredError, blockfrostEndpoints } from '../lib/blockfrost.ts'; +import { BlockfrostProjectIdRequiredError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { SCRIPT_PARTS, indexerEnvironment } from '../lib/contract/runner.ts'; import * as rcScripts from '../engine/rc/contract-scripts.ts'; -import type { CallScript, DeployScript, StateScript } from '../lib/engine.ts'; +import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; // The rc engine's scripts, with the parts the runner gives every engine. const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const preprod = (projectId: string | undefined): NetworkConfig => ({ diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index 487a145a..3cffdf32 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -3,7 +3,7 @@ // mn serve RPC (`rpcCall`) is stubbed. import { describe, it, expect, beforeAll, afterEach } from 'vitest'; -import { CancelledError } from '../lib/errors.ts'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { spawnSync } from 'node:child_process'; import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -34,7 +34,7 @@ import { } from '../lib/contract/runner.ts'; import * as rcScripts from '../engine/rc/contract-scripts.ts'; import { PROVIDER_IMPORTS, walletProviderCode } from '../engine/rc/contract-scripts.ts'; -import type { CallScript, DeployScript, StateScript } from '../lib/engine.ts'; +import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; // The rc engine's scripts, with the parts the runner gives every engine. const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); @@ -42,7 +42,7 @@ const generateCallScript = (opts: CallScript & { dappDir?: string }): string => const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); const providerSetupCode = (networkConfig: Parameters[0], key: string): string => rcScripts.providerSetupCode(networkConfig, key, SCRIPT_PARTS); -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new ( ...params: string[] diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index 6e7a33b6..777382e5 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -23,7 +23,7 @@ import { import * as rcScripts from '../engine/rc/contract-scripts.ts'; import { SCRIPT_PACKAGES, packageFolder } from '../engine/rc/contract-scripts.ts'; import { rcEngine } from '../engine/rc/index.ts'; -import type { CallScript, DeployScript, StateScript } from '../lib/engine.ts'; +import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; // The rc engine's scripts, with the parts the runner gives every engine. const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); diff --git a/src/__tests__/contract-validate.test.ts b/src/__tests__/contract-validate.test.ts index 148b5f67..22ca9377 100644 --- a/src/__tests__/contract-validate.test.ts +++ b/src/__tests__/contract-validate.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { validateCallRequest, validateContractAddress } from '../lib/contract/validate.ts'; -import { UsageError } from '../lib/errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import type { ContractInfo } from '../lib/contract/inspect.ts'; const UINT = { 'type-name': 'Uint', maxval: 255 } as never; diff --git a/src/__tests__/dapp-connector.test.ts b/src/__tests__/dapp-connector.test.ts index 6289ef5a..f06cb926 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/src/__tests__/dapp-connector.test.ts @@ -13,22 +13,22 @@ import { Effect } from 'effect'; import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '../engine/rc/dapp-connector.ts'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; import { PartlySignedTransactionError } from '../engine/rc/sign-recipe.ts'; -import { signedMessageBytes } from '../lib/sign-data.ts'; +import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { Intent, UnshieldedOffer, verifySignature } from '@midnightntwrk/ledger-v9'; import type { FacadeBundle } from '../engine/rc/facade.ts'; -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { RpcHandlerContext } from '../lib/ws-rpc.ts'; -import { PROOF_TIMEOUT_MS } from '../lib/constants.ts'; -import { withDustShortfall } from '../lib/sdk-errors.ts'; -import { classifyError } from '../lib/exit-codes.ts'; +import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { FORK_SCHEDULE } from '../engine/rc/fork-schedule.ts'; import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '../engine/rc/derive-address.ts'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; -import type { FeeLimits } from '../lib/fee-limits.ts'; -import type { ApprovalOptions } from '../lib/approval.ts'; -import { setNoticeSink } from '../lib/notices.ts'; +import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; +import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { AGENT_SK, NIGHT, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, sealedBytes, spend, unsealedBytes, } from './helpers/ledger-tx.ts'; diff --git a/src/__tests__/derive-address.test.ts b/src/__tests__/derive-address.test.ts index 2cc4774f..3f5d90b5 100644 --- a/src/__tests__/derive-address.test.ts +++ b/src/__tests__/derive-address.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); diff --git a/src/__tests__/device-code.test.ts b/src/__tests__/device-code.test.ts index fb183be3..38b802bf 100644 --- a/src/__tests__/device-code.test.ts +++ b/src/__tests__/device-code.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest'; import { freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '../lib/errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { verifyReadKeyAttestation } from '@kuiralabs/midnight-account'; import { deviceCodeOf, deviceKeyOf, identityCodeOf, joinCodeOf, parseDeviceCode } from '../lib/grant/device-code.ts'; diff --git a/src/__tests__/dust-balancing-plan.test.ts b/src/__tests__/dust-balancing-plan.test.ts index 672cf5df..78e97b92 100644 --- a/src/__tests__/dust-balancing-plan.test.ts +++ b/src/__tests__/dust-balancing-plan.test.ts @@ -4,7 +4,7 @@ // combines them: the smallest first, until they cover what is owed. import { describe, expect, it } from 'vitest'; -import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '../lib/dust-balancing-plan.ts'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '@kuiralabs/midnight-cli-core/lib/dust-balancing-plan'; type Coin = DustInput; const coin = (token: string, value: bigint): Coin => ({ token, value }); diff --git a/src/__tests__/dust-command.test.ts b/src/__tests__/dust-command.test.ts index 7f7f805a..155e79b9 100644 --- a/src/__tests__/dust-command.test.ts +++ b/src/__tests__/dust-command.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import dustCommand from '../commands/dust.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; diff --git a/src/__tests__/dust-direct-cache.test.ts b/src/__tests__/dust-direct-cache.test.ts index 35994996..d70875de 100644 --- a/src/__tests__/dust-direct-cache.test.ts +++ b/src/__tests__/dust-direct-cache.test.ts @@ -8,7 +8,7 @@ import * as os from 'os'; import * as ledger from '@midnightntwrk/ledger-v9'; import { loadDustCache, saveDustCache, dustPublicKeyHex } from '../engine/rc/dust-direct-cache.ts'; -import { clearDustDirectCache, getDustCachePath } from '../lib/reader-cache-files.ts'; +import { clearDustDirectCache, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; const CACHE_DIR = path.join(os.tmpdir(), `midnight-dust-cache-test-${process.pid}-${Date.now()}`); const NETWORK = 'undeployed'; diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index d34ea55c..14114bed 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -98,7 +98,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { exportDustSnapshot } from '../engine/rc/dust-export.ts'; import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; const EXPORT_NETWORK: NetworkConfig = { diff --git a/src/__tests__/dust-logic.test.ts b/src/__tests__/dust-logic.test.ts index a90ef7ab..3c6cb919 100644 --- a/src/__tests__/dust-logic.test.ts +++ b/src/__tests__/dust-logic.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import * as rx from 'rxjs'; import { isDustRelatedError, ensureDust, registerNightUtxos } from '../engine/rc/transfer.ts'; -import { DustFeeNotGeneratedError } from '../lib/dust-registration-plan.ts'; +import { DustFeeNotGeneratedError } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; import type { FacadeBundle } from '../engine/rc/facade.ts'; import type { DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; diff --git a/src/__tests__/dust-registration-plan.test.ts b/src/__tests__/dust-registration-plan.test.ts index fb058dcd..953a167f 100644 --- a/src/__tests__/dust-registration-plan.test.ts +++ b/src/__tests__/dust-registration-plan.test.ts @@ -3,9 +3,9 @@ // wallet airdropped 20 NIGHT 34 minutes earlier. import { describe, it, expect } from 'vitest'; -import { DustFeeNotGeneratedError, planRegistration } from '../lib/dust-registration-plan.ts'; -import { formatWait } from '../lib/duration.ts'; -import { classifyError, EXIT_INSUFFICIENT_BALANCE } from '../lib/exit-codes.ts'; +import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; +import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; +import { classifyError, EXIT_INSUFFICIENT_BALANCE } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; const FEE = 526_587_115_818_352n; const TWENTY_NIGHT = { dust: { generatedNow: 337_954_960_000_000n, rate: 165_340_000_000n, maxCap: 100_000_000_000_000_000n } }; diff --git a/src/__tests__/dust-wait.test.ts b/src/__tests__/dust-wait.test.ts index 48afc151..4be24b5c 100644 --- a/src/__tests__/dust-wait.test.ts +++ b/src/__tests__/dust-wait.test.ts @@ -3,8 +3,8 @@ // NIGHT generates it (1000 NIGHT: ~0.0083 DUST/s on a ledger-9 localnet). import { describe, it, expect, vi } from 'vitest'; -import { DUST_SHORT_WAIT_MS, awaitDustForFee, dustShortError, msUntilDust, payWhenDustCovers, planDustWait, sleep } from '../lib/dust-wait.ts'; -import { withDustShortfall } from '../lib/sdk-errors.ts'; +import { DUST_SHORT_WAIT_MS, awaitDustForFee, dustShortError, msUntilDust, payWhenDustCovers, planDustWait, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; const DUST = 10n ** 15n; const NOW = new Date('2026-10-05T05:00:00Z'); diff --git a/src/__tests__/dust-wallet.test.ts b/src/__tests__/dust-wallet.test.ts index 3989271e..ce81900a 100644 --- a/src/__tests__/dust-wallet.test.ts +++ b/src/__tests__/dust-wallet.test.ts @@ -12,7 +12,7 @@ import { WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk import { EitherOps } from '@midnightntwrk/wallet-sdk/utilities'; import { ConvergingDustTransacting, DustWallet } from '../engine/rc/dust-wallet.ts'; import { FORK_SCHEDULE } from '../engine/rc/fork-schedule.ts'; -import { dustShortfallOf, isDustShortage } from '../lib/sdk-errors.ts'; +import { dustShortfallOf, isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { CAPTURED_AT, type FeeRange, coinsAt, computeArguments, feeRange, paymentToBalance, timeWhenSmallestReaches, transacting, } from './helpers/dust-balancing-case.ts'; diff --git a/src/__tests__/endpoint-check.test.ts b/src/__tests__/endpoint-check.test.ts index 532c3a36..e0c472da 100644 --- a/src/__tests__/endpoint-check.test.ts +++ b/src/__tests__/endpoint-check.test.ts @@ -1,7 +1,7 @@ // What is asked of a network's endpoints before a wallet sync starts. import { describe, expect, it } from 'vitest'; -import { BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '../lib/blockfrost.ts'; +import { BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { assertNetworkAnswers } from '../lib/endpoint-check.ts'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; diff --git a/src/__tests__/endpoint-refusals.test.ts b/src/__tests__/endpoint-refusals.test.ts index acd050f7..44a67865 100644 --- a/src/__tests__/endpoint-refusals.test.ts +++ b/src/__tests__/endpoint-refusals.test.ts @@ -6,7 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import * as http from 'node:http'; import type { AddressInfo } from 'node:net'; import { checkBalance } from '../lib/balance-subscription.ts'; -import { BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '../lib/blockfrost.ts'; +import { BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; import { callNodeRpc } from '../lib/node-rpc.ts'; diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index 4e95756a..5ed01371 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -2,8 +2,8 @@ // same for work every set does alike. import { describe, expect, it } from 'vitest'; -import { anyEngine, engineFor, sdkSetOf } from '../lib/engine.ts'; -import { getValidNetworkNames, type NetworkName } from '../lib/network.ts'; +import { anyEngine, engineFor, sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { rcEngine } from '../engine/rc/index.ts'; describe('the engine for a network', () => { diff --git a/src/__tests__/error-trim.test.ts b/src/__tests__/error-trim.test.ts index 9807ee0d..c7342f6a 100644 --- a/src/__tests__/error-trim.test.ts +++ b/src/__tests__/error-trim.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { trimAgentMessage } from '../lib/error-trim.ts'; +import { trimAgentMessage } from '@kuiralabs/midnight-cli-core/lib/error-trim'; describe('trimAgentMessage', () => { it('returns the input unchanged when there are no suggestions or paragraphs', () => { diff --git a/src/__tests__/exec-program.test.ts b/src/__tests__/exec-program.test.ts index fd800701..1591c1d7 100644 --- a/src/__tests__/exec-program.test.ts +++ b/src/__tests__/exec-program.test.ts @@ -3,8 +3,8 @@ // processes (this Node, running a short script), never on Docker. import { describe, expect, it } from 'vitest'; -import { CancelledError } from '../lib/errors.ts'; -import { execProgram, ProgramFailedError, ProgramTimedOutError } from '../lib/exec-program.ts'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { execProgram, ProgramFailedError, ProgramTimedOutError } from '@kuiralabs/midnight-cli-core/lib/exec-program'; /** Whether a process with this id is still alive. */ function isAlive(pid: number): boolean { diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 0c1836e3..cae2074b 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect } from 'vitest'; -import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR, EXIT_INVALID_ARGS } from '../lib/exit-codes.ts'; +import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; import { NoAccountError } from '../lib/grant/prepare.ts'; -import { WrongPassphraseError } from '../lib/keystore.ts'; +import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { NoPassphraseError } from '../lib/passphrase.ts'; describe('humanizeNetworkError', () => { @@ -61,7 +61,7 @@ describe('classifyError: typed setup errors keep their own code', () => { ['UNSUPPORTED_LEDGER', async () => new (await import('../lib/ledger-guard.ts')).UnsupportedLedgerError('preview', 1000300n)], ['LOCAL_STACK_UNREACHABLE', async () => new (await import('../lib/ledger-guard.ts')).LocalStackUnreachableError('indexer', 'http://localhost:8088/api/v4/graphql')], ['LOCALNET_UNAVAILABLE', async () => new (await import('../lib/localnet.ts')).LocalnetUnavailableError()], - ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('../lib/network.ts')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], + ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('@kuiralabs/midnight-cli-core/lib/network')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], ])('%s', async (code, make) => { const result = classifyError(await make()); expect(result.errorCode).toBe(code); @@ -96,7 +96,7 @@ describe('classifyError: mn grant', () => { describe('classifyError: usage errors', () => { it('classifies any UsageError as INVALID_ARGS (exit 2), whatever its text, so MCP agents get INVALID_ARGS too', async () => { - const { UsageError } = await import('../lib/errors.ts'); + const { UsageError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); expect(classifyError(new UsageError('A contract address is 64 hex characters (32 bytes); got "deadbeef" (8 characters).'))) .toEqual({ exitCode: 2, errorCode: 'INVALID_ARGS' }); expect(classifyError(new UsageError('increment takes 0 arguments; --args gave 3.'))) diff --git a/src/__tests__/facade.test.ts b/src/__tests__/facade.test.ts index b0a657ee..9d3948e8 100644 --- a/src/__tests__/facade.test.ts +++ b/src/__tests__/facade.test.ts @@ -261,7 +261,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { const url = await indexerWith({ zswapLedgerEvents: { id: 0, maxId: 384 }, dustLedgerEvents: { id: 0, maxId: 385 } }); const rx = await import('rxjs'); const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); - const { CancelledError } = await import('../lib/errors.ts'); + const { CancelledError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, seeds: {}, seedStartable: {}, keystore: {}, restoredFromCache: false, indexerWsUrl: url, @@ -282,7 +282,7 @@ describe('waitForDustAvailable', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const rx = await import('rxjs'); const { waitForDustAvailable } = await import('../engine/rc/facade.ts'); - const { CancelledError } = await import('../lib/errors.ts'); + const { CancelledError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); // A wallet with no Dust, and no later state. const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; diff --git a/src/__tests__/fee-limits.test.ts b/src/__tests__/fee-limits.test.ts index bb314a71..4e358f18 100644 --- a/src/__tests__/fee-limits.test.ts +++ b/src/__tests__/fee-limits.test.ts @@ -10,8 +10,8 @@ import { pendingLimitRefusal, DEFAULT_FEE_LIMITS, SPECKS_PER_DUST, -} from '../lib/fee-limits.ts'; -import { UsageError } from '../lib/errors.ts'; +} from '@kuiralabs/midnight-cli-core/lib/fee-limits'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; describe('parseDustAmount', () => { it.each([ diff --git a/src/__tests__/format.test.ts b/src/__tests__/format.test.ts index cfd18003..035d3035 100644 --- a/src/__tests__/format.test.ts +++ b/src/__tests__/format.test.ts @@ -3,7 +3,7 @@ import { header, divider, keyValue, toNight, formatNight, toDust, roughDust, formatDust, formatAddress, box, errorMessage, usageMessage, successMessage, -} from '../ui/format.ts'; +} from '@kuiralabs/midnight-cli-core/ui/format'; // Run format tests with NO_COLOR so we can assert exact string content // without ANSI escape codes getting in the way diff --git a/src/__tests__/generate-command.test.ts b/src/__tests__/generate-command.test.ts index 74aeec61..e7a84462 100644 --- a/src/__tests__/generate-command.test.ts +++ b/src/__tests__/generate-command.test.ts @@ -3,7 +3,7 @@ import { mnemonicToSeedSync } from '@scure/bip39'; import generateCommand from '../commands/generate.ts'; import { unlockWallet } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/genesis-address-command.test.ts b/src/__tests__/genesis-address-command.test.ts index e67e79ab..6b4945c4 100644 --- a/src/__tests__/genesis-address-command.test.ts +++ b/src/__tests__/genesis-address-command.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import genesisAddressCommand from '../commands/genesis-address.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/grant-account.test.ts b/src/__tests__/grant-account.test.ts index 05570879..8ea2cc04 100644 --- a/src/__tests__/grant-account.test.ts +++ b/src/__tests__/grant-account.test.ts @@ -8,9 +8,9 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError } from '../lib/keystore.ts'; +import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig } from '../lib/network.ts'; +import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { openGrantAccount } from '../lib/grant/account.ts'; import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; diff --git a/src/__tests__/grant-deploy-cost.test.ts b/src/__tests__/grant-deploy-cost.test.ts index 265a38da..0a4adfae 100644 --- a/src/__tests__/grant-deploy-cost.test.ts +++ b/src/__tests__/grant-deploy-cost.test.ts @@ -1,7 +1,7 @@ // What an owner is told when an account deploy stops for want of Dust. import { describe, expect, it } from 'vitest'; -import { ERROR_CODES, EXIT_INSUFFICIENT_BALANCE, classifyError } from '../lib/exit-codes.ts'; +import { ERROR_CODES, EXIT_INSUFFICIENT_BALANCE, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { MEASURED_ACCOUNT_DEPLOY, deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; describe('deployShortOfDustNote', () => { diff --git a/src/__tests__/grant-owner-commands.test.ts b/src/__tests__/grant-owner-commands.test.ts index 9a70e848..7f9007e1 100644 --- a/src/__tests__/grant-owner-commands.test.ts +++ b/src/__tests__/grant-owner-commands.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { freshGrantee, grantRequestFor, grantRequestLink } from '@kuiralabs/midnight-account-chain/agent'; -import { UsageError } from '../lib/errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { DEFAULT_GRANT_LIMITS, grantRequestOf, issuePreview } from '../lib/grant/owner-commands.ts'; const ACCOUNT = '5e'.repeat(32); diff --git a/src/__tests__/grant-prepare.test.ts b/src/__tests__/grant-prepare.test.ts index 51b334fe..447d5213 100644 --- a/src/__tests__/grant-prepare.test.ts +++ b/src/__tests__/grant-prepare.test.ts @@ -6,8 +6,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { UnreachableByAccountError } from '../lib/grant/account.ts'; import { NoAccountError, prepareGrant } from '../lib/grant/prepare.ts'; import { createAccountKey, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; diff --git a/src/__tests__/grant-request.test.ts b/src/__tests__/grant-request.test.ts index 3dd81598..0c5e2c7d 100644 --- a/src/__tests__/grant-request.test.ts +++ b/src/__tests__/grant-request.test.ts @@ -1,8 +1,8 @@ // What `mn grant` is asked to do, checked from its arguments alone. import { describe, expect, it } from 'vitest'; -import { parseArgs } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { describeGrantTerms, paysAFee, resolveGrantRequest } from '../lib/grant/request.ts'; const request = (...argv: string[]) => resolveGrantRequest(parseArgs(['grant', ...argv])); diff --git a/src/__tests__/graphql-ws-subscription.test.ts b/src/__tests__/graphql-ws-subscription.test.ts index 99f0b854..fa53fdc4 100644 --- a/src/__tests__/graphql-ws-subscription.test.ts +++ b/src/__tests__/graphql-ws-subscription.test.ts @@ -4,7 +4,7 @@ // closed-early / initial-silence / error / abort) is exercised end-to-end. import { describe, it, expect, afterEach } from 'vitest'; -import { CancelledError } from '../lib/errors.ts'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; diff --git a/src/__tests__/heap-guard.test.ts b/src/__tests__/heap-guard.test.ts index 4a412390..6b57f116 100644 --- a/src/__tests__/heap-guard.test.ts +++ b/src/__tests__/heap-guard.test.ts @@ -4,7 +4,7 @@ import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB, -} from '../lib/constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; describe('computeHeapTargetMb', () => { // The OOM repro: a 128 GB box with Node's default ~4.3 GB old-space cap. diff --git a/src/__tests__/help-agent.test.ts b/src/__tests__/help-agent.test.ts index 6d6e95b6..1f81e246 100644 --- a/src/__tests__/help-agent.test.ts +++ b/src/__tests__/help-agent.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import helpCommand from '../commands/help.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; @@ -32,7 +32,7 @@ describe('help --agent', () => { }); it('lists every error code mn can return', async () => { - const { ERROR_CODES } = await import('../lib/exit-codes.ts'); + const { ERROR_CODES } = await import('@kuiralabs/midnight-cli-core/lib/exit-codes'); await cliCall(helpCommand, parseArgs(['help', '--agent'])); const table = io.stdout().split('ERROR CODES')[1]!.split('MCP SERVER')[0]!; const missing = Object.values(ERROR_CODES).filter((code) => !new RegExp(`^ ${code}\\s+\\d`, 'm').test(table)); diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index a325bf43..ec8f7bd6 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import helpCommand, { helpSpecs } from '../commands/help.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/helpers/cli-call.ts b/src/__tests__/helpers/cli-call.ts index eb3a39d7..0cc5c0ed 100644 --- a/src/__tests__/helpers/cli-call.ts +++ b/src/__tests__/helpers/cli-call.ts @@ -2,10 +2,10 @@ // shell builds one, its result written at once to stdout as one JSON line. // Tests that read a command's output from the process's streams call it so. -import type { ParsedArgs } from '../../lib/argv.ts'; -import { createCallContext, runHandler, type CommandHandler, type CommandOutcome } from '../../lib/call-context.ts'; +import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { createCallContext, runHandler, type CommandHandler, type CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { processOutput } from '../../lib/command-dispatch.ts'; -import type { Payer } from '../../lib/payer.ts'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; export interface CliCallOptions { /** The call's cancellation; none: it is never cancelled. */ diff --git a/src/__tests__/helpers/dust-balancing-case.ts b/src/__tests__/helpers/dust-balancing-case.ts index e10b5ad0..f530cd70 100644 --- a/src/__tests__/helpers/dust-balancing-case.ts +++ b/src/__tests__/helpers/dust-balancing-case.ts @@ -5,7 +5,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { CoinsAndBalances, CoreWallet, Keys, Transacting } from '@midnightntwrk/wallet-sdk/dust/v2'; -import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '../../lib/constants.ts'; +import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/lib/constants'; import { TWO_COIN_DUST_CAPTURED_AT, TWO_COIN_DUST_SEED_HEX, TWO_COIN_DUST_STATE_HEX } from '../fixtures/dust-state-two-coins.ts'; import { LEDGER9_PARAMETERS_HEX } from '../fixtures/ledger9-parameters.ts'; import { NETWORK, TTL, agentPaysMerchant, unsealedBytes } from './ledger-tx.ts'; diff --git a/src/__tests__/helpers/offline-facade.ts b/src/__tests__/helpers/offline-facade.ts index d0ca50d5..13f0a473 100644 --- a/src/__tests__/helpers/offline-facade.ts +++ b/src/__tests__/helpers/offline-facade.ts @@ -12,7 +12,7 @@ import { WalletFacade, WalletEntrySchema, mergeWalletEntries } from '@midnightnt import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; import { PublicKey, UnshieldedWallet, createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { FORK_SCHEDULE } from '../../engine/rc/fork-schedule.ts'; -import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '../../lib/constants.ts'; +import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/lib/constants'; import { NETWORK } from './ledger-tx.ts'; /** The secret behind ledger-tx's WALLET_SK, as mn's schnorr keystore takes it. */ diff --git a/src/__tests__/helpers/own-call.ts b/src/__tests__/helpers/own-call.ts index 7d8abdbb..4801b8ce 100644 --- a/src/__tests__/helpers/own-call.ts +++ b/src/__tests__/helpers/own-call.ts @@ -2,7 +2,7 @@ // outside any host: no host's filters report to it. import type { CommandRun } from '../../lib/run-command.ts'; -import { createSdkWarningRouter, sdkWarningCallsOn } from '../../lib/sdk-warnings.ts'; +import { createSdkWarningRouter, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; export function ownCall(run: Omit = {}): CommandRun { return { ...run, sdkWarnings: sdkWarningCallsOn(createSdkWarningRouter()) }; diff --git a/src/__tests__/helpers/plain-wallet.ts b/src/__tests__/helpers/plain-wallet.ts index 1ab03cd1..0be74222 100644 --- a/src/__tests__/helpers/plain-wallet.ts +++ b/src/__tests__/helpers/plain-wallet.ts @@ -5,8 +5,8 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; -import type { NetworkName } from '../../lib/network.ts'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; export interface PlainWalletConfig { seed: string; diff --git a/src/__tests__/helpers/shell-settings.ts b/src/__tests__/helpers/shell-settings.ts index 26895bc1..e9b08357 100644 --- a/src/__tests__/helpers/shell-settings.ts +++ b/src/__tests__/helpers/shell-settings.ts @@ -5,10 +5,10 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; -import { setSettingsSource, settingsFromEnvironment } from '../../lib/settings.ts'; -import { setHostPathsSource } from '../../lib/state-root.ts'; -import { MIDNIGHT_DIR } from '../../lib/constants.ts'; -import { setEngineLoader } from '../../lib/engine.ts'; +import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import { loadInstalledEngine } from '../../lib/installed-engines.ts'; setSettingsSource(() => settingsFromEnvironment(process.env)); diff --git a/src/__tests__/helpers/stand-in-indexer.ts b/src/__tests__/helpers/stand-in-indexer.ts index 2c9e7a8f..8633697c 100644 --- a/src/__tests__/helpers/stand-in-indexer.ts +++ b/src/__tests__/helpers/stand-in-indexer.ts @@ -11,7 +11,7 @@ import { createServer, type Server, type Socket } from 'node:net'; import type { AddressInfo } from 'node:net'; import { WebSocketServer, type WebSocket } from 'ws'; -import { NATIVE_TOKEN_TYPE } from '../../lib/constants.ts'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; /** One subscription the stand-in indexer took. */ export interface Subscription { diff --git a/src/__tests__/helpers/state-root-in.ts b/src/__tests__/helpers/state-root-in.ts index e0fbd011..9e57e498 100644 --- a/src/__tests__/helpers/state-root-in.ts +++ b/src/__tests__/helpers/state-root-in.ts @@ -1,6 +1,6 @@ // The state root the CLI would keep under a test's home: its .midnight folder. import { join } from 'node:path'; -import { MIDNIGHT_DIR } from '../../lib/constants.ts'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; export const stateRootIn = (home: string): string => join(home, MIDNIGHT_DIR); diff --git a/src/__tests__/info-command.test.ts b/src/__tests__/info-command.test.ts index cf208b5d..ae87947d 100644 --- a/src/__tests__/info-command.test.ts +++ b/src/__tests__/info-command.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import infoCommand from '../commands/info.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; diff --git a/src/__tests__/inspect-cost-command.test.ts b/src/__tests__/inspect-cost-command.test.ts index 3aff9bed..1388ef7c 100644 --- a/src/__tests__/inspect-cost-command.test.ts +++ b/src/__tests__/inspect-cost-command.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; import { LEDGER9_PARAMETERS_HEX } from './fixtures/ledger9-parameters.ts'; diff --git a/src/__tests__/json-fields.test.ts b/src/__tests__/json-fields.test.ts index c721f9d0..b1a10370 100644 --- a/src/__tests__/json-fields.test.ts +++ b/src/__tests__/json-fields.test.ts @@ -7,10 +7,10 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; import { captureCommand } from '../lib/run-command.ts'; -import type { CommandHandler } from '../lib/call-context.ts'; +import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { ownCall } from './helpers/own-call.ts'; const PASSPHRASE = 'correct horse battery staple'; diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index 221206d6..8a139567 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; -import { classifyError, EXIT_WALLET_NOT_FOUND, EXIT_INVALID_ARGS, EXIT_CANCELLED, EXIT_NETWORK_ERROR, EXIT_INSUFFICIENT_BALANCE, EXIT_TX_REJECTED, EXIT_GENERAL_ERROR, ERROR_CODES } from '../lib/exit-codes.ts'; -import { writeJsonResult, writeJsonError } from '../lib/json-output.ts'; +import { classifyError, EXIT_WALLET_NOT_FOUND, EXIT_INVALID_ARGS, EXIT_CANCELLED, EXIT_NETWORK_ERROR, EXIT_INSUFFICIENT_BALANCE, EXIT_TX_REJECTED, EXIT_GENERAL_ERROR, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { writeJsonResult, writeJsonError } from '@kuiralabs/midnight-cli-core/lib/json-output'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -13,11 +13,11 @@ import infoCommand from '../commands/info.ts'; import addressCommand from '../commands/address.ts'; import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import configCommand from '../commands/config.ts'; +import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; import helpCommand from '../commands/help.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; -import { loadCliConfig } from '../lib/cli-config.ts'; +import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { localIndexerFlags } from './helpers/local-indexer.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/keystore.test.ts b/src/__tests__/keystore.test.ts index 6707b095..c6bac5e4 100644 --- a/src/__tests__/keystore.test.ts +++ b/src/__tests__/keystore.test.ts @@ -5,7 +5,7 @@ // machine than mn's own parameters do. import { describe, expect, it } from 'vitest'; -import { MalformedSecretError, WrongPassphraseError, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '../lib/keystore.ts'; +import { MalformedSecretError, WrongPassphraseError, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '@kuiralabs/midnight-cli-core/lib/keystore'; const SEED = Buffer.from('aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233', 'hex'); const PASSPHRASE = 'correct horse battery staple'; diff --git a/src/__tests__/ledger-guard.test.ts b/src/__tests__/ledger-guard.test.ts index b90b1bf2..51f69ea6 100644 --- a/src/__tests__/ledger-guard.test.ts +++ b/src/__tests__/ledger-guard.test.ts @@ -12,7 +12,7 @@ import { LocalStackUnreachableError, walletsBelowLedger9, } from '../lib/ledger-guard.ts'; -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; const PREVIEW = 1000300n; const LEDGER9_LOCALNET = 2001000n; diff --git a/src/__tests__/local-stacks.test.ts b/src/__tests__/local-stacks.test.ts index 4eb46796..a1d6be3f 100644 --- a/src/__tests__/local-stacks.test.ts +++ b/src/__tests__/local-stacks.test.ts @@ -11,7 +11,7 @@ import { pickLocalStack, resolveNetworkConfig, AmbiguousLocalStacksError, -} from '../lib/network.ts'; +} from '@kuiralabs/midnight-cli-core/lib/network'; const SCRATCH = [ 'midnightntwrk/indexer-standalone:4.4.0-rc.5|0.0.0.0:28088->8088/tcp, [::]:28088->8088/tcp', @@ -142,8 +142,8 @@ describe('resolveNetwork', () => { } it('applies endpoints saved with `midnight config set`, for commands with no endpoint flags', async () => { - const { resolveNetwork } = await import('../lib/resolve-network.ts'); - const { parseArgs } = await import('../lib/argv.ts'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); + const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); await withConfig({ network: 'undeployed', networks: { undeployed: { node: 'ws://localhost:29944', 'indexer-ws': 'ws://localhost:28088/api/v4/graphql/ws', 'proof-server': 'http://localhost:26300' } }, @@ -157,8 +157,8 @@ describe('resolveNetwork', () => { }); it('lets a flag win over the saved config', async () => { - const { resolveNetwork } = await import('../lib/resolve-network.ts'); - const { parseArgs } = await import('../lib/argv.ts'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); + const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); await withConfig({ network: 'undeployed', networks: { undeployed: { node: 'ws://localhost:29944' } } }, (configDir) => { const { config } = resolveNetwork({ args: parseArgs(['balance', '--node', 'ws://localhost:39944']), configDir }); expect(config.node).toBe('ws://localhost:39944'); @@ -166,8 +166,8 @@ describe('resolveNetwork', () => { }); it('keeps one network\'s saved endpoints away from another', async () => { - const { resolveNetwork } = await import('../lib/resolve-network.ts'); - const { parseArgs } = await import('../lib/argv.ts'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); + const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); await withConfig({ network: 'preview', networks: { preview: { 'proof-server': 'http://preview-prover:6300' } } }, (configDir) => { const { config } = resolveNetwork({ args: parseArgs(['balance', '--network', 'preprod']), configDir }); expect(config.proofServer).toBe('http://localhost:6300'); @@ -175,8 +175,8 @@ describe('resolveNetwork', () => { }); it('with every endpoint given by flag, works whatever docker runs', async () => { - const { resolveNetwork } = await import('../lib/resolve-network.ts'); - const { parseArgs } = await import('../lib/argv.ts'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); + const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); await withConfig(null, (configDir) => { const { name, config } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed', '--node', 'ws://localhost:29944', diff --git a/src/__tests__/localnet-cancellation.test.ts b/src/__tests__/localnet-cancellation.test.ts index 93079f36..120a9944 100644 --- a/src/__tests__/localnet-cancellation.test.ts +++ b/src/__tests__/localnet-cancellation.test.ts @@ -13,10 +13,10 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { runLocalnet } from '../commands/localnet.ts'; import { startLocalnet, type DockerCall } from '../lib/localnet.ts'; -import { CancelledError } from '../lib/errors.ts'; -import type { ExecRun, ExecRunner } from '../lib/exec-program.ts'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { ExecRun, ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; import { captureCommand } from '../lib/run-command.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { ownCall } from './helpers/own-call.ts'; diff --git a/src/__tests__/localnet-command.test.ts b/src/__tests__/localnet-command.test.ts index 1f58fe27..4018ed05 100644 --- a/src/__tests__/localnet-command.test.ts +++ b/src/__tests__/localnet-command.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; import localnetCommand from '../commands/localnet.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { existsSync, statSync } from 'fs'; import { @@ -15,7 +15,7 @@ import { parseServiceStatus, } from '../lib/localnet.ts'; import helpCommand from '../commands/help.ts'; -import { commandHelpSpecs, introBriefs } from '../lib/command-definition.ts'; +import { commandHelpSpecs, introBriefs } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { installedCommands } from '../lib/installed-commands.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/localnet-docker-probe.test.ts b/src/__tests__/localnet-docker-probe.test.ts index 8f8fc1cc..28105e35 100644 --- a/src/__tests__/localnet-docker-probe.test.ts +++ b/src/__tests__/localnet-docker-probe.test.ts @@ -13,7 +13,7 @@ import { pathToFileURL } from 'node:url'; // has no docker in it. const localnet = pathToFileURL(resolve(import.meta.dirname, '../lib/localnet.ts')).href; -const execProgram = pathToFileURL(resolve(import.meta.dirname, '../lib/exec-program.ts')).href; +const execProgram = pathToFileURL(resolve(import.meta.dirname, '../../packages/cli-core/src/lib/exec-program.ts')).href; const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href; describe('checkDockerAvailable on a machine without Docker', () => { diff --git a/src/__tests__/manual-command.test.ts b/src/__tests__/manual-command.test.ts index 9839184e..3b4d5a51 100644 --- a/src/__tests__/manual-command.test.ts +++ b/src/__tests__/manual-command.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import { buildManual } from '../commands/manual.ts'; -import { getConfigValue } from '../lib/cli-config.ts'; +import { getConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { installedCommands } from '../lib/installed-commands.ts'; function stripAnsi(s: string): string { diff --git a/src/__tests__/mcp-registry-tools.test.ts b/src/__tests__/mcp-registry-tools.test.ts index fcd03a35..28925386 100644 --- a/src/__tests__/mcp-registry-tools.test.ts +++ b/src/__tests__/mcp-registry-tools.test.ts @@ -3,10 +3,10 @@ // their JSON result through their call's context, as a command does. import { describe, expect, it } from 'vitest'; -import { createCommandRegistry, type CommandDefinition, type ToolDefinition } from '../lib/command-definition.ts'; +import { createCommandRegistry, type CommandDefinition, type ToolDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { CONFIRM_TOOL, confirmationFor, findTool, listedTools, runTool } from '../lib/mcp/registry-tools.ts'; -import type { CallContext } from '../lib/call-context.ts'; -import { MINIMAL_FLAG, type ParsedArgs } from '../lib/argv.ts'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { MINIMAL_FLAG, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { ownCall } from './helpers/own-call.ts'; const received: ParsedArgs[] = []; diff --git a/src/__tests__/mcp-server-concurrent-calls.test.ts b/src/__tests__/mcp-server-concurrent-calls.test.ts index a46f96db..63634694 100644 --- a/src/__tests__/mcp-server-concurrent-calls.test.ts +++ b/src/__tests__/mcp-server-concurrent-calls.test.ts @@ -22,7 +22,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.js'; import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; -import { toNight } from '../ui/format.ts'; +import { toNight } from '@kuiralabs/midnight-cli-core/ui/format'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); diff --git a/src/__tests__/mcp-server.test.ts b/src/__tests__/mcp-server.test.ts index d193470c..4cbc7fee 100644 --- a/src/__tests__/mcp-server.test.ts +++ b/src/__tests__/mcp-server.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { commandHelpSpecs } from '../lib/command-definition.ts'; +import { commandHelpSpecs } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { installedCommands } from '../lib/installed-commands.ts'; import { listedTools } from '../lib/mcp/registry-tools.ts'; diff --git a/src/__tests__/multi-wallet.test.ts b/src/__tests__/multi-wallet.test.ts index ed09f21f..900b41f4 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/src/__tests__/multi-wallet.test.ts @@ -16,7 +16,7 @@ import { loadCliConfig, saveCliConfig, type CliConfig, -} from '../lib/cli-config.ts'; +} from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { MIDNIGHT_DIR, WALLETS_DIR_NAME, @@ -25,7 +25,7 @@ import { DIR_MODE, FILE_MODE, isValidWalletName, -} from '../lib/constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; // Use a temp dir that simulates ~/.midnight diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index d843c6ce..e3c85050 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -11,12 +11,12 @@ import { createServer, type Server } from 'node:http'; import { createServer as createTcpServer, type AddressInfo, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; import { establishPassphrase } from '../lib/passphrase.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; -import type { CommandHandler } from '../lib/call-context.ts'; +import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; diff --git a/src/__tests__/network-id.test.ts b/src/__tests__/network-id.test.ts index 0f4d41b1..7fbd085f 100644 --- a/src/__tests__/network-id.test.ts +++ b/src/__tests__/network-id.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { getNetworkId } from '../lib/network-id.ts'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { NetworkId } from '@midnightntwrk/wallet-sdk'; describe('getNetworkId', () => { @@ -27,7 +27,7 @@ describe('getNetworkId', () => { describe('the plain values the base keeps match the SDK', () => { it("names each network by the SDK's NetworkId", async () => { - const { networkIdForName } = await import('../lib/network-id.ts'); + const { networkIdForName } = await import('@kuiralabs/midnight-cli-core/lib/network-id'); expect(networkIdForName('preprod')).toBe(NetworkId.NetworkId.PreProd); expect(networkIdForName('preview')).toBe(NetworkId.NetworkId.Preview); expect(networkIdForName('undeployed')).toBe(NetworkId.NetworkId.Undeployed); @@ -35,7 +35,7 @@ describe('the plain values the base keeps match the SDK', () => { it("keeps the ledger-9 fork at the SDK's version, and the facade's schedule starts there", async () => { const { ProtocolVersion } = await import('@midnightntwrk/wallet-sdk'); - const { LEDGER_9_FORK_VERSION } = await import('../lib/network.ts'); + const { LEDGER_9_FORK_VERSION } = await import('@kuiralabs/midnight-cli-core/lib/network'); const { FORK_SCHEDULE } = await import('../engine/rc/fork-schedule.ts'); expect(LEDGER_9_FORK_VERSION).toBe(ProtocolVersion.V9NativeForkVersion); expect(FORK_SCHEDULE.v9).toBe(LEDGER_9_FORK_VERSION); diff --git a/src/__tests__/network.test.ts b/src/__tests__/network.test.ts index 5596c998..5a04ca64 100644 --- a/src/__tests__/network.test.ts +++ b/src/__tests__/network.test.ts @@ -10,7 +10,7 @@ import { resolveNetworkConfig, applyEndpointOverrides, indexerHttpFromWs, -} from '../lib/network.ts'; +} from '@kuiralabs/midnight-cli-core/lib/network'; describe('detectNetworkFromAddress', () => { it('detects preprod from address prefix', () => { diff --git a/src/__tests__/node-version.test.ts b/src/__tests__/node-version.test.ts index c9b81b89..5676fa48 100644 --- a/src/__tests__/node-version.test.ts +++ b/src/__tests__/node-version.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { MIN_NODE_MAJOR, UnsupportedNodeError, assertNodeSupported } from '../lib/node-version.ts'; -import { classifyError } from '../lib/exit-codes.ts'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; describe('assertNodeSupported', () => { it('accepts Node.js 22 and newer', () => { diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index 17743703..e6f810ae 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -7,7 +7,7 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { notice, setNoticeSink } from '../lib/notices.ts'; +import { notice, setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { unlockWallet } from '../lib/wallet-config.ts'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; diff --git a/src/__tests__/passphrase.test.ts b/src/__tests__/passphrase.test.ts index 8e3cca94..66699e0f 100644 --- a/src/__tests__/passphrase.test.ts +++ b/src/__tests__/passphrase.test.ts @@ -8,7 +8,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { PassThrough } from 'node:stream'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError } from '../lib/keystore.ts'; +import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { NoPassphraseError, PASSPHRASE_ENV, @@ -19,8 +19,8 @@ import { readPassphrase, unlockPassphrase, } from '../lib/passphrase.ts'; -import { FILE_MODE } from '../lib/constants.ts'; -import { createTerminalPrompter } from '../ui/terminal-prompter.ts'; +import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; import { stateRootIn } from './helpers/state-root-in.ts'; const PASSPHRASE = 'correct horse battery staple'; diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index 42ee6119..732f1608 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -7,15 +7,15 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; -import { saveCliConfig } from '../lib/cli-config.ts'; -import { NoPayerError, resolvePayingTarget } from '../lib/payer.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { NoPayerError, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { NoAccountError } from '../lib/grant/prepare.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; import { probeServeNetwork } from '../lib/serve-manager.ts'; -import { silentSpinner } from '../ui/spinner.ts'; -import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; -import { CancelledError } from '../lib/errors.ts'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import contractCommand from '../commands/contract.ts'; import grantCommand from '../commands/grant.ts'; diff --git a/src/__tests__/phase-tracker.test.ts b/src/__tests__/phase-tracker.test.ts index ab073bcd..f8faa2e4 100644 --- a/src/__tests__/phase-tracker.test.ts +++ b/src/__tests__/phase-tracker.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { createPhaseTracker } from '../lib/phase-tracker.ts'; +import { createPhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; describe('createPhaseTracker', () => { beforeEach(() => { diff --git a/src/__tests__/prep-runner-cancellation.test.ts b/src/__tests__/prep-runner-cancellation.test.ts index 9396c760..86c61c98 100644 --- a/src/__tests__/prep-runner-cancellation.test.ts +++ b/src/__tests__/prep-runner-cancellation.test.ts @@ -4,8 +4,8 @@ import { describe, expect, it } from 'vitest'; import { runPrepSteps } from '../lib/test/prep-runner.ts'; import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; -import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; -import { CancelledError } from '../lib/errors.ts'; +import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; const config = { network: 'undeployed', prep: ['dust', 'mn-serve'] } as unknown as DappTestConfig; diff --git a/src/__tests__/protect-account.test.ts b/src/__tests__/protect-account.test.ts index 95d986de..02d8c7df 100644 --- a/src/__tests__/protect-account.test.ts +++ b/src/__tests__/protect-account.test.ts @@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { type FeeWallet, accountProviders, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_ID } from '@kuiralabs/midnight-account-chain/contract'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig } from '../lib/network.ts'; +import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { LEGACY_STORE_PASSWORD, openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { AccountMigrationInterruptedError, protectAccount } from '../lib/grant/protect-account.ts'; import { isSealedAccount } from '../lib/grant/sealed-account.ts'; diff --git a/src/__tests__/read-cancellation.test.ts b/src/__tests__/read-cancellation.test.ts index 8f0f66f0..92c14fd4 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/src/__tests__/read-cancellation.test.ts @@ -16,9 +16,9 @@ import { checkBalance } from '../lib/balance-subscription.ts'; import { waitForFirstBlock } from '../lib/node-ready.ts'; import { waitForAddressFunded } from '../lib/indexer-ready.ts'; import { waitForProofServerReady } from '../lib/proof-server-ready.ts'; -import { sleep } from '../lib/sleep.ts'; +import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; -import { getNetworkConfig, type NetworkConfig } from '../lib/network.ts'; +import { getNetworkConfig, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { BalanceSummary } from '../lib/balance-subscription.ts'; let http: Server; diff --git a/src/__tests__/resolve-network.test.ts b/src/__tests__/resolve-network.test.ts index f90506b0..aa1e8760 100644 --- a/src/__tests__/resolve-network.test.ts +++ b/src/__tests__/resolve-network.test.ts @@ -2,9 +2,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import { resolveBlockfrostProjectId, resolveNetworkName, resolveNetwork, type NetworkResolutionContext } from '../lib/resolve-network.ts'; -import { saveCliConfig, setConfigValue } from '../lib/cli-config.ts'; -import { parseArgs, type ParsedArgs } from '../lib/argv.ts'; +import { resolveBlockfrostProjectId, resolveNetworkName, resolveNetwork, type NetworkResolutionContext } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { saveCliConfig, setConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; // Use a temp config dir to avoid polluting the real ~/.midnight/ const TEST_DIR = path.join(os.tmpdir(), `midnight-resolve-network-test-${process.pid}`); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index f0d6752c..f77fe1a2 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { captureCommand } from '../lib/run-command.ts'; -import { SecondResultError, type CommandHandler } from '../lib/call-context.ts'; -import { CancelledError, CommandFailedError } from '../lib/errors.ts'; -import { classifyError } from '../lib/exit-codes.ts'; -import type { Spinner } from '../ui/spinner.ts'; -import { parseArgs, type ParsedArgs } from '../lib/argv.ts'; +import { SecondResultError, type CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { CancelledError, CommandFailedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/sdk-errors.test.ts b/src/__tests__/sdk-errors.test.ts index c3f3a45f..38c2064e 100644 --- a/src/__tests__/sdk-errors.test.ts +++ b/src/__tests__/sdk-errors.test.ts @@ -6,9 +6,9 @@ import { describe, it, expect } from 'vitest'; import { Brand, Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { NodeClientError } from '@midnightntwrk/wallet-sdk/node-client/effect'; -import { dustShortfallOf, isColdStartRace, isDustShortage, nodeRefusalOf, withDustShortfall, withNodeReason } from '../lib/sdk-errors.ts'; -import { TransactionRefusedError } from '../lib/errors.ts'; -import { classifyError } from '../lib/exit-codes.ts'; +import { dustShortfallOf, isColdStartRace, isDustShortage, nodeRefusalOf, withDustShortfall, withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; /** wallet-sdk 2.0's dust InsufficientFundsError: tagged, with the token it could not balance. */ function sdkInsufficientFunds(tokenType: string): Error { diff --git a/src/__tests__/sdk-free-base.test.ts b/src/__tests__/sdk-free-base.test.ts index 52c98cf2..151ebddf 100644 --- a/src/__tests__/sdk-free-base.test.ts +++ b/src/__tests__/sdk-free-base.test.ts @@ -1,6 +1,6 @@ // The base and the network I/O helpers (the files the layering check places // in core and chain) load with no Midnight SDK: each is imported in a node -// whose module hook refuses every Midnight and kuiralabs package. And the +// whose module hook refuses every Midnight SDK and account package. And the // built `mn` loads none for --version, help or config, which run before any // command needs one. @@ -12,7 +12,7 @@ import { join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; const ROOT = resolve(import.meta.dirname, '..', '..'); -const SDK = String.raw`^(@midnight(?:-ntwrk|ntwrk)\/[^/]+|@kuiralabs\/[^/]+)`; +const SDK = String.raw`^(@midnight(?:-ntwrk|ntwrk)\/[^/]+|@kuiralabs\/midnight-account[^/]*)`; /** A module hook file: `refuse` makes an SDK import fail, otherwise each one is logged to `log`. */ function sdkHook(dir: string, mode: 'refuse' | 'record'): string { diff --git a/src/__tests__/sdk-warnings.test.ts b/src/__tests__/sdk-warnings.test.ts index 63235266..4e62c763 100644 --- a/src/__tests__/sdk-warnings.test.ts +++ b/src/__tests__/sdk-warnings.test.ts @@ -3,7 +3,7 @@ // tested in a process of their own (process-safety.test.ts). import { describe, it, expect } from 'vitest'; -import { createSdkWarningRouter, sdkTransientWarning, sdkWarningCallsOn } from '../lib/sdk-warnings.ts'; +import { createSdkWarningRouter, sdkTransientWarning, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; describe('the SDK-warning router', () => { it('gives a warning with a call\'s identity to that call\'s newest listener, and no other call\'s', () => { diff --git a/src/__tests__/sealed-account.test.ts b/src/__tests__/sealed-account.test.ts index 5e2b25b6..d9dd3bba 100644 --- a/src/__tests__/sealed-account.test.ts +++ b/src/__tests__/sealed-account.test.ts @@ -15,7 +15,7 @@ import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; -import { WrongPassphraseError } from '../lib/keystore.ts'; +import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { contractAddressOnRecord, createAccountKey, diff --git a/src/__tests__/sealed-wallet.test.ts b/src/__tests__/sealed-wallet.test.ts index e6dddfca..289aee81 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/src/__tests__/sealed-wallet.test.ts @@ -8,11 +8,11 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError } from '../lib/keystore.ts'; +import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { loadWalletConfig, protectAllWallets, sealWalletInPlace, unlockWallet, writeSealedWallet } from '../lib/wallet-config.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; -import { FILE_MODE } from '../lib/constants.ts'; +import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { stateRootIn } from './helpers/state-root-in.ts'; const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 869108ad..3273cb3d 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -6,7 +6,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { parseSeedHex, resolveSeedSource, resolveSeed } from '../lib/seed-resolver.ts'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; diff --git a/src/__tests__/serve-command.test.ts b/src/__tests__/serve-command.test.ts index d03e4efb..641c8e1b 100644 --- a/src/__tests__/serve-command.test.ts +++ b/src/__tests__/serve-command.test.ts @@ -2,9 +2,9 @@ import { describe, it, expect } from 'vitest'; import serveCommand from '../commands/serve.ts'; -import { parseArgs } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; -import { findUnknownFlags } from '../lib/command-flags.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { findUnknownFlags } from '@kuiralabs/midnight-cli-core/lib/command-flags'; import { installedCommands } from '../lib/installed-commands.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index 32cba373..b84b5036 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -8,7 +8,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; -import { createSdkWarningRouter } from '../lib/sdk-warnings.ts'; +import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; const scratch = { node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws' }; diff --git a/src/__tests__/settings.test.ts b/src/__tests__/settings.test.ts index 6ea9e325..07e8c5cd 100644 --- a/src/__tests__/settings.test.ts +++ b/src/__tests__/settings.test.ts @@ -3,9 +3,9 @@ // settings source behaves as if none were set, whatever the environment says. import { afterEach, describe, expect, it } from 'vitest'; -import { setSettingsSource, settings, settingsFromEnvironment } from '../lib/settings.ts'; -import { resolveBlockfrostProjectId } from '../lib/resolve-network.ts'; -import { detectLocalStacks } from '../lib/network.ts'; +import { setSettingsSource, settings, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { resolveBlockfrostProjectId } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { detectLocalStacks } from '@kuiralabs/midnight-cli-core/lib/network'; import { readPassphrase, NoPassphraseError } from '../lib/passphrase.ts'; afterEach(() => { diff --git a/src/__tests__/shielded-direct-cache.test.ts b/src/__tests__/shielded-direct-cache.test.ts index 54d263b4..49c5275c 100644 --- a/src/__tests__/shielded-direct-cache.test.ts +++ b/src/__tests__/shielded-direct-cache.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path'; import { tmpdir } from 'node:os'; import * as ledger from '@midnightntwrk/ledger-v9'; import { shieldedCoinPublicKeyHexFromSeed, loadShieldedCache, saveShieldedCache } from '../engine/rc/shielded-direct-cache.ts'; -import { getShieldedCachePath, clearShieldedDirectCache } from '../lib/reader-cache-files.ts'; +import { getShieldedCachePath, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; const PUBKEY = 'aabbccddeeff00112233445566778899aabbccddeeff001122334455667788ff'; const OTHER_PUBKEY = '1122334455667788112233445566778811223344556677881122334455667788'; diff --git a/src/__tests__/sign-data.test.ts b/src/__tests__/sign-data.test.ts index be6052fa..443c2174 100644 --- a/src/__tests__/sign-data.test.ts +++ b/src/__tests__/sign-data.test.ts @@ -2,7 +2,7 @@ // never signs bytes other than the ones the dApp meant. import { describe, expect, it } from 'vitest'; -import { decodeSignPayload, signedMessageBytes } from '../lib/sign-data.ts'; +import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; describe('signedMessageBytes', () => { it('puts "midnight_signed_message::" before the bytes', () => { diff --git a/src/__tests__/sleep.test.ts b/src/__tests__/sleep.test.ts index 9db324cf..4b36a0a0 100644 --- a/src/__tests__/sleep.test.ts +++ b/src/__tests__/sleep.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { untilCancelled } from '../lib/sleep.ts'; -import { CancelledError } from '../lib/errors.ts'; +import { untilCancelled } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; describe('untilCancelled', () => { it('gives what the work gives, and its error', async () => { diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 0c706308..c9ba2ca7 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -8,18 +8,18 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { setHostPathsSource, stateRoot, NoStateRootError } from '../lib/state-root.ts'; -import { setConfigValue } from '../lib/cli-config.ts'; -import { bindCachesToIndexer } from '../lib/cache-indexer.ts'; +import { setHostPathsSource, stateRoot, NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { setConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { passphraseForNewSecret, PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import { accountRecordsDir } from '../lib/grant/account-records.ts'; import { accountArtifactsDir } from '../lib/grant/account.ts'; -import { getCachePath } from '../lib/wallet-cache.ts'; -import { getDustCachePath } from '../lib/reader-cache-files.ts'; -import { getShieldedCachePath } from '../lib/reader-cache-files.ts'; +import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; import { getComposePath } from '../lib/localnet.ts'; -import { MIDNIGHT_DIR } from '../lib/constants.ts'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import before from './fixtures/state-layout-before-1g.json'; const PASSPHRASE = 'fixture-passphrase-1g'; diff --git a/src/__tests__/terminal-prompter.test.ts b/src/__tests__/terminal-prompter.test.ts index 37eeb819..226f5588 100644 --- a/src/__tests__/terminal-prompter.test.ts +++ b/src/__tests__/terminal-prompter.test.ts @@ -6,8 +6,8 @@ import { describe, expect, it } from 'vitest'; import { spawnSync } from 'node:child_process'; import { resolve } from 'node:path'; import { PassThrough } from 'node:stream'; -import { createTerminalPrompter } from '../ui/terminal-prompter.ts'; -import { PromptBusyError } from '../lib/prompter.ts'; +import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; +import { PromptBusyError } from '@kuiralabs/midnight-cli-core/lib/prompter'; const ROOT = resolve(import.meta.dirname, '..', '..'); @@ -17,7 +17,7 @@ describe('the terminal prompter', () => { let touched = 0; const own = Object.getOwnPropertyDescriptor(process, 'stdin'); Object.defineProperty(process, 'stdin', { configurable: true, get() { touched++; return own.get.call(process); } }); - const { createTerminalPrompter } = await import(${JSON.stringify(resolve(ROOT, 'src/ui/terminal-prompter.ts'))}); + const { createTerminalPrompter } = await import(${JSON.stringify(resolve(ROOT, 'packages/cli-core/src/ui/terminal-prompter.ts'))}); const prompter = createTerminalPrompter(); const atCreation = touched; prompter.isInteractive(); diff --git a/src/__tests__/transfer-command.test.ts b/src/__tests__/transfer-command.test.ts index 992a70fc..6ade2715 100644 --- a/src/__tests__/transfer-command.test.ts +++ b/src/__tests__/transfer-command.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import transferCommand from '../commands/transfer.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/transfer-lib.test.ts b/src/__tests__/transfer-lib.test.ts index f67e1591..d99bcb95 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/src/__tests__/transfer-lib.test.ts @@ -1,11 +1,11 @@ import { describe, it, expect } from 'vitest'; import { validateRecipientAddress, isDustRelatedError } from '../engine/rc/transfer.ts'; -import { nightToMicro, parseAmount } from '../lib/amount.ts'; -import { getNetworkConfig } from '../lib/network.ts'; +import { nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; -import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '../lib/constants.ts'; -import { UsageError } from '../lib/errors.ts'; -import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '../lib/exit-codes.ts'; +import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; describe('nightToMicro', () => { it('converts whole NIGHT to micro-NIGHT', () => { diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index 1a1d82a1..04cf106a 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -7,12 +7,12 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { resolveTransferRequest } from '../lib/transfer-request.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; -import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '../lib/constants.ts'; -import { UsageError } from '../lib/errors.ts'; -import { classifyError } from '../lib/exit-codes.ts'; +import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; const HOME = path.join(os.tmpdir(), `midnight-transfer-request-test-${process.pid}`); const WALLETS = path.join(HOME, MIDNIGHT_DIR, WALLETS_DIR_NAME); diff --git a/src/__tests__/tx-serde.test.ts b/src/__tests__/tx-serde.test.ts index 359d58ab..e505bc10 100644 --- a/src/__tests__/tx-serde.test.ts +++ b/src/__tests__/tx-serde.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { toHex, fromHex } from '../lib/tx-serde.ts'; +import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; describe('tx-serde', () => { describe('toHex', () => { diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 03f74f07..f86f0a5b 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -9,12 +9,12 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Buffer } from 'node:buffer'; import { captureCommand } from '../lib/run-command.ts'; -import { callDiagnostics } from '../lib/call-context.ts'; -import { parseArgs } from '../lib/argv.ts'; -import { setNoticeSink } from '../lib/notices.ts'; +import { callDiagnostics } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import balanceCommand from '../commands/balance.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { ownCall } from './helpers/own-call.ts'; diff --git a/src/__tests__/verbose.test.ts b/src/__tests__/verbose.test.ts index 1890db44..8e6c6049 100644 --- a/src/__tests__/verbose.test.ts +++ b/src/__tests__/verbose.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { verboseLine } from '../lib/verbose.ts'; +import { verboseLine } from '@kuiralabs/midnight-cli-core/lib/verbose'; // The verbose line's format. Whether a call shows it is the call's own // (verbose-per-call.test.ts, call-context.test.ts). diff --git a/src/__tests__/wallet-cache.test.ts b/src/__tests__/wallet-cache.test.ts index 1152c927..6f4e2f46 100644 --- a/src/__tests__/wallet-cache.test.ts +++ b/src/__tests__/wallet-cache.test.ts @@ -9,8 +9,8 @@ import { saveWalletCache, clearWalletCache, getCachePath, -} from '../lib/wallet-cache.ts'; -import { CACHE_VERSION } from '../lib/constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { CACHE_VERSION } from '@kuiralabs/midnight-cli-core/lib/constants'; const TEST_ADDRESS = 'mn_addr_preprod1mp06mtx1234567890abcdef'; const TEST_NETWORK = 'preprod'; diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 9b370bb3..aed47d3d 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -5,7 +5,7 @@ import * as os from 'os'; import { loadWalletConfig, matchWalletAddress, unlockWallet, writeSealedWallet, type WalletInfo } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { DIR_MODE, FILE_MODE } from '../lib/constants.ts'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index af834a81..eb695c44 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -12,7 +12,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '../engine/rc/wallet-data-repository.ts'; import { UnsupportedLedgerError } from '../lib/ledger-guard.ts'; -import type { NetworkConfig } from '../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { BalanceSummary } from '../lib/balance-subscription.ts'; import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index ae25ac5b..c92aa62c 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -10,7 +10,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import walletCommand from '../commands/wallet.ts'; -import { parseArgs } from '../lib/argv.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { PASSPHRASE_ENV, isPassphraseSet } from '../lib/passphrase.ts'; import { loadWalletConfig } from '../lib/wallet-config.ts'; import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index 7c3bf64e..91d56831 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -13,9 +13,9 @@ import { join } from 'node:path'; import * as ledger from '@midnightntwrk/ledger-v9'; import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; import { dustPublicKeyHexFromSeed, saveDustCache } from '../engine/rc/dust-direct-cache.ts'; -import type { NetworkConfig } from '../lib/network.ts'; -import { parseArgs } from '../lib/argv.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; let NETWORK: NetworkConfig; diff --git a/src/commands/address.definition.ts b/src/commands/address.definition.ts index cff35eb0..7945d327 100644 --- a/src/commands/address.definition.ts +++ b/src/commands/address.definition.ts @@ -1,6 +1,6 @@ // The `address` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const addressDefinition: CommandDefinition = { name: 'address', diff --git a/src/commands/address.ts b/src/commands/address.ts index 710bf505..6ec24682 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -1,13 +1,13 @@ // address command — derive and display an unshielded address from a seed // Bare address to stdout (pipeable), formatted details to stderr -import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveSeed } from '../lib/seed-resolver.ts'; -import { engineFor } from '../lib/engine.ts'; -import { resolveNetworkName } from '../lib/resolve-network.ts'; -import { keyValue, divider, formatAddress } from '../ui/format.ts'; -import { dim } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function addressCommand(args: ParsedArgs, ctx: CallContext): Promise { // `address` is a seed-derivation tool with no active-wallet notion → requireExplicit. diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index 1dcf13b5..c68366aa 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -1,6 +1,6 @@ // The `airdrop` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const airdropDefinition: CommandDefinition = { name: 'airdrop', diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index afc341d5..d4b99768 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -9,17 +9,17 @@ // file required, useful for funding externally-generated addresses. // A shielded address implies --shielded; the flag is optional there. -import { throwIfCancelled } from '../lib/errors.ts'; -import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; import { loadWalletConfig, resolveWalletPath, saveShieldedAddress } from '../lib/wallet-config.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; -import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '../lib/network.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; -import { engineFor } from '../lib/engine.ts'; -import { parseAmount, nightToMicro } from '../lib/amount.ts'; -import { header, keyValue, divider, formatAddress, successMessage } from '../ui/format.ts'; -import { bold, dim } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { parseAmount, nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function airdropCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); diff --git a/src/commands/balance.definition.ts b/src/commands/balance.definition.ts index 69842f4d..1f58bd71 100644 --- a/src/commands/balance.definition.ts +++ b/src/commands/balance.definition.ts @@ -1,6 +1,6 @@ // The `balance` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const balanceDefinition: CommandDefinition = { name: 'balance', diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 90a19377..fefacb29 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -1,22 +1,22 @@ // balance command — check unshielded + shielded balance via full wallet sync // For positional address: unshielded only (GraphQL, no facade needed) -import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '../lib/argv.ts'; -import { type NetworkName, isValidNetworkName } from '../lib/network.ts'; +import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { type NetworkName, isValidNetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { saveShieldedAddress, findWalletByAddress } from '../lib/wallet-config.ts'; import { resolveSeedSource } from '../lib/seed-resolver.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; -import { applyEndpointOverrides } from '../lib/network.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; import { shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; import { isNativeToken } from '../lib/balance-subscription.ts'; -import { engineFor } from '../lib/engine.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; import { getChainGenesisHash } from '../lib/chain-id.ts'; import { createEtaEstimator, formatSyncStatus } from '../lib/sync-eta.ts'; -import { header, keyValue, divider, formatNight, formatAddress, toNight } from '../ui/format.ts'; -import { bold, dim } from '../ui/colors.ts'; -import type { Spinner } from '../ui/spinner.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { header, keyValue, divider, formatNight, formatAddress, toNight } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function balanceCommand(args: ParsedArgs, ctx: CallContext): Promise { // Positional address → unshielded only (lightweight, no facade) diff --git a/src/commands/cache.definition.ts b/src/commands/cache.definition.ts index 727edded..946d9284 100644 --- a/src/commands/cache.definition.ts +++ b/src/commands/cache.definition.ts @@ -1,6 +1,6 @@ // The `cache` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const cacheDefinition: CommandDefinition = { name: 'cache', diff --git a/src/commands/cache.ts b/src/commands/cache.ts index df4a1b1a..47ca6dc6 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -1,15 +1,15 @@ // cache command — manage wallet state cache // cache clear [--network ] [--wallet ] -import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; -import { UsageError, throwIfCancelled } from '../lib/errors.ts'; -import { clearWalletCache } from '../lib/wallet-cache.ts'; -import { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from '../lib/reader-cache-files.ts'; -import { engineFor } from '../lib/engine.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { clearWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveNetworkName } from '../lib/resolve-network.ts'; -import { green } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { green } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { clearChainCaches } from '../lib/chain-caches.ts'; export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): Promise { diff --git a/src/commands/chain.guidance.ts b/src/commands/chain.guidance.ts index 71714605..3abf6b0e 100644 --- a/src/commands/chain.guidance.ts +++ b/src/commands/chain.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each // naming its section and its place there. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; export const chainGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/connect.guidance.ts b/src/commands/connect.guidance.ts index 271494b4..8528a471 100644 --- a/src/commands/connect.guidance.ts +++ b/src/commands/connect.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; export const connectGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index f1389b08..d27c5d3f 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -1,6 +1,6 @@ // The `contract` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '../lib/command-definition.ts'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** The subcommands that reach a chain: inspect reads only the compiled contract (--path, --managed, --name). */ const ON_CHAIN: readonly string[] = ['deploy', 'call', 'state']; diff --git a/src/commands/contract.guidance.ts b/src/commands/contract.guidance.ts index 77c5be9f..03a78cce 100644 --- a/src/commands/contract.guidance.ts +++ b/src/commands/contract.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; export const contractGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 3d2d8a04..5569115c 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -1,18 +1,18 @@ // Contract commands — inspect, deploy, call, and query state for compiled Midnight contracts. import { resolve } from 'node:path'; -import { type ParsedArgs, getFlag, hasFlag, requireFlag } from '../lib/argv.ts'; -import { CancelledError, UsageError, throwIfCancelled } from '../lib/errors.ts'; -import { untilCancelled } from '../lib/sleep.ts'; -import type { CallContext, CallOutput } from '../lib/call-context.ts'; -import { header, keyValue } from '../ui/format.ts'; -import { bold, dim, teal, yellow, green } from '../ui/colors.ts'; - -import { type Payer, payerFor, resolvePayingTarget } from '../lib/payer.ts'; +import { type ParsedArgs, getFlag, hasFlag, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { CancelledError, UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { untilCancelled } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { header, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim, teal, yellow, green } from '@kuiralabs/midnight-cli-core/ui/colors'; + +import { type Payer, payerFor, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { validateContractAddress } from '../lib/contract/validate.ts'; -import { engineFor, type RawStateValue } from '../lib/engine.ts'; +import { engineFor, type RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; import { findContractInfo, diff --git a/src/commands/dev.definition.ts b/src/commands/dev.definition.ts index 60d1253e..31a6c26c 100644 --- a/src/commands/dev.definition.ts +++ b/src/commands/dev.definition.ts @@ -1,6 +1,6 @@ // The `dev` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const devDefinition: CommandDefinition = { name: 'dev', diff --git a/src/commands/dev.guidance.ts b/src/commands/dev.guidance.ts index 913cff30..14ea6b7f 100644 --- a/src/commands/dev.guidance.ts +++ b/src/commands/dev.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; export const devGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/dev.ts b/src/commands/dev.ts index 90435a2a..cbf20949 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -3,9 +3,9 @@ // M2: `d` keypress deploys the current compiled artifact, `q` quits cleanly. import { resolve, relative } from 'node:path'; -import { type ParsedArgs } from '../lib/argv.ts'; -import { payerFor } from '../lib/payer.ts'; -import type { CallContext, CallOutput } from '../lib/call-context.ts'; +import { type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { isPassphraseSet, unlockPassphrase } from '../lib/passphrase.ts'; import { detectProject, type ProjectInfo } from '../lib/dev/detect-project.ts'; import { runCompile, type CompileResult } from '../lib/dev/compile.ts'; @@ -19,8 +19,8 @@ import { } from '../lib/dev/provision-wallets.ts'; import { startKeyDispatcher } from '../ui/dev-keys.ts'; import { findWitnessFile, buildMissingWitnessError } from '../lib/contract/witness-discovery.ts'; -import { header, divider, keyValue } from '../ui/format.ts'; -import { bold, dim, red, teal, yellow } from '../ui/colors.ts'; +import { header, divider, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim, red, teal, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; /** Wallet used when `d` deploys. Must be one of the provisioned dev-* names. */ diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index f881c71e..e9b741fe 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -1,6 +1,6 @@ // The `dust` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const dustDefinition: CommandDefinition = { name: 'dust', diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 473dcd82..b5551393 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -2,18 +2,18 @@ // Usage: midnight dust register | midnight dust status | midnight dust export -import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites } from '../lib/argv.ts'; -import { UsageError, throwIfCancelled } from '../lib/errors.ts'; +import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; -import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '../lib/network.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { checkBalance } from '../lib/balance-subscription.ts'; -import { engineFor } from '../lib/engine.ts'; -import { header, keyValue, divider, formatDust, successMessage, toDust } from '../ui/format.ts'; -import { bold, dim, yellow } from '../ui/colors.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { header, keyValue, divider, formatDust, successMessage, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '../lib/call-context.ts'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function dustCommand(args: ParsedArgs, ctx: CallContext): Promise { const subcommand = args.subcommand; diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index 9aa7d0d5..a225af8a 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -1,6 +1,6 @@ // The `generate` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const generateDefinition: CommandDefinition = { name: 'generate', diff --git a/src/commands/generate.ts b/src/commands/generate.ts index b16ed49e..50b36a13 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -5,19 +5,19 @@ import * as fs from 'fs'; import * as path from 'path'; -import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { engineFor } from '../lib/engine.ts'; -import { resolveNetworkName } from '../lib/resolve-network.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { passphraseForNewSecret } from '../lib/passphrase.ts'; import { parseSeedHex } from '../lib/seed-resolver.ts'; -import { header, keyValue, divider, formatAddress } from '../ui/format.ts'; -import { bold, yellow, dim, green } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { header, keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, yellow, dim, green } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { getDefaultWalletPath } from '../lib/wallet-paths.ts'; -import { throwIfCancelled } from '../lib/errors.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function generateCommand(args: ParsedArgs, ctx: CallContext): Promise { const networkName = resolveNetworkName({ args }); diff --git a/src/commands/genesis-address.definition.ts b/src/commands/genesis-address.definition.ts index bf545c5c..d1f44502 100644 --- a/src/commands/genesis-address.definition.ts +++ b/src/commands/genesis-address.definition.ts @@ -1,6 +1,6 @@ // The `genesis-address` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const genesisAddressDefinition: CommandDefinition = { name: 'genesis-address', diff --git a/src/commands/genesis-address.ts b/src/commands/genesis-address.ts index 8492495c..4e53d89e 100644 --- a/src/commands/genesis-address.ts +++ b/src/commands/genesis-address.ts @@ -1,12 +1,12 @@ // genesis-address command — display the genesis wallet address (seed 0x01) -import { type ParsedArgs, hasFlag } from '../lib/argv.ts'; -import { GENESIS_SEED } from '../lib/constants.ts'; -import { engineFor } from '../lib/engine.ts'; -import { resolveNetworkName } from '../lib/resolve-network.ts'; -import { keyValue, divider, formatAddress } from '../ui/format.ts'; -import { dim } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function genesisAddressCommand(args: ParsedArgs, ctx: CallContext): Promise { const networkName = resolveNetworkName({ args }); diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index ff9cc6ce..89b6670a 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -1,6 +1,6 @@ // The `grant` command, described once. -import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '../lib/command-definition.ts'; +import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** A grant request can run: its arguments, the network, the account and the wallet are all in order. */ async function checkGrant(params: Readonly>, call: ToolCheckCall) { diff --git a/src/commands/grant.guidance.ts b/src/commands/grant.guidance.ts index 9ae61ba6..e029647a 100644 --- a/src/commands/grant.guidance.ts +++ b/src/commands/grant.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; export const grantGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/grant.ts b/src/commands/grant.ts index 79f74b66..0eaf1fef 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -9,21 +9,21 @@ import { existsSync } from 'node:fs'; // confirmed. The others are paid by this wallet, through its DApp connector in // this process: no server, no port. -import { type ParsedArgs, hasFlag, getFlag } from '../lib/argv.ts'; -import { UsageError } from '../lib/errors.ts'; -import { ERROR_CODES, classifyError } from '../lib/exit-codes.ts'; +import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { ERROR_CODES, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { type GrantAccount, openGrantAccount, ownerDeviceOf } from '../lib/grant/account.ts'; import { deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; import { type OwnerCommandOutput, grantRequestOf, grantsOf, issue, issuePreview, revoke, revokeAll, statusOf } from '../lib/grant/owner-commands.ts'; import { prepareGrant } from '../lib/grant/prepare.ts'; import { type GrantRequest, paysAFee } from '../lib/grant/request.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { type PayingWallet, openPayingWallet } from '../lib/grant/fee-wallet.ts'; -import { payerFor } from '../lib/payer.ts'; -import { dim } from '../ui/colors.ts'; -import { header, keyValue, formatNight } from '../ui/format.ts'; -import type { Spinner } from '../ui/spinner.ts'; -import { throwIfCancelled } from '../lib/errors.ts'; +import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { header, keyValue, formatNight } from '@kuiralabs/midnight-cli-core/ui/format'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; const SPINNER_LABEL: Record = { deploy: 'Deploying the account...', diff --git a/src/commands/help.definition.ts b/src/commands/help.definition.ts index 947719fb..819a7a58 100644 --- a/src/commands/help.definition.ts +++ b/src/commands/help.definition.ts @@ -1,6 +1,6 @@ // The `help` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const helpDefinition: CommandDefinition = { name: 'help', diff --git a/src/commands/help.ts b/src/commands/help.ts index 8f3e1691..f969b3cd 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -5,17 +5,17 @@ // Every list of commands it shows comes from the command registry, and the // agent manual from the installed packages' guidance. -import { type ParsedArgs, hasFlag } from '../lib/argv.ts'; -import { bold, teal, gray, dim } from '../ui/colors.ts'; -import { header } from '../ui/format.ts'; +import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { bold, teal, gray, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { header } from '@kuiralabs/midnight-cli-core/ui/format'; import { animateMaterialize } from '../ui/animate.ts'; import { WORDMARK_BIG } from '../ui/art.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { agentManual } from '../lib/agent-manual.ts'; -import { commandHelpSpecs, introBriefs, type CommandHelpSpec } from '../lib/command-definition.ts'; +import { commandHelpSpecs, introBriefs, type CommandHelpSpec } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { hasShownIntroThisSession, markIntroShown } from '../lib/intro-marker.ts'; -import { UsageError } from '../lib/errors.ts'; -import type { CallContext, CallOutput } from '../lib/call-context.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { PKG_NAME, PKG_VERSION, PKG_DESCRIPTION } from '../lib/pkg.ts'; type CommandSpec = CommandHelpSpec; diff --git a/src/commands/info.definition.ts b/src/commands/info.definition.ts index 4609f0e9..f154373f 100644 --- a/src/commands/info.definition.ts +++ b/src/commands/info.definition.ts @@ -1,6 +1,6 @@ // The `info` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const infoDefinition: CommandDefinition = { name: 'info', diff --git a/src/commands/info.ts b/src/commands/info.ts index 0e41a266..ed198873 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -1,13 +1,13 @@ // info command — display wallet metadata (no secrets) // Shows addresses for all networks + shielded, creation date, file path -import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { loadWalletConfig, resolveWalletPath } from '../lib/wallet-config.ts'; -import { resolveNetworkName } from '../lib/resolve-network.ts'; -import { header, divider } from '../ui/format.ts'; -import { formatAddress } from '../ui/format.ts'; -import { bold, dim, teal } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; +import { formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim, teal } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function infoCommand(args: ParsedArgs, ctx: CallContext): Promise { const resolvedPath = resolveWalletPath(getFlag(args, 'wallet')); diff --git a/src/commands/inspect-cost.definition.ts b/src/commands/inspect-cost.definition.ts index 661a416a..ba246ff7 100644 --- a/src/commands/inspect-cost.definition.ts +++ b/src/commands/inspect-cost.definition.ts @@ -1,6 +1,6 @@ // The `inspect-cost` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const inspectCostDefinition: CommandDefinition = { name: 'inspect-cost', diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 8561a15d..98306d84 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -2,13 +2,13 @@ // ledger parameters of its latest block, as the engine for the chain's SDK // set reads them. -import { type ParsedArgs, hasFlag } from '../lib/argv.ts'; -import { header, keyValue, divider } from '../ui/format.ts'; -import { bold, dim } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; +import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { header, keyValue, divider } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { fetchLedgerParameters } from '../lib/chain-params.ts'; -import { engineFor } from '../lib/engine.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; const UNITS: Record = { diff --git a/src/commands/localnet.definition.ts b/src/commands/localnet.definition.ts index 86c28cb5..61dcfef0 100644 --- a/src/commands/localnet.definition.ts +++ b/src/commands/localnet.definition.ts @@ -1,6 +1,6 @@ // The `localnet` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const localnetDefinition: CommandDefinition = { name: 'localnet', diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index 80c64ba8..4f129caf 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -2,9 +2,9 @@ // Subcommands: up, down, status, logs import { spawn } from 'child_process'; -import { type ParsedArgs, hasFlag, getFlag } from '../lib/argv.ts'; -import { CancelledError, UsageError } from '../lib/errors.ts'; -import { execProgram, ProgramFailedError, type ExecRunner } from '../lib/exec-program.ts'; +import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { CancelledError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { execProgram, ProgramFailedError, type ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; import { assertLocalnetCanStart, checkDockerAvailable, @@ -18,10 +18,10 @@ import { type DockerCall, type ServiceStatus, } from '../lib/localnet.ts'; -import { header, divider } from '../ui/format.ts'; -import { bold, green, red, dim, yellow } from '../ui/colors.ts'; +import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, green, red, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '../lib/call-context.ts'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; const VALID_SUBCOMMANDS = ['up', 'stop', 'down', 'status', 'logs', 'clean'] as const; type Subcommand = typeof VALID_SUBCOMMANDS[number]; @@ -71,9 +71,9 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) const { waitForFirstBlock } = await import('../lib/node-ready.ts'); const { waitForAddressFunded } = await import('../lib/indexer-ready.ts'); const { waitForProofServerReady } = await import('../lib/proof-server-ready.ts'); - const { getNetworkConfig } = await import('../lib/network.ts'); - const { engineFor } = await import('../lib/engine.ts'); - const { GENESIS_SEED } = await import('../lib/constants.ts'); + const { getNetworkConfig } = await import('@kuiralabs/midnight-cli-core/lib/network'); + const { engineFor } = await import('@kuiralabs/midnight-cli-core/lib/engine'); + const { GENESIS_SEED } = await import('@kuiralabs/midnight-cli-core/lib/constants'); const netCfg = getNetworkConfig('undeployed'); await waitForFirstBlock(netCfg.node, { timeoutMs: 30_000, signal: ctx.signal }); diff --git a/src/commands/manual.definition.ts b/src/commands/manual.definition.ts index 4e80fefd..5311dc48 100644 --- a/src/commands/manual.definition.ts +++ b/src/commands/manual.definition.ts @@ -1,6 +1,6 @@ // The `manual` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const manualDefinition: CommandDefinition = { name: 'manual', diff --git a/src/commands/manual.ts b/src/commands/manual.ts index e7186f22..f3d1d120 100644 --- a/src/commands/manual.ts +++ b/src/commands/manual.ts @@ -5,9 +5,9 @@ // search and scroll. Disable with --no-pager. import { spawn } from 'node:child_process'; -import { type ParsedArgs, hasFlag, getFlag } from '../lib/argv.ts'; -import type { CallContext, CallOutput } from '../lib/call-context.ts'; -import { bold, dim, teal, yellow, white } from '../ui/colors.ts'; +import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { bold, dim, teal, yellow, white } from '@kuiralabs/midnight-cli-core/ui/colors'; import { helpSpecs, type CommandSpec } from './help.ts'; import { PKG_NAME, PKG_VERSION, PKG_REPOSITORY_URL } from '../lib/pkg.ts'; diff --git a/src/commands/serve.definition.ts b/src/commands/serve.definition.ts index 39a3cfb1..422c621e 100644 --- a/src/commands/serve.definition.ts +++ b/src/commands/serve.definition.ts @@ -1,6 +1,6 @@ // The `serve` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const serveDefinition: CommandDefinition = { name: 'serve', diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 410afe73..bab40936 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -2,23 +2,23 @@ // Usage: midnight serve [--port 9932] [--wallet path] [--network name] // [--approve-all | --approve-fees] [--no-auto-approve-reads] [--json] -import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; +import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; -import { applyEndpointOverrides } from '../lib/network.ts'; -import { engineFor, type DAppConnector, type DAppConnectorCallbacks } from '../lib/engine.ts'; -import { OPERATOR_REJECTED_MESSAGE } from '../lib/connector-api.ts'; -import type { PhaseTiming } from '../lib/phase-tracker.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; +import { engineFor, type DAppConnector, type DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import type { PhaseTiming } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; -import { DEFAULT_SERVE_PORT } from '../lib/constants.ts'; +import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; import { shieldedSyncEnabled } from '../lib/shielded-policy.ts'; -import { header, keyValue, divider, formatAddress, toDust } from '../ui/format.ts'; -import { parseFeeLimits } from '../lib/fee-limits.ts'; -import { describeApprovalPolicy } from '../lib/approval.ts'; -import { bold, dim, teal, green, red } from '../ui/colors.ts'; -import type { Spinner } from '../ui/spinner.ts'; -import type { CallContext } from '../lib/call-context.ts'; -import { UsageError, throwIfCancelled } from '../lib/errors.ts'; +import { header, keyValue, divider, formatAddress, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { parseFeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; +import { describeApprovalPolicy } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { bold, dim, teal, green, red } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function serveCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); diff --git a/src/commands/status.definition.ts b/src/commands/status.definition.ts index 8722c00d..db1bd520 100644 --- a/src/commands/status.definition.ts +++ b/src/commands/status.definition.ts @@ -1,6 +1,6 @@ // The `status` command, described once. -import type { CommandDefinition } from '../lib/command-definition.ts'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const statusDefinition: CommandDefinition = { name: 'status', diff --git a/src/commands/status.ts b/src/commands/status.ts index 563f54e1..2d32ef75 100644 --- a/src/commands/status.ts +++ b/src/commands/status.ts @@ -5,16 +5,16 @@ // canary data from the dashboard (hourly monitoring history). // No wallet or SDK needed — works from anywhere. -import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; -import { DASHBOARD_BASE_URL } from '../lib/constants.ts'; -import { BlockfrostProjectIdRequiredError, assertEndpointUsable, endpointRefusal } from '../lib/blockfrost.ts'; -import { isValidNetworkName, resolveNetworkConfig, type NetworkName } from '../lib/network.ts'; -import { resolveBlockfrostProjectId } from '../lib/resolve-network.ts'; -import { CancelledError } from '../lib/errors.ts'; -import { header, divider } from '../ui/format.ts'; -import { bold, dim, teal, green, red, gray } from '../ui/colors.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { DASHBOARD_BASE_URL } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { BlockfrostProjectIdRequiredError, assertEndpointUsable, endpointRefusal } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { isValidNetworkName, resolveNetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { resolveBlockfrostProjectId } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim, teal, green, red, gray } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext, CallOutput, CommandOutcome } from '../lib/call-context.ts'; +import type { CallContext, CallOutput, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; // ── Types matching status.json contract ── @@ -149,7 +149,7 @@ async function tryDetectNetwork(args: ParsedArgs): Promise { // Check config file for default network try { - const { loadCliConfig } = await import('../lib/cli-config.ts'); + const { loadCliConfig } = await import('@kuiralabs/midnight-cli-core/lib/cli-config'); const config = loadCliConfig(); if (config.network && isValidNetworkName(config.network)) return config.network; } catch { diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index 6b6dbaad..82f84e1c 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -1,6 +1,6 @@ // The `test` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const testDefinition: CommandDefinition = { name: 'test', diff --git a/src/commands/test.ts b/src/commands/test.ts index 38886573..6f3f7f7a 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -5,12 +5,12 @@ import { StringDecoder } from 'node:string_decoder'; import { join } from 'node:path'; import { mkdirSync } from 'node:fs'; -import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; -import { CancelledError, throwIfCancelled, UsageError } from '../lib/errors.ts'; -import type { CallContext, CallOutput, CallProgress, CommandOutcome } from '../lib/call-context.ts'; -import { header, keyValue, divider } from '../ui/format.ts'; -import { bold, dim, green, red, teal, yellow } from '../ui/colors.ts'; -import type { Spinner } from '../ui/spinner.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { CancelledError, throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { CallContext, CallOutput, CallProgress, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { header, keyValue, divider } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim, green, red, teal, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { discoverDappConfig, discoverTestSuites, loadAssertions, loadActions, loadPrompt } from '../lib/test/discovery.ts'; import { createPrepContext, type TestRunResult, type PrepStepResult } from '../lib/test/types.ts'; @@ -542,7 +542,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): } const { runActions, diffState } = await import('../lib/test/actions-runner.ts'); - const { resolveNetwork } = await import('../lib/resolve-network.ts'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ @@ -551,7 +551,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): // mn serve should already be started by the prep step (mn-serve) // Use the serve port from the prep context if available, otherwise default - const { DEFAULT_SERVE_PORT } = await import('../lib/constants.ts'); + const { DEFAULT_SERVE_PORT } = await import('@kuiralabs/midnight-cli-core/lib/constants'); const servePort = prep.serveHandle?.port ?? DEFAULT_SERVE_PORT; const redeployFlag = hasFlag(args, 'redeploy'); diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 45cbccf0..ce7631e3 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -1,6 +1,6 @@ // The `transfer` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '../lib/command-definition.ts'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const transferDefinition: CommandDefinition = { name: 'transfer', diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 9b66fd9a..7c3d9d14 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -1,17 +1,17 @@ // transfer command — send NIGHT from my wallet to another address // Usage: midnight transfer [--shielded] -import { throwIfCancelled } from '../lib/errors.ts'; -import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '../lib/argv.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveShieldedAddress, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveNetwork } from '../lib/resolve-network.ts'; -import { applyEndpointOverrides } from '../lib/network.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; import { resolveTransferRequest, type TransferRequest } from '../lib/transfer-request.ts'; -import { engineFor } from '../lib/engine.ts'; -import { nightToMicro } from '../lib/amount.ts'; -import { header, keyValue, divider, formatAddress, successMessage } from '../ui/format.ts'; -import { bold, dim } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 9bc32540..f0ed60e2 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -1,6 +1,6 @@ // The `wallet` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '../lib/command-definition.ts'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const walletDefinition: CommandDefinition = { name: 'wallet', diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index 2942ff21..a03c76a4 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -3,7 +3,7 @@ // skills, each naming its section and its place there, and its tools' rows in // the manual's tools table. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; export const walletGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index 19ace2e6..3616f720 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -2,11 +2,11 @@ // Subcommands: generate, list, use, info, remove import * as fs from 'fs'; -import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '../lib/argv.ts'; -import { UsageError, throwIfCancelled } from '../lib/errors.ts'; +import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { mnemonicToEntropy } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { resolveNetworkName } from '../lib/resolve-network.ts'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { parseSeedHex } from '../lib/seed-resolver.ts'; import { loadWalletConfig, @@ -21,10 +21,10 @@ import { import { passphraseForNewSecret } from '../lib/passphrase.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../lib/wallet-create.ts'; import { coinKeyOfWallet, type ProtectorResult, type WalletCommandContext } from '../lib/wallet-protector.ts'; -import { header, keyValue, divider, formatAddress } from '../ui/format.ts'; -import { bold, yellow, dim, green, teal } from '../ui/colors.ts'; -import type { CallContext } from '../lib/call-context.ts'; -import { stateRoot } from '../lib/state-root.ts'; +import { header, keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; +import { bold, yellow, dim, green, teal } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; export default async function walletCommand(args: ParsedArgs, ctx: WalletCommandContext): Promise { const subcommand = args.subcommand; diff --git a/src/engine/rc/addresses.ts b/src/engine/rc/addresses.ts index 5aea5a8d..e103402b 100644 --- a/src/engine/rc/addresses.ts +++ b/src/engine/rc/addresses.ts @@ -2,8 +2,8 @@ // must be on. import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; -import { networkIdForName } from '../../lib/network-id.ts'; -import type { NetworkName } from '../../lib/network.ts'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; /** A shielded address on `network`, as the SDK reads it. Throws when it is not one. */ export function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress { diff --git a/src/engine/rc/airdrop.ts b/src/engine/rc/airdrop.ts index 51fc24cf..f31eb5aa 100644 --- a/src/engine/rc/airdrop.ts +++ b/src/engine/rc/airdrop.ts @@ -2,10 +2,10 @@ // devnet. `mn airdrop` and `mn dev` both fund wallets through here; the // caller has already checked that the network is the local one. -import { GENESIS_SEED } from '../../lib/constants.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; -import type { AirdropParams } from '../../lib/engine.ts'; -export type { AirdropParams } from '../../lib/engine.ts'; +import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; /** Sends `amountNight` NIGHT from genesis to `recipientAddress`. */ diff --git a/src/engine/rc/contract-providers.ts b/src/engine/rc/contract-providers.ts index d3943a95..dd94b435 100644 --- a/src/engine/rc/contract-providers.ts +++ b/src/engine/rc/contract-providers.ts @@ -2,9 +2,9 @@ // Deploy/call use the runner (generated scripts in dApp context) which build their own providers. import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; -import { assertEndpointUsable } from '../../lib/blockfrost.ts'; -import type { NetworkConfig } from '../../lib/network.ts'; -import type { RawStateValue } from '../../lib/engine.ts'; +import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; import { describeRawState } from './raw-state.ts'; /** diff --git a/src/engine/rc/contract-scripts.ts b/src/engine/rc/contract-scripts.ts index 3f91388e..584d55e0 100644 --- a/src/engine/rc/contract-scripts.ts +++ b/src/engine/rc/contract-scripts.ts @@ -8,8 +8,8 @@ import { existsSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; -import type { CallScript, DeployScript, ScriptParts, StateScript } from '../../lib/engine.ts'; -import type { NetworkConfig } from '../../lib/network.ts'; +import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; /** * Every package a generated script imports, and the compact runtime the diff --git a/src/engine/rc/dapp-connector.ts b/src/engine/rc/dapp-connector.ts index 1c5250a2..760d5e13 100644 --- a/src/engine/rc/dapp-connector.ts +++ b/src/engine/rc/dapp-connector.ts @@ -2,35 +2,35 @@ // Factory function returns a handler map for ws-rpc.ts to dispatch import * as rx from 'rxjs'; -import { notice } from '../../lib/notices.ts'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { TransactionStage, WalletTransaction } from '@midnightntwrk/wallet-sdk'; import type { FacadeState, WalletEntry } from '@midnightntwrk/wallet-sdk/facade'; import type { FinalizedTx } from '@midnightntwrk/wallet-sdk'; import { type FacadeBundle, hasDustAvailable } from './facade.ts'; -import { LEDGER_9_FORK_VERSION, type NetworkConfig } from '../../lib/network.ts'; -import type { ApprovalOptions } from '../../lib/approval.ts'; -import { promptApproval } from '../../lib/approval.ts'; -import { createApiError, type RpcHandler, type RpcHandlerContext } from '../../lib/connector-api.ts'; -import { createPhaseTracker, type PhaseTracker } from '../../lib/phase-tracker.ts'; -import { toHex, fromHex } from '../../lib/tx-serde.ts'; -import { getNetworkId } from '../../lib/network-id.ts'; -import { isDustShortage } from '../../lib/sdk-errors.ts'; -import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '../../lib/fee-limits.ts'; +import { LEDGER_9_FORK_VERSION, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { createApiError, type RpcHandler, type RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { createPhaseTracker, type PhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; +import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; -import { decodeSignPayload, signedMessageBytes } from '../../lib/sign-data.ts'; -import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '../../lib/dust-wait.ts'; -import { formatWait } from '../../lib/duration.ts'; +import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; +import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; import { fetchPartialSuccessSegments, type SegmentResult } from '../../lib/tx-segments.ts'; import { walletsBelowLedger9 } from '../../lib/ledger-guard.ts'; -import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '../../lib/constants.ts'; -import { dim } from '../../ui/colors.ts'; -import { roughDust, toDust } from '../../ui/format.ts'; -import type { DAppConnector, DAppConnectorCallbacks } from '../../lib/engine.ts'; -export type { DAppConnector, DAppConnectorCallbacks } from '../../lib/engine.ts'; +import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; // ── Types ── @@ -139,8 +139,8 @@ function extractErrorDetail(err: unknown): string { return deduped.join(' → ') || 'Unknown error'; } -export { OPERATOR_REJECTED_MESSAGE } from '../../lib/connector-api.ts'; -import { OPERATOR_REJECTED_MESSAGE } from '../../lib/connector-api.ts'; +export { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; /** The connector API's history entry for one wallet history entry. */ export type HistoryEntry = { diff --git a/src/engine/rc/derive-address.ts b/src/engine/rc/derive-address.ts index e5e6cc41..7a6cb8c7 100644 --- a/src/engine/rc/derive-address.ts +++ b/src/engine/rc/derive-address.ts @@ -10,9 +10,9 @@ import { ShieldedEncryptionPublicKey, } from '@midnightntwrk/wallet-sdk/address-format'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { type NetworkName, getValidNetworkNames } from '../../lib/network.ts'; +import { type NetworkName, getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { deriveShieldedSeed } from './derivation.ts'; -import { networkIdForName } from '../../lib/network-id.ts'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; /** * Derive an unshielded address from a seed buffer, network, and optional key index. diff --git a/src/engine/rc/dust-balance-direct.ts b/src/engine/rc/dust-balance-direct.ts index cb34fb8c..4d514bad 100644 --- a/src/engine/rc/dust-balance-direct.ts +++ b/src/engine/rc/dust-balance-direct.ts @@ -24,7 +24,7 @@ import { INITIAL_NIGHT_DUST_RATIO, INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from '../../lib/constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; const SUBSCRIPTION_QUERY = ` diff --git a/src/engine/rc/dust-direct-cache.ts b/src/engine/rc/dust-direct-cache.ts index e1d0c82d..09f30bbc 100644 --- a/src/engine/rc/dust-direct-cache.ts +++ b/src/engine/rc/dust-direct-cache.ts @@ -14,10 +14,10 @@ import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveDustSeed } from './derivation.ts'; import { type DustRetention } from './dust-direct.ts'; -import { dustCacheDir, getDustCachePath } from '../../lib/reader-cache-files.ts'; +import { dustCacheDir, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; // v2 added the retention fields (owned generation indices + frontier) that the // generation-tree collapse needs. v1 caches lack them and are invalidated, so diff --git a/src/engine/rc/dust-direct.ts b/src/engine/rc/dust-direct.ts index 084b7079..bf68c02e 100644 --- a/src/engine/rc/dust-direct.ts +++ b/src/engine/rc/dust-direct.ts @@ -16,9 +16,9 @@ import { INITIAL_NIGHT_DUST_RATIO, INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from '../../lib/constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; -import { settings } from '../../lib/settings.ts'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; // MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): settings().isDustCollapseOff. diff --git a/src/engine/rc/dust-export.ts b/src/engine/rc/dust-export.ts index 348a96fa..dca16597 100644 --- a/src/engine/rc/dust-export.ts +++ b/src/engine/rc/dust-export.ts @@ -19,11 +19,11 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; -import { type NetworkConfig } from '../../lib/network.ts'; +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from '../../lib/verbose.ts'; -import type { DustExportResult } from '../../lib/engine.ts'; -export type { DustExportResult } from '../../lib/engine.ts'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export interface DustExportOptions { diff --git a/src/engine/rc/dust-register.ts b/src/engine/rc/dust-register.ts index 3ea34ed1..5b149356 100644 --- a/src/engine/rc/dust-register.ts +++ b/src/engine/rc/dust-register.ts @@ -2,14 +2,14 @@ // Dust to spend. `mn dust register` and `mn dev` both register through here. import { waitForLiteSyncedState } from './facade.ts'; -import { throwIfCancelled } from '../../lib/errors.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { ensureDust } from './transfer.ts'; import { defaultRepository } from './wallet-data-repository.ts'; -import type { NetworkConfig } from '../../lib/network.ts'; -import type { CallSdkWarnings } from '../../lib/sdk-warnings.ts'; -import type { VerboseLog } from '../../lib/verbose.ts'; -import type { DustRegisterOptions, DustRegistration } from '../../lib/engine.ts'; -export type { DustRegisterOptions, DustRegistration } from '../../lib/engine.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; diff --git a/src/engine/rc/dust-sync-native.ts b/src/engine/rc/dust-sync-native.ts index ac9fc537..d7b03aa8 100644 --- a/src/engine/rc/dust-sync-native.ts +++ b/src/engine/rc/dust-sync-native.ts @@ -4,7 +4,7 @@ // fails, callers fall back to the WASM path — the sidecar is an optional // accelerator, never a hard dependency. -import { assertEndpointUsable } from '../../lib/blockfrost.ts'; +import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { spawn } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; @@ -13,15 +13,15 @@ import { fileURLToPath } from 'node:url'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveDustSeed } from './derivation.ts'; -import type { NetworkConfig } from '../../lib/network.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { settings } from '../../lib/settings.ts'; -import { cacheRootDir } from '../../lib/wallet-cache.ts'; -import { nativeCheckpointName } from '../../lib/reader-cache-files.ts'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { cacheRootDir } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; /** Sidecar checkpoint JSON shape (snake_case — matches the Rust `Checkpoint`). */ export interface SidecarCheckpoint { diff --git a/src/engine/rc/dust-wallet.ts b/src/engine/rc/dust-wallet.ts index d0750d3b..b011a7f4 100644 --- a/src/engine/rc/dust-wallet.ts +++ b/src/engine/rc/dust-wallet.ts @@ -13,8 +13,8 @@ import { CustomForkingDustWallet, DustWallet as SdkDustWallet, asV8DustParameter import { V1Builder } from '@midnightntwrk/wallet-sdk/dust/v1'; import { Migration, Transacting, V2Builder, WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; import { LedgerOps } from '@midnightntwrk/wallet-sdk/utilities'; -import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '../../lib/dust-balancing-plan.ts'; -import { type DustShortfall, withDustShortfall } from '../../lib/sdk-errors.ts'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '@kuiralabs/midnight-cli-core/lib/dust-balancing-plan'; +import { type DustShortfall, withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; type SdkTransacting = Transacting.TransactingCapabilityImplementation; type RecipeArguments = Parameters; diff --git a/src/engine/rc/facade.ts b/src/engine/rc/facade.ts index d8b078b0..021381b2 100644 --- a/src/engine/rc/facade.ts +++ b/src/engine/rc/facade.ts @@ -1,5 +1,5 @@ import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; -import { notice } from '../../lib/notices.ts'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; import { UnshieldedWallet, createKeystore, @@ -18,22 +18,22 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import * as rx from 'rxjs'; -import { type NetworkConfig } from '../../lib/network.ts'; +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { FORK_SCHEDULE } from './fork-schedule.ts'; -import { getNetworkId } from '../../lib/network-id.ts'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; -import { type WalletCacheData } from '../../lib/wallet-cache.ts'; +import { type WalletCacheData } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, SYNC_TIMEOUT_MS, PRE_SEND_SYNC_TIMEOUT_MS, -} from '../../lib/constants.ts'; -import type { VerboseLog } from '../../lib/verbose.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import { assertNetworkAnswers } from '../../lib/endpoint-check.ts'; import { isStreamEmpty } from '../../lib/event-tip.ts'; -import { CancelledError, throwIfCancelled } from '../../lib/errors.ts'; +import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust diff --git a/src/engine/rc/index.ts b/src/engine/rc/index.ts index a8703e9e..7c0dc975 100644 --- a/src/engine/rc/index.ts +++ b/src/engine/rc/index.ts @@ -1,7 +1,7 @@ // The engine for the SDK's release candidates (rc): the wallet SDK 2.0 // release candidates, ledger 9 and midnight-js 5 as mn pins them. -import type { Engine } from '../../lib/engine.ts'; +import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; import * as ledger from '@midnightntwrk/ledger-v9'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { blockLimitsOf } from './ledger-parameters.ts'; diff --git a/src/engine/rc/ledger-parameters.ts b/src/engine/rc/ledger-parameters.ts index 2d32b92a..decf682d 100644 --- a/src/engine/rc/ledger-parameters.ts +++ b/src/engine/rc/ledger-parameters.ts @@ -3,7 +3,7 @@ // normalizeFullness: normalized = value / limit, so limit = value / normalized. import * as ledger from '@midnightntwrk/ledger-v9'; -import type { BlockLimits } from '../../lib/engine.ts'; +import type { BlockLimits } from '@kuiralabs/midnight-cli-core/lib/engine'; type Dimension = keyof BlockLimits; diff --git a/src/engine/rc/raw-state.ts b/src/engine/rc/raw-state.ts index b6798b70..93b18a95 100644 --- a/src/engine/rc/raw-state.ts +++ b/src/engine/rc/raw-state.ts @@ -3,7 +3,7 @@ // layout the fields have no names, so cells show their field-aligned bytes in // hex and maps show their size, as the parsed state does. -import type { RawStateValue } from '../../lib/engine.ts'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; const toHex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); diff --git a/src/engine/rc/shielded-direct-cache.ts b/src/engine/rc/shielded-direct-cache.ts index e069e606..c6116908 100644 --- a/src/engine/rc/shielded-direct-cache.ts +++ b/src/engine/rc/shielded-direct-cache.ts @@ -9,18 +9,18 @@ // Security: the cached state contains owned coins but NOT the secret keys. Same // sensitivity as the wallet file (mode 0o600). -import { bindCachesToIndexer } from '../../lib/cache-indexer.ts'; +import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '../../lib/constants.ts'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveShieldedSeed } from './derivation.ts'; import { readShieldedBalanceDirect, type ShieldedDirectOptions } from './shielded-direct.ts'; import { fetchEventTip, isCursorBeyondTip } from '../../lib/event-tip.ts'; -import { clearShieldedDirectCache, getShieldedCachePath } from '../../lib/reader-cache-files.ts'; +import { clearShieldedDirectCache, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; // v2: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis // hash, so the chain-id guard can't keep a ledger-8 cache off a ledger-9 chain. @@ -123,8 +123,8 @@ export function saveShieldedCache( } -export type { ShieldedBalanceResult, ShieldedCachedOptions } from '../../lib/engine.ts'; -import type { ShieldedBalanceResult, ShieldedCachedOptions } from '../../lib/engine.ts'; +export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; /** * Read the shielded NIGHT balance for a wallet seed, using (and refreshing) the diff --git a/src/engine/rc/transfer.ts b/src/engine/rc/transfer.ts index 8e80ea51..a39f6b19 100644 --- a/src/engine/rc/transfer.ts +++ b/src/engine/rc/transfer.ts @@ -2,17 +2,17 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { throwIfCancelled } from '../../lib/errors.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; import * as rx from 'rxjs'; -import { type NetworkConfig } from '../../lib/network.ts'; -import { getNetworkId } from '../../lib/network-id.ts'; +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; import { defaultRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from '../../lib/verbose.ts'; -import { nightToMicro } from '../../lib/amount.ts'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; import { NATIVE_TOKEN_TYPE, TOKEN_MULTIPLIER, @@ -26,7 +26,7 @@ import { SYNC_ATTEMPT_TIMEOUT_MS, DUST_COST_OVERHEAD, MIN_DUST_FOR_TRANSFER, -} from '../../lib/constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -53,19 +53,19 @@ export function validateRecipientAddress(address: string, networkConfig: Network // SDK error classifiers moved to ./sdk-errors.ts so wallet-data-repository // can import them without a circular dependency. Re-exported for callers // that still import from this module. -export { isDustRelatedError, isSdkInsufficientFundsError } from '../../lib/sdk-errors.ts'; -import { isColdStartRace, isDustRelatedError } from '../../lib/sdk-errors.ts'; -import { DustFeeNotGeneratedError, planRegistration } from '../../lib/dust-registration-plan.ts'; -import { formatWait } from '../../lib/duration.ts'; +export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { isColdStartRace, isDustRelatedError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; +import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; import { assertChainClockCurrent, fetchChainTime } from '../../lib/chain-clock.ts'; -import { awaitDustForFee, sleep } from '../../lib/dust-wait.ts'; +import { awaitDustForFee, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; /** How long the transfer retry waits for Dust to grow when the fee is above the pre-flight threshold. */ const DUST_GROW_WAIT_MS = 10_000; -import { toDust } from '../../ui/format.ts'; -import type { CallSdkWarnings } from '../../lib/sdk-warnings.ts'; -import type { EnsureDustResult, TransferParams, TransferResult } from '../../lib/engine.ts'; -export type { EnsureDustResult, TransferParams, TransferResult } from '../../lib/engine.ts'; +import { toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; /** Format milliseconds as "Xs" or "Xm Ys" for human-friendly elapsed display. */ diff --git a/src/engine/rc/tx-inspect.ts b/src/engine/rc/tx-inspect.ts index 5a6f1428..9f0c302d 100644 --- a/src/engine/rc/tx-inspect.ts +++ b/src/engine/rc/tx-inspect.ts @@ -2,7 +2,7 @@ // Used by the DApp Connector approval prompt to show Lace-style transaction summaries import { Transaction } from '@midnightntwrk/ledger-v9'; -import type { TransactionDetail } from '../../lib/engine.ts'; +import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; /** * Try to extract structured details from a transaction hex string. diff --git a/src/engine/rc/wallet-data-repository.ts b/src/engine/rc/wallet-data-repository.ts index b7faec63..b0ebc901 100644 --- a/src/engine/rc/wallet-data-repository.ts +++ b/src/engine/rc/wallet-data-repository.ts @@ -18,11 +18,11 @@ // tests against localnet — accepted scope per architecture-deepening.md. import { Buffer } from 'node:buffer'; -import { throwIfCancelled } from '../../lib/errors.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import * as ledger from '@midnightntwrk/ledger-v9'; -import type { NetworkConfig, NetworkName } from '../../lib/network.ts'; -import { isValidNetworkName } from '../../lib/network.ts'; +import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { isValidNetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { type FacadeState } from '@midnightntwrk/wallet-sdk/facade'; import { buildFacade, @@ -33,29 +33,29 @@ import { type SyncMode, overlayDustDirectSnapshot, } from './facade.ts'; -import { isColdStartRace } from '../../lib/sdk-errors.ts'; +import { isColdStartRace } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from './dust-direct-cache.ts'; -import { clearDustDirectCache } from '../../lib/reader-cache-files.ts'; +import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; import { loadWalletCache, saveWalletCache, clearWalletCache, validateWalletCacheChainId, type WalletCacheData, -} from '../../lib/wallet-cache.ts'; +} from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { getChainGenesisHash } from '../../lib/chain-id.ts'; import { assertLedgerSupported, fetchProtocolVersion } from '../../lib/ledger-guard.ts'; import { checkBalance, type BalanceSummary } from '../../lib/balance-subscription.ts'; import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; -import { bindCachesToIndexer, describeIndexerChange } from '../../lib/cache-indexer.ts'; +import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; -import type { VerboseLog } from '../../lib/verbose.ts'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import { callNodeRpc } from '../../lib/node-rpc.ts'; import { deriveDustSeed } from './derivation.ts'; import { deriveUnshieldedAddress } from './derive-address.ts'; import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '../../lib/event-tip.ts'; -import type { DustBalance, ReadOptions, UnshieldedView } from '../../lib/engine.ts'; -export type { DustBalance, ReadOptions, UnshieldedView } from '../../lib/engine.ts'; +import type { DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; // ── Public types ────────────────────────────────────────── diff --git a/src/engine/rc/wallet.ts b/src/engine/rc/wallet.ts index b76fc7be..58e3c28a 100644 --- a/src/engine/rc/wallet.ts +++ b/src/engine/rc/wallet.ts @@ -12,13 +12,13 @@ import type { PrepWallet, ServedWalletSession, ShieldedTransferParams, -} from '../../lib/engine.ts'; -import { throwIfCancelled } from '../../lib/errors.ts'; -import { getNetworkId } from '../../lib/network-id.ts'; -import { bindCachesToIndexer, describeIndexerChange } from '../../lib/cache-indexer.ts'; -import { loadWalletCache, saveWalletCache } from '../../lib/wallet-cache.ts'; -import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '../../lib/dust-wait.ts'; -import { trackElapsed } from '../../ui/spinner.ts'; +} from '@kuiralabs/midnight-cli-core/lib/engine'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { decodeShieldedAddress } from './addresses.ts'; import { buildFacade, hasDustAvailable, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; import { ensureDust, executeTransfer } from './transfer.ts'; diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index 767018aa..f2ce4d39 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -5,8 +5,8 @@ // registry's tools, each in the topic group its package's row names. import { PKG_VERSION } from './pkg.ts'; -import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type ToolsTableRow } from './agent-guidance.ts'; -import { commandHelpSpecs, type CommandRegistry, type RegisteredTool } from './command-definition.ts'; +import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type ToolsTableRow } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { commandHelpSpecs, type CommandRegistry, type RegisteredTool } from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** The manual's sections, in order. */ export const AGENT_MANUAL_SECTIONS = [ diff --git a/src/lib/balance-subscription.ts b/src/lib/balance-subscription.ts index d8f50752..b054704a 100644 --- a/src/lib/balance-subscription.ts +++ b/src/lib/balance-subscription.ts @@ -1,10 +1,10 @@ import WebSocket from 'ws'; -import { assertEndpointUsable, endpointRefusalFromWsError } from './blockfrost.ts'; -import { NATIVE_TOKEN_TYPE, BALANCE_CHECK_TIMEOUT_MS } from './constants.ts'; -import { CancelledError } from './errors.ts'; +import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { NATIVE_TOKEN_TYPE, BALANCE_CHECK_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -export type { BalanceSummary } from './engine.ts'; -import type { BalanceSummary } from './engine.ts'; +export type { BalanceSummary } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { BalanceSummary } from '@kuiralabs/midnight-cli-core/lib/engine'; interface Utxo { value: string; diff --git a/src/lib/chain-caches.ts b/src/lib/chain-caches.ts index a08bdcd3..ab111ead 100644 --- a/src/lib/chain-caches.ts +++ b/src/lib/chain-caches.ts @@ -3,10 +3,10 @@ // still referring to it is stale and would fail the next command, and // `cache clear` clears the same set. -import { clearWalletCache } from './wallet-cache.ts'; -import { clearDustDirectCache } from './reader-cache-files.ts'; -import { clearShieldedDirectCache } from './reader-cache-files.ts'; -import { clearNativeDustCheckpoint } from './reader-cache-files.ts'; +import { clearWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { clearNativeDustCheckpoint } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; /** * Clears every wallet cache kept for `network` (all networks when undefined): diff --git a/src/lib/chain-clock.ts b/src/lib/chain-clock.ts index 79a5fa12..eacb56bb 100644 --- a/src/lib/chain-clock.ts +++ b/src/lib/chain-clock.ts @@ -6,7 +6,7 @@ // built on them is refused with a bare "Transaction submission error". import { queryIndexer } from './indexer-graphql.ts'; -import { formatWait } from './duration.ts'; +import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; /** How far behind this computer's clock the chain may be before mn says so. */ export const CHAIN_CLOCK_TOLERANCE_MS = 2 * 60_000; diff --git a/src/lib/chain-id.ts b/src/lib/chain-id.ts index 2df3b59f..0a725cec 100644 --- a/src/lib/chain-id.ts +++ b/src/lib/chain-id.ts @@ -5,7 +5,7 @@ // preprod reset that advanced the chain past our cache). import { callNodeRpc } from './node-rpc.ts'; -import { throwIfCancelled } from './errors.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** Memoise genesis-hash lookups so back-to-back commands don't re-fetch. */ const CHAIN_ID_MEMO = new Map(); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 47cf6628..4c0a891e 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -12,13 +12,13 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; import { installSdkNoiseFilters } from './sdk-noise.ts'; -import { setNoticeSink } from './notices.ts'; -import { setSettingsSource, settingsFromEnvironment } from './settings.ts'; -import { setHostPathsSource } from './state-root.ts'; -import { MIDNIGHT_DIR } from './constants.ts'; -import { setEngineLoader } from './engine.ts'; +import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import { loadInstalledEngine } from './installed-engines.ts'; -import type { SdkWarningCalls } from './sdk-warnings.ts'; +import type { SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; /** What the host gives its runners. */ export interface CliHost { diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index 0b486b1b..31d50a9f 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -3,13 +3,13 @@ // shell (src/wallet.ts) owns the process: it passes in what a handler may be // given and where a notice goes, and decides the heap and the exit. -import type { ParsedArgs } from './argv.ts'; -import { createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput } from './call-context.ts'; -import type { CommandDefinition, CommandRegistry } from './command-definition.ts'; -import { UsageError } from './errors.ts'; -import { writeJsonResult } from './json-output.ts'; -import type { Payer } from './payer.ts'; -import type { CallSdkWarnings, SdkWarningCalls } from './sdk-warnings.ts'; +import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import type { CommandDefinition, CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { writeJsonResult } from '@kuiralabs/midnight-cli-core/lib/json-output'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { CallSdkWarnings, SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { WalletProtector } from './wallet-protector.ts'; /** What the shell can give a handler: its call's signal and output, and, as its definition's `shell` field asks, the payer or protectors, loaded only then. */ diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index 4cdd6dbd..8a21f2be 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -1,10 +1,10 @@ // Calling a circuit of a deployed contract: the call script, run against the // wallet the payer serves (served-wallet.ts). `mn contract call` calls through here. -import type { Payer, PayingTarget } from '../payer.ts'; +import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { withServedWallet } from './served-wallet.ts'; -import type { Spinner } from '../../ui/spinner.ts'; -import type { CallSdkWarnings } from '../sdk-warnings.ts'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { ContractCallRequest } from './request.ts'; export interface CallContractParams { diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index 19e34617..b8453715 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -1,10 +1,10 @@ // Deploying a compiled contract: the deploy script, run against the wallet // the payer serves (served-wallet.ts). `mn contract deploy` and `mn dev` both deploy through here. -import type { Payer, PayingTarget } from '../payer.ts'; +import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { withServedWallet } from './served-wallet.ts'; -import type { Spinner } from '../../ui/spinner.ts'; -import type { CallSdkWarnings } from '../sdk-warnings.ts'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { ContractDeployRequest } from './request.ts'; export interface DeployContractParams { diff --git a/src/lib/contract/request.ts b/src/lib/contract/request.ts index 6fd9b4ff..0ef22669 100644 --- a/src/lib/contract/request.ts +++ b/src/lib/contract/request.ts @@ -3,8 +3,8 @@ // wallet syncs, the MCP server before it issues a confirmation token. import { resolve } from 'node:path'; -import { type ParsedArgs, getFlag, requireFlag } from '../argv.ts'; -import { UsageError } from '../errors.ts'; +import { type ParsedArgs, getFlag, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { findContractInfo, type ContractInfo } from './inspect.ts'; import { findWitnessFile, buildMissingWitnessError } from './witness-discovery.ts'; import { validateCallRequest, validateContractAddress } from './validate.ts'; diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 1d10171b..6eff291b 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -11,13 +11,13 @@ import { writeFileSync, unlinkSync, existsSync, symlinkSync, readFileSync, mkdir import { join, dirname, delimiter } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; -import { assertEndpointUsable } from '../blockfrost.ts'; -import type { NetworkConfig, NetworkName } from '../network.ts'; -import { engineFor, type EngineContractScripts, type ScriptParts } from '../engine.ts'; +import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { engineFor, type EngineContractScripts, type ScriptParts } from '@kuiralabs/midnight-cli-core/lib/engine'; import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; import { coerceArg } from './arg-coerce.ts'; import { resolvePrivateStateSecretKey } from './private-state-secret.ts'; -import { CancelledError, throwIfCancelled } from '../errors.ts'; +import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; // The generated deploy/call script imports SDK packages by bare specifier // (`@midnight-ntwrk/midnight-js-contracts`, `ws`, etc.); without help, Node diff --git a/src/lib/contract/served-wallet.ts b/src/lib/contract/served-wallet.ts index 3d692adc..245e5f8e 100644 --- a/src/lib/contract/served-wallet.ts +++ b/src/lib/contract/served-wallet.ts @@ -2,10 +2,10 @@ // can pay, serve it through the payer, run the script against it with a // progress line, and stop serving whatever happens. -import type { Payer, PayingTarget } from '../payer.ts'; -import type { Spinner } from '../../ui/spinner.ts'; -import type { CallSdkWarnings } from '../sdk-warnings.ts'; -import { throwIfCancelled } from '../errors.ts'; +import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export interface ServedWalletParams { target: PayingTarget; diff --git a/src/lib/contract/validate.ts b/src/lib/contract/validate.ts index 5c9382a9..71063d82 100644 --- a/src/lib/contract/validate.ts +++ b/src/lib/contract/validate.ts @@ -5,7 +5,7 @@ // length of 32"), and a wrong argument count as the runtime's count, which // includes its own context ("expected 1 argument ... received 4" for 3 args). -import { UsageError } from '../errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import type { ContractInfo } from './inspect.ts'; /** A contract address is 32 bytes as 64 hex characters. */ diff --git a/src/lib/dev/deploy.ts b/src/lib/dev/deploy.ts index 98343ca5..92be928a 100644 --- a/src/lib/dev/deploy.ts +++ b/src/lib/dev/deploy.ts @@ -3,12 +3,12 @@ // wallets on the local network. What its steps say goes to `progress`; the // SDK's warnings go to the deploying call's `sdkWarnings`. -import type { ParsedArgs } from '../argv.ts'; +import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { deployContract, type DeployedContract } from '../contract/deploy.ts'; import { resolveContractDeployRequest } from '../contract/request.ts'; -import { resolvePayingTarget, type Payer } from '../payer.ts'; -import type { Spinner } from '../../ui/spinner.ts'; -import type { CallSdkWarnings } from '../sdk-warnings.ts'; +import { resolvePayingTarget, type Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; export async function deployDevContract(projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { // The deploy as `mn contract deploy --path --wallet --network ` reads it. diff --git a/src/lib/dev/localnet-ready.ts b/src/lib/dev/localnet-ready.ts index 0fb32f70..d66c9f62 100644 --- a/src/lib/dev/localnet-ready.ts +++ b/src/lib/dev/localnet-ready.ts @@ -3,7 +3,7 @@ // running stack at the endpoints `undeployed` resolves to (saved config, or // the single local stack docker shows). -import { resolveNetwork } from '../resolve-network.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { assertLedger9StackReachable } from '../ledger-guard.ts'; export type LocalnetState = 'already-running'; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 0e5c2a32..222d204c 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -7,12 +7,12 @@ import { existsSync } from 'node:fs'; import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet } from '../wallet-config.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; import { passphraseForNewSecret } from '../passphrase.ts'; -import { engineFor } from '../engine.ts'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { checkBalance } from '../balance-subscription.ts'; -import { resolveNetwork } from '../resolve-network.ts'; -import type { NetworkConfig } from '../network.ts'; -import type { CallSdkWarnings } from '../sdk-warnings.ts'; -import { throwIfCancelled } from '../errors.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** Default dev wallet names — one per common test persona. */ export const DEFAULT_DEV_WALLET_NAMES = ['dev-alice', 'dev-bob', 'dev-carol'] as const; diff --git a/src/lib/endpoint-check.ts b/src/lib/endpoint-check.ts index e4b18f93..9ff01cf3 100644 --- a/src/lib/endpoint-check.ts +++ b/src/lib/endpoint-check.ts @@ -2,8 +2,8 @@ // refuses it without saying why, so mn finds out first. The endpoints mn // connects to itself are checked where the connection is made. -import { assertEndpointUsable, endpointRefusal, isBlockfrostUrl } from './blockfrost.ts'; -import type { NetworkConfig } from './network.ts'; +import { assertEndpointUsable, endpointRefusal, isBlockfrostUrl } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; const PROBE_TIMEOUT_MS = 10_000; diff --git a/src/lib/grant/account-backup.ts b/src/lib/grant/account-backup.ts index 84755ee4..4c4f0283 100644 --- a/src/lib/grant/account-backup.ts +++ b/src/lib/grant/account-backup.ts @@ -10,13 +10,13 @@ // a second device (`midnight grant device add`). import * as fs from 'node:fs'; -import { anyEngine } from '../engine.ts'; +import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { type OwnerRecord, type Roster, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '../errors.ts'; -import { FileExistsError, writeJsonDurably } from '../durable-file.ts'; -import { type SealedSecret, openSecret, sealSecret } from '../keystore.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { FileExistsError, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; +import { type SealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { privateStateLocationOf } from './account.ts'; import { type DeviceIdentity, deviceCodeOf } from './device-code.ts'; import { diff --git a/src/lib/grant/account-records.ts b/src/lib/grant/account-records.ts index 3c7b4f6e..8eadcd8a 100644 --- a/src/lib/grant/account-records.ts +++ b/src/lib/grant/account-records.ts @@ -5,9 +5,9 @@ import { mkdirSync } from 'node:fs'; import { basename, join } from 'node:path'; -import { DIR_MODE } from '../constants.ts'; +import { DIR_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { getActiveWalletName } from '../wallet-config.ts'; -import { stateRoot } from '../state-root.ts'; +import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** The directory under ~/.midnight that holds each network's accounts. */ export const ACCOUNTS_DIR_NAME = 'accounts'; diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 1dcb43aa..ce0e9477 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -8,8 +8,8 @@ // owner key) and roster.json, with the private state in the directory's // midnight-level-db under the store name and password it was first made with. -import { notice } from '../notices.ts'; -import { anyEngine } from '../engine.ts'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; import { join } from 'node:path'; import { artefactCache } from '@kuiralabs/midnight-account-chain/artefacts'; import { type AccountContext, type ProgressEvent, accountContext, describeProgress, networkOf } from '@kuiralabs/midnight-account-chain/context'; @@ -36,9 +36,9 @@ import { sealedOwnerStore, sealedPrivateStatePassword, } from './sealed-account.ts'; -import { UsageError } from '../errors.ts'; -import type { NetworkConfig } from '../network.ts'; -import { stateRoot } from '../state-root.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** Where the account package caches its proving artefacts, under ~/.midnight: each file is fetched the first time a command proves with it. */ const ACCOUNT_ARTIFACTS_DIR_NAME = 'account-artifacts'; diff --git a/src/lib/grant/deploy-cost.ts b/src/lib/grant/deploy-cost.ts index 9f97f686..09fb7a41 100644 --- a/src/lib/grant/deploy-cost.ts +++ b/src/lib/grant/deploy-cost.ts @@ -13,7 +13,7 @@ // 12.23, 9.87, 10.00, 1.37, 0.26: 33.74 in fees, 43.74 from the wallet, 15.62 for the largest // 13.40, 10.74, 10.82, 1.53, 0.27: 36.75 in fees, 47.51 from the wallet, 17.08 for the largest -import { formatDust } from '../../ui/format.ts'; +import { formatDust } from '@kuiralabs/midnight-cli-core/ui/format'; export const MEASURED_ACCOUNT_DEPLOY = { transactions: 5, diff --git a/src/lib/grant/device-code.ts b/src/lib/grant/device-code.ts index 4101bf30..cab7fc46 100644 --- a/src/lib/grant/device-code.ts +++ b/src/lib/grant/device-code.ts @@ -12,7 +12,7 @@ import { type Arm, type DeviceKey, type ReadKeyAttestation, deviceCodeOf as libraryDeviceCodeOf, joinCodeOf as libraryJoinCodeOf, parseDeviceCode as libraryParseDeviceCode } from '@kuiralabs/midnight-account'; import type { LocalOwnerDevice, OwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '../errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; /** A device named by its arm and public key, with its read key, and its signature of it when the code carries one. */ export interface DeviceIdentity { diff --git a/src/lib/grant/fee-wallet.ts b/src/lib/grant/fee-wallet.ts index ab0a47cd..646c56c4 100644 --- a/src/lib/grant/fee-wallet.ts +++ b/src/lib/grant/fee-wallet.ts @@ -2,10 +2,10 @@ // process, made into the account package's fee wallet. import type { FeeWallet } from '@kuiralabs/midnight-account-chain/owner'; -import { NATIVE_TOKEN_TYPE } from '../constants.ts'; -import type { Payer, PayingTarget } from '../payer.ts'; -import type { Spinner } from '../../ui/spinner.ts'; -import type { CallSdkWarnings } from '../sdk-warnings.ts'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; /** A fee wallet in this process, and how to stop it. */ export interface PayingWallet { diff --git a/src/lib/grant/owner-commands.ts b/src/lib/grant/owner-commands.ts index 3a937b9e..16983b99 100644 --- a/src/lib/grant/owner-commands.ts +++ b/src/lib/grant/owner-commands.ts @@ -21,7 +21,7 @@ import { sealedResponseLink, termsFor, } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '../errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import type { GrantLimits as RequestedLimits } from './request.ts'; /** What a command gives: its result, and the lines a person reads. */ diff --git a/src/lib/grant/prepare.ts b/src/lib/grant/prepare.ts index ed679c79..d4e990d0 100644 --- a/src/lib/grant/prepare.ts +++ b/src/lib/grant/prepare.ts @@ -3,9 +3,9 @@ // account yet, and for a command that starts one, that its wallet exists. The CLI runs it first; the MCP server runs it before it issues a // confirmation token. -import { type ParsedArgs, getFlag } from '../argv.ts'; -import { UsageError } from '../errors.ts'; -import { type PayingTarget, resolvePayingTarget } from '../payer.ts'; +import { type ParsedArgs, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type PayingTarget, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { assertWalletFileExists, resolveWalletPath } from '../wallet-config.ts'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; diff --git a/src/lib/grant/protect-account.ts b/src/lib/grant/protect-account.ts index db8c8629..1c286ab8 100644 --- a/src/lib/grant/protect-account.ts +++ b/src/lib/grant/protect-account.ts @@ -13,7 +13,7 @@ // never opened under the public password its private state has left. import * as fs from 'node:fs'; -import { anyEngine } from '../engine.ts'; +import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { changePrivateStatePassword, directoryOwnerStore, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; diff --git a/src/lib/grant/request.ts b/src/lib/grant/request.ts index 1392e475..4b52ae96 100644 --- a/src/lib/grant/request.ts +++ b/src/lib/grant/request.ts @@ -3,9 +3,9 @@ // server before it issues a confirmation token. import { parseDeviceCode } from './device-code.ts'; -import { type ParsedArgs, getFlag, hasFlag } from '../argv.ts'; -import { UsageError } from '../errors.ts'; -import { nightToMicro, parseAmount } from '../amount.ts'; +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; export const GRANT_SUBCOMMANDS = ['deploy', 'deposit', 'status', 'list', 'issue', 'revoke', 'revoke-all', 'export', 'import', 'device'] as const; diff --git a/src/lib/grant/sealed-account.ts b/src/lib/grant/sealed-account.ts index 8594ed90..e93ac505 100644 --- a/src/lib/grant/sealed-account.ts +++ b/src/lib/grant/sealed-account.ts @@ -29,11 +29,11 @@ import { freshOwnerDevice, ownerDeviceFromSecret, } from '@kuiralabs/midnight-account-chain/owner'; -import { FILE_MODE } from '../constants.ts'; +import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deviceCodeOf, joinCodeOf } from './device-code.ts'; -import { UsageError } from '../errors.ts'; -import { FileExistsError, readJsonIfPresent, writeJsonDurably } from '../durable-file.ts'; -import { type KeyedSecret, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '../keystore.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { FileExistsError, readJsonIfPresent, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; +import { type KeyedSecret, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '@kuiralabs/midnight-cli-core/lib/keystore'; const ACCOUNT_KEY_FILE = 'account-key.json'; // The data key while a plain-text account is being sealed: the account is diff --git a/src/lib/graphql-ws-subscription.ts b/src/lib/graphql-ws-subscription.ts index 5e90333d..70d1ecba 100644 --- a/src/lib/graphql-ws-subscription.ts +++ b/src/lib/graphql-ws-subscription.ts @@ -18,8 +18,8 @@ // `partial=true` means "state is valid but not caught up — persist and resume". import WebSocket from 'ws'; -import { CancelledError } from './errors.ts'; -import { assertEndpointUsable, endpointRefusalFromWsError } from './blockfrost.ts'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; /** Why the subscription settled. `timeout`/`closed-early` are the partial cases. */ export type WsFinishReason = diff --git a/src/lib/heap-guard.ts b/src/lib/heap-guard.ts index ce0dd308..345da559 100644 --- a/src/lib/heap-guard.ts +++ b/src/lib/heap-guard.ts @@ -22,7 +22,7 @@ import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB, -} from './constants.ts'; +} from '@kuiralabs/midnight-cli-core/lib/constants'; /** Set on the re-exec'd child so it doesn't recurse. */ const BUMP_ENV = 'MN_HEAP_BUMPED'; diff --git a/src/lib/indexer-graphql.ts b/src/lib/indexer-graphql.ts index 16d52c32..d07e19e4 100644 --- a/src/lib/indexer-graphql.ts +++ b/src/lib/indexer-graphql.ts @@ -1,7 +1,7 @@ // One GraphQL query to the indexer's HTTP endpoint. -import { assertEndpointUsable, endpointRefusal } from './blockfrost.ts'; -import { throwIfCancelled } from './errors.ts'; +import { assertEndpointUsable, endpointRefusal } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** The indexer could not answer a query: unreachable, an HTTP error, a non-JSON body, or GraphQL errors. */ export class IndexerQueryError extends Error { diff --git a/src/lib/indexer-ready.ts b/src/lib/indexer-ready.ts index 07c64adb..68f89afc 100644 --- a/src/lib/indexer-ready.ts +++ b/src/lib/indexer-ready.ts @@ -6,8 +6,8 @@ // on localnet), confirming state has been ingested end-to-end. import { checkBalance } from './balance-subscription.ts'; -import { throwIfCancelled } from './errors.ts'; -import { sleep } from './sleep.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; export interface WaitForIndexerOptions { /** Overall deadline for the wait. Default 30s. */ diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 6b8564d2..c511c6f5 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -5,7 +5,7 @@ // flag checks read it, and so do help, the manual and the intro, the MCP // server's tools, and the agent manual and skills. -import { createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from './command-definition.ts'; +import { createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { walletDefinition } from '../commands/wallet.definition.ts'; import { generateDefinition } from '../commands/generate.definition.ts'; import { infoDefinition } from '../commands/info.definition.ts'; @@ -16,7 +16,7 @@ import { inspectCostDefinition } from '../commands/inspect-cost.definition.ts'; import { airdropDefinition } from '../commands/airdrop.definition.ts'; import { transferDefinition } from '../commands/transfer.definition.ts'; import { dustDefinition } from '../commands/dust.definition.ts'; -import { configDefinition } from '../commands/config.definition.ts'; +import { configDefinition } from '@kuiralabs/midnight-cli-core/commands/config.definition'; import { cacheDefinition } from '../commands/cache.definition.ts'; import { serveDefinition } from '../commands/serve.definition.ts'; import { testDefinition } from '../commands/test.definition.ts'; @@ -27,7 +27,7 @@ import { localnetDefinition } from '../commands/localnet.definition.ts'; import { statusDefinition } from '../commands/status.definition.ts'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; -import { coreGuidance } from '../commands/core.guidance.ts'; +import { coreGuidance } from '@kuiralabs/midnight-cli-core/commands/core.guidance'; import { chainGuidance } from '../commands/chain.guidance.ts'; import { walletGuidance } from '../commands/wallet.guidance.ts'; import { contractGuidance } from '../commands/contract.guidance.ts'; diff --git a/src/lib/installed-engines.ts b/src/lib/installed-engines.ts index a7586b39..9050f8de 100644 --- a/src/lib/installed-engines.ts +++ b/src/lib/installed-engines.ts @@ -2,7 +2,7 @@ // gives the libraries as their engine loader. Each loads its SDK, so each is // imported only when a call needs it. -import type { Engine, SdkSet } from './engine.ts'; +import type { Engine, SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; /** The engine for an SDK set, as this build ships it. */ export async function loadInstalledEngine(set: SdkSet): Promise { diff --git a/src/lib/ledger-guard.ts b/src/lib/ledger-guard.ts index 45c3f41f..621c1084 100644 --- a/src/lib/ledger-guard.ts +++ b/src/lib/ledger-guard.ts @@ -3,11 +3,11 @@ // events. So check the chain's protocol version up front and fail with a // clear message instead of hanging or failing on a deserialize error. -import { LEDGER_9_FORK_VERSION, type NetworkConfig } from './network.ts'; +import { LEDGER_9_FORK_VERSION, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { getChainGenesisHash } from './chain-id.ts'; -import { isEndpointError } from './blockfrost.ts'; +import { isEndpointError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { queryIndexer } from './indexer-graphql.ts'; -import { throwIfCancelled } from './errors.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export class UnsupportedLedgerError extends Error { readonly code = 'UNSUPPORTED_LEDGER'; diff --git a/src/lib/localnet.ts b/src/lib/localnet.ts index bff2be93..92c16732 100644 --- a/src/lib/localnet.ts +++ b/src/lib/localnet.ts @@ -5,11 +5,11 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; -import { LOCALNET_DIR_NAME, DIR_MODE } from './constants.ts'; -import { stateRoot } from './state-root.ts'; -import { CancelledError, CANCELLED_MESSAGE, throwIfCancelled } from './errors.ts'; -import type { ExecRunner } from './exec-program.ts'; -import { sleep } from './sleep.ts'; +import { LOCALNET_DIR_NAME, DIR_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { CancelledError, CANCELLED_MESSAGE, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; +import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; // Version tag — bump when compose content changes so stale files get overwritten export const COMPOSE_VERSION = '3.0.6'; diff --git a/src/lib/mcp/known-params.ts b/src/lib/mcp/known-params.ts index 192abc62..b7cffe5c 100644 --- a/src/lib/mcp/known-params.ts +++ b/src/lib/mcp/known-params.ts @@ -2,7 +2,7 @@ // parameter outside the tool's schema is refused, and so is one whose value // is not the type its schema says. -import { UsageError } from '../errors.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; /** A parameter's schema as the server checks it. */ interface ParamCheck { diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index ab706af7..f8b19386 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -5,8 +5,8 @@ // the confirmation flow gives. import { type CommandRun, captureCommand } from '../run-command.ts'; -import { getEndpointOverridesForNetwork, loadCliConfig } from '../cli-config.ts'; -import { resolveNetworkName } from '../resolve-network.ts'; +import { getEndpointOverridesForNetwork, loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { type CommandRegistry, type RegisteredTool, @@ -14,7 +14,7 @@ import { type ToolInputSchema, confirmationText, toolArgv, -} from '../command-definition.ts'; +} from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** A tool as tools/list sends it. */ export interface ListedTool { diff --git a/src/lib/mcp/skills.ts b/src/lib/mcp/skills.ts index 1426fb6f..358b80ac 100644 --- a/src/lib/mcp/skills.ts +++ b/src/lib/mcp/skills.ts @@ -6,8 +6,8 @@ // at each resources/read; scripts/write-skill-docs.ts writes the same text to // docs/SKILL-CORE.md and docs/SKILL.md, the copies the README links to. -import { assembleGuidance, sectionsWithAdded, type GuidancePiece } from '../agent-guidance.ts'; -import type { CommandRegistry } from '../command-definition.ts'; +import { assembleGuidance, sectionsWithAdded, type GuidancePiece } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import type { CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** skill/core's sections, in order. */ export const SKILL_CORE_SECTIONS = ['title', 'intent-routing', 'safety-rules', 'when-to-fetch'] as const; diff --git a/src/lib/node-ready.ts b/src/lib/node-ready.ts index 5110ba7c..ed4ef906 100644 --- a/src/lib/node-ready.ts +++ b/src/lib/node-ready.ts @@ -5,8 +5,8 @@ // until a non-zero block number appears. import { callNodeRpc } from './node-rpc.ts'; -import { throwIfCancelled } from './errors.ts'; -import { sleep } from './sleep.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; export interface WaitForFirstBlockOptions { /** Overall deadline for the wait. Default 30s. */ diff --git a/src/lib/node-rpc.ts b/src/lib/node-rpc.ts index 5c336749..06126a08 100644 --- a/src/lib/node-rpc.ts +++ b/src/lib/node-rpc.ts @@ -4,8 +4,8 @@ // this is used at cold-start moments where heavyweight init would hurt. import WebSocket from 'ws'; -import { assertEndpointUsable, endpointRefusalFromWsError } from './blockfrost.ts'; -import { CancelledError } from './errors.ts'; +import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; export interface RpcOptions { url: string; diff --git a/src/lib/output-redaction.ts b/src/lib/output-redaction.ts index 821dc5fb..9041bf95 100644 --- a/src/lib/output-redaction.ts +++ b/src/lib/output-redaction.ts @@ -8,7 +8,7 @@ // holds a project id. (A wrapper that dropped writes or their callbacks once // made libraries waiting on a write hang; this one drops nothing.) -import { mayHoldProjectId, redactProjectId } from './blockfrost.ts'; +import { mayHoldProjectId, redactProjectId } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; type Write = typeof process.stdout.write; diff --git a/src/lib/passphrase.ts b/src/lib/passphrase.ts index f5a9f1eb..6f61cfbb 100644 --- a/src/lib/passphrase.ts +++ b/src/lib/passphrase.ts @@ -8,12 +8,12 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { throwIfCancelled, UsageError } from './errors.ts'; -import { openSecret, sealSecret } from './keystore.ts'; -import { currentPrompter, type Prompter } from './prompter.ts'; -import { PASSPHRASE_ENV, settings } from './settings.ts'; -import { stateRoot } from './state-root.ts'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { currentPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { PASSPHRASE_ENV, settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** The variable a non-interactive run sets the passphrase in (named in settings.ts). */ export { PASSPHRASE_ENV }; diff --git a/src/lib/proof-server-ready.ts b/src/lib/proof-server-ready.ts index 81fad67b..5d6870d3 100644 --- a/src/lib/proof-server-ready.ts +++ b/src/lib/proof-server-ready.ts @@ -5,8 +5,8 @@ // polls the proof-server's `/` status endpoint until it returns a 2xx with // `{"status":"ok",...}` before `mn localnet up` claims readiness. -import { throwIfCancelled } from './errors.ts'; -import { sleep } from './sleep.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; export interface WaitForProofServerOptions { /** Overall deadline for the wait. Default 30s. */ diff --git a/src/lib/readme-commands.ts b/src/lib/readme-commands.ts index 8a5c1646..330d7029 100644 --- a/src/lib/readme-commands.ts +++ b/src/lib/readme-commands.ts @@ -3,7 +3,7 @@ // description. scripts/write-readme-commands.ts writes it between the // README's markers; a test fails when the README differs. -import type { CommandRegistry } from './command-definition.ts'; +import type { CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** The markers around the generated table in README.md. */ export const README_COMMANDS_START = ''; diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index bd5556d1..3f4c12c2 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -1,11 +1,11 @@ // Run a command handler and capture its JSON output // Used by the MCP server to invoke CLI commands programmatically -import { type ParsedArgs, MINIMAL_FLAG } from './argv.ts'; -import type { Payer } from './payer.ts'; -import { createCallContext, runHandler, type CommandHandler, type CallOutput } from './call-context.ts'; -import type { SdkWarningCalls } from './sdk-warnings.ts'; -import { CommandFailedError } from './errors.ts'; +import { type ParsedArgs, MINIMAL_FLAG } from '@kuiralabs/midnight-cli-core/lib/argv'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { createCallContext, runHandler, type CommandHandler, type CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import type { SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { CommandFailedError } from '@kuiralabs/midnight-cli-core/lib/errors'; export interface CommandRun { /** Cancels the command; a call already cancelled never starts. None: it runs to the end. */ diff --git a/src/lib/sdk-noise.ts b/src/lib/sdk-noise.ts index 9272a941..552e369e 100644 --- a/src/lib/sdk-noise.ts +++ b/src/lib/sdk-noise.ts @@ -25,7 +25,7 @@ // one call listening, or to none. import { AsyncLocalStorage } from 'node:async_hooks'; -import { createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls } from './sdk-warnings.ts'; +import { createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; let installed: SdkWarningCalls | null = null; diff --git a/src/lib/seed-resolver.ts b/src/lib/seed-resolver.ts index 7e2ecbdb..243048ea 100644 --- a/src/lib/seed-resolver.ts +++ b/src/lib/seed-resolver.ts @@ -3,10 +3,10 @@ // `MN_SEED` / `--wallet` separately, which is how `balance` drifted and never // learned `MN_SEED`. Centralizing it keeps the precedence identical everywhere. -import { getFlag, type ParsedArgs } from './argv.ts'; -import { UsageError } from './errors.ts'; +import { getFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { resolveWalletPath, unlockWallet, type WalletConfig } from './wallet-config.ts'; -import { settings } from './settings.ts'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; export interface ResolvedSeed { /** The wallet seed: 32-byte raw, or 64-byte BIP-39 (mnemonic-derived). */ diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 3abbfb6d..b53feaad 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -5,15 +5,15 @@ import { Socket } from 'node:net'; import { loadWalletConfig, resolveWalletPath, unlockWallet } from './wallet-config.ts'; -import { resolveNetwork } from './resolve-network.ts'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { assertLedgerSupported } from './ledger-guard.ts'; -import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from './network.ts'; -import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from './engine.ts'; +import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; -import { DEFAULT_SERVE_PORT } from './constants.ts'; -import type { CallSdkWarnings } from './sdk-warnings.ts'; +import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { shieldedSyncEnabled } from './shielded-policy.ts'; -import { CancelledError, throwIfCancelled } from './errors.ts'; +import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** A running mn serve, and how to stop it. */ export interface ServeHandle { @@ -215,7 +215,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise; /** The shielded coin public key of the wallet `name`, unlocked with mn's passphrase. */ export async function coinKeyOfWallet(name: string): Promise { // The engine loads the SDK, which the other wallet subcommands don't need: loaded here, not up front. - const { anyEngine } = await import('./engine.ts'); + const { anyEngine } = await import('@kuiralabs/midnight-cli-core/lib/engine'); return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(name))).seed, 'hex')); } diff --git a/src/lib/ws-rpc.ts b/src/lib/ws-rpc.ts index 344ec842..1fa90e1d 100644 --- a/src/lib/ws-rpc.ts +++ b/src/lib/ws-rpc.ts @@ -2,11 +2,11 @@ // Transport layer for the DApp Connector — dispatches RPC calls to handler functions import { WebSocketServer, WebSocket } from 'ws'; -import { notice } from './notices.ts'; -import type { APIError, RpcHandler, RpcHandlerContext } from './connector-api.ts'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { APIError, RpcHandler, RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; // The wire types the connector's handlers use, from where every package can reach them. -export { createApiError, type APIError, type ErrorCode, type RpcHandler, type RpcHandlerContext } from './connector-api.ts'; +export { createApiError, type APIError, type ErrorCode, type RpcHandler, type RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; // ── JSON-RPC 2.0 types ── diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 96b048f8..9029b0eb 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -16,14 +16,14 @@ import { import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; import type { CommandRun } from './lib/run-command.ts'; import { servePayer } from './lib/serve-payer.ts'; -import { classifyError } from './lib/exit-codes.ts'; -import { withNodeReason } from './lib/sdk-errors.ts'; -import { trimAgentMessage } from './lib/error-trim.ts'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { trimAgentMessage } from '@kuiralabs/midnight-cli-core/lib/error-trim'; import { PKG_VERSION } from './lib/pkg.ts'; import { createConfirmationStore } from './lib/mcp/confirmation.ts'; import { assertKnownParams, assertParamTypes } from './lib/mcp/known-params.ts'; import { CONFIRM_TOOL, confirmationFor, findTool, listedTools, runTool } from './lib/mcp/registry-tools.ts'; -import { needsConfirmation } from './lib/command-definition.ts'; +import { needsConfirmation } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { ensureHeapForSync } from './lib/heap-guard.ts'; import { assertNodeSupported } from './lib/node-version.ts'; import { hideProjectIdsInOutput } from './lib/output-redaction.ts'; diff --git a/src/ui/animate.ts b/src/ui/animate.ts index a5dfa700..a3e8d1e6 100644 --- a/src/ui/animate.ts +++ b/src/ui/animate.ts @@ -2,7 +2,7 @@ // Each animation is a standalone async function writing to stderr // All respect NO_COLOR and accept AbortSignal for cancellation -import { teal, white, purple, green, red, bold, dim, isColorEnabled } from './colors.ts'; +import { teal, white, purple, green, red, bold, dim, isColorEnabled } from '@kuiralabs/midnight-cli-core/ui/colors'; import { getMaterializeFrame, getWordmarkTypingFrame, getWordmarkMaterializeFrame, WORDMARK_BIG, MIDNIGHT_LOGO } from './art.ts'; const FRAME_MS = 80; diff --git a/src/ui/dev-keys.ts b/src/ui/dev-keys.ts index 3c5bf0c3..aae0aa43 100644 --- a/src/ui/dev-keys.ts +++ b/src/ui/dev-keys.ts @@ -1,4 +1,4 @@ -import { notice } from '../lib/notices.ts'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; // Raw-mode single-keystroke dispatcher for `mn dev`. // Registers {key → handler} pairs; reads one char at a time from stdin. // Always restores the terminal's cooked mode on stop() so a crash or Ctrl+C diff --git a/src/ui/test-create-prompt.ts b/src/ui/test-create-prompt.ts index 50a5c68d..a2f8856b 100644 --- a/src/ui/test-create-prompt.ts +++ b/src/ui/test-create-prompt.ts @@ -4,7 +4,7 @@ import { existsSync, statSync } from 'node:fs'; import * as readline from 'node:readline'; -import { teal, dim, yellow } from './colors.ts'; +import { teal, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CreateStrategy, BrowserOptions } from '../lib/test/create.ts'; import type { CircuitInfo } from '../lib/contract/inspect.ts'; import type { BrowserMode } from '../lib/test/types.ts'; diff --git a/src/wallet.ts b/src/wallet.ts index b3dace05..db034a41 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -3,23 +3,23 @@ // Dispatches to command handlers via dynamic import // Also supports: midnight --mcp (starts MCP server for AI agent integration) -import { parseArgs, hasFlag } from './lib/argv.ts'; -import { errorMessage, usageMessage } from './ui/format.ts'; -import { assertKnownFlags } from './lib/command-flags.ts'; -import { withNodeReason } from './lib/sdk-errors.ts'; +import { parseArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { errorMessage, usageMessage } from '@kuiralabs/midnight-cli-core/ui/format'; +import { assertKnownFlags } from '@kuiralabs/midnight-cli-core/lib/command-flags'; +import { withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { installedCommands } from './lib/installed-commands.ts'; import { commandNeedsWalletSdk, dispatchCommand, processOutput } from './lib/command-dispatch.ts'; -import type { CommandOutcome } from './lib/call-context.ts'; -import { classifyError, humanizeNetworkError, EXIT_INVALID_ARGS } from './lib/exit-codes.ts'; -import { isUsageError } from './lib/errors.ts'; -import { writeJsonError } from './lib/json-output.ts'; +import type { CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { classifyError, humanizeNetworkError, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { writeJsonError } from '@kuiralabs/midnight-cli-core/lib/json-output'; import { PKG_VERSION } from './lib/pkg.ts'; import { migrateOldWallet } from './lib/wallet-paths.ts'; import { ensureHeapForSync } from './lib/heap-guard.ts'; import { assertNodeSupported } from './lib/node-version.ts'; import { hideProjectIdsInOutput } from './lib/output-redaction.ts'; -import { setPrompter } from './lib/prompter.ts'; -import { createTerminalPrompter } from './ui/terminal-prompter.ts'; +import { setPrompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; import { installCliHost } from './lib/cli-host.ts'; // --mcp: start MCP server instead of CLI (for: npx midnight-wallet-cli --mcp) diff --git a/tsconfig.json b/tsconfig.json index 09ee28a0..57b186c3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,8 @@ "module": "ES2022", "lib": ["ES2022"], "moduleResolution": "bundler", + // Inside this repository the workspace packages run from their source. + "customConditions": ["midnight-cli-source"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, @@ -13,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts"], "exclude": ["node_modules"] } diff --git a/vitest.config.ts b/vitest.config.ts index 23abdccb..d2aa6b61 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,13 +1,16 @@ import { configDefaults, defineConfig } from 'vitest/config'; export default defineConfig({ + // Inside this repository the workspace packages run from their source: + // here, and in every process a test starts (NODE_OPTIONS). + resolve: { conditions: ['midnight-cli-source'] }, test: { // Tests must never spawn the native dust-sync sidecar (it would make real // network calls / behave differently by machine). Force the WASM path; the // native bridge is covered directly by dust-sync-native.test.ts. // Likewise, local stack detection must not depend on what docker runs on // the machine; it's covered with captured docker output in local-stacks.test.ts. - env: { MN_DISABLE_NATIVE_DUST: '1', MN_NO_LOCAL_DETECT: '1' }, + env: { MN_DISABLE_NATIVE_DUST: '1', MN_NO_LOCAL_DETECT: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --conditions=midnight-cli-source`.trim() }, // Libraries read those variables, and the ones tests set, as settings the shell gives them. setupFiles: ['src/__tests__/helpers/shell-settings.ts'], // Tests seal and open wallets and accounts at their real cost (scrypt at diff --git a/vitest.live.config.ts b/vitest.live.config.ts index b3cb72f9..b0e6effe 100644 --- a/vitest.live.config.ts +++ b/vitest.live.config.ts @@ -6,6 +6,7 @@ import { configDefaults, defineConfig } from 'vitest/config'; import base from './vitest.config.ts'; export default defineConfig({ + resolve: base.resolve, test: { ...base.test, include: ['src/**/*.live.test.ts'], From 4287faf75204a7b013fde26184463933e4625536 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:21:00 -0800 Subject: [PATCH 31/88] chain is a package: @kuiralabs/midnight-chain (phase E, EJ) chain's modules (node RPC, the indexer's GraphQL and its subscriptions, readiness checks, chain id, tip and events, the ledger guard, the chain clock, transaction segments, and the status command) move to packages/chain, 0.1.0-rc.0, which depends on core and ws. Engines use chain as they use core, so it has to be one shared copy too. Same mechanics as core: source under the midnight-cli-source condition here, its build when published; the checks read it; the clean install packs it and finds one copy. No behaviour changes: suite (2256) and snapshot unchanged, clean install works. --- package-lock.json | 20 ++++++++++- package.json | 6 ++-- packages/chain/package.json | 36 +++++++++++++++++++ .../chain/src}/commands/chain.guidance.ts | 0 .../chain/src}/commands/status.definition.ts | 0 .../chain/src}/commands/status.ts | 0 .../chain/src}/lib/balance-subscription.ts | 0 .../chain/src}/lib/chain-clock.ts | 0 {src => packages/chain/src}/lib/chain-id.ts | 0 .../chain/src}/lib/endpoint-check.ts | 0 {src => packages/chain/src}/lib/event-tip.ts | 0 .../chain/src}/lib/graphql-ws-subscription.ts | 0 .../chain/src}/lib/indexer-graphql.ts | 0 .../chain/src}/lib/indexer-ready.ts | 0 .../chain/src}/lib/ledger-guard.ts | 0 {src => packages/chain/src}/lib/node-ready.ts | 0 {src => packages/chain/src}/lib/node-rpc.ts | 0 .../chain/src}/lib/proof-server-ready.ts | 0 .../chain/src}/lib/tx-segments.ts | 0 packages/chain/tsconfig.build.json | 28 +++++++++++++++ scripts/check-layering.mjs | 1 + src/__tests__/balance-subscription.test.ts | 4 +-- src/__tests__/chain-clock.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 2 +- src/__tests__/dust-logic.test.ts | 2 +- src/__tests__/endpoint-check.test.ts | 2 +- src/__tests__/endpoint-refusals.test.ts | 6 ++-- src/__tests__/event-tip.test.ts | 2 +- src/__tests__/exit-codes.test.ts | 4 +-- src/__tests__/graphql-ws-subscription.test.ts | 2 +- src/__tests__/indexer-graphql.test.ts | 2 +- src/__tests__/ledger-guard.test.ts | 2 +- src/__tests__/read-cancellation.test.ts | 18 +++++----- src/__tests__/status.test.ts | 2 +- src/__tests__/tx-segments.test.ts | 2 +- src/__tests__/wallet-data-repository.test.ts | 4 +-- src/commands/balance.ts | 6 ++-- src/commands/dust.ts | 2 +- src/commands/inspect-cost.ts | 2 +- src/commands/localnet.ts | 6 ++-- src/engine/rc/dapp-connector.ts | 4 +-- src/engine/rc/dust-balance-direct.ts | 2 +- src/engine/rc/dust-direct.ts | 2 +- src/engine/rc/facade.ts | 4 +-- src/engine/rc/shielded-direct-cache.ts | 2 +- src/engine/rc/shielded-direct.ts | 2 +- src/engine/rc/transfer.ts | 2 +- src/engine/rc/wallet-data-repository.ts | 10 +++--- src/lib/chain-params.ts | 2 +- src/lib/dev/localnet-ready.ts | 2 +- src/lib/dev/provision-wallets.ts | 2 +- src/lib/installed-commands.ts | 4 +-- src/lib/serve-manager.ts | 2 +- src/lib/test/prep-runner.ts | 2 +- tsconfig.json | 2 +- 55 files changed, 146 insertions(+), 61 deletions(-) create mode 100644 packages/chain/package.json rename {src => packages/chain/src}/commands/chain.guidance.ts (100%) rename {src => packages/chain/src}/commands/status.definition.ts (100%) rename {src => packages/chain/src}/commands/status.ts (100%) rename {src => packages/chain/src}/lib/balance-subscription.ts (100%) rename {src => packages/chain/src}/lib/chain-clock.ts (100%) rename {src => packages/chain/src}/lib/chain-id.ts (100%) rename {src => packages/chain/src}/lib/endpoint-check.ts (100%) rename {src => packages/chain/src}/lib/event-tip.ts (100%) rename {src => packages/chain/src}/lib/graphql-ws-subscription.ts (100%) rename {src => packages/chain/src}/lib/indexer-graphql.ts (100%) rename {src => packages/chain/src}/lib/indexer-ready.ts (100%) rename {src => packages/chain/src}/lib/ledger-guard.ts (100%) rename {src => packages/chain/src}/lib/node-ready.ts (100%) rename {src => packages/chain/src}/lib/node-rpc.ts (100%) rename {src => packages/chain/src}/lib/proof-server-ready.ts (100%) rename {src => packages/chain/src}/lib/tx-segments.ts (100%) create mode 100644 packages/chain/tsconfig.build.json diff --git a/package-lock.json b/package-lock.json index 7456892c..98a1a781 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,11 +10,13 @@ "license": "Apache-2.0", "workspaces": [ "packages/connector", - "packages/cli-core" + "packages/cli-core", + "packages/chain" ], "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.0", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", @@ -676,6 +678,10 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@kuiralabs/midnight-chain": { + "resolved": "packages/chain", + "link": true + }, "node_modules/@kuiralabs/midnight-cli-core": { "resolved": "packages/cli-core", "link": true @@ -5699,6 +5705,18 @@ "zod": "^3.25 || ^4" } }, + "packages/chain": { + "name": "@kuiralabs/midnight-chain", + "version": "0.1.0-rc.0", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "ws": "^8.19.0" + }, + "engines": { + "node": ">=22" + } + }, "packages/cli-core": { "name": "@kuiralabs/midnight-cli-core", "version": "0.1.0-rc.0", diff --git a/package.json b/package.json index 583058b3..eecb2792 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,8 @@ ], "workspaces": [ "packages/connector", - "packages/cli-core" + "packages/cli-core", + "packages/chain" ], "bin": { "midnight": "dist/wallet.js", @@ -46,7 +47,7 @@ }, "scripts": { "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", - "build": "npm run build -w @kuiralabs/midnight-cli-core && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", @@ -60,6 +61,7 @@ "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.0", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", diff --git a/packages/chain/package.json b/packages/chain/package.json new file mode 100644 index 00000000..1a980520 --- /dev/null +++ b/packages/chain/package.json @@ -0,0 +1,36 @@ +{ + "name": "@kuiralabs/midnight-chain", + "version": "0.1.0-rc.0", + "type": "module", + "description": "Read-only network access for the Midnight CLI packages: node, indexer and proof-server readiness, chain id, tip, events and the ledger-version guard", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/chain" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + "./*": { + "midnight-cli-source": "./src/*.ts", + "types": "./dist/*.d.ts", + "default": "./dist/*.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "ws": "^8.19.0" + } +} diff --git a/src/commands/chain.guidance.ts b/packages/chain/src/commands/chain.guidance.ts similarity index 100% rename from src/commands/chain.guidance.ts rename to packages/chain/src/commands/chain.guidance.ts diff --git a/src/commands/status.definition.ts b/packages/chain/src/commands/status.definition.ts similarity index 100% rename from src/commands/status.definition.ts rename to packages/chain/src/commands/status.definition.ts diff --git a/src/commands/status.ts b/packages/chain/src/commands/status.ts similarity index 100% rename from src/commands/status.ts rename to packages/chain/src/commands/status.ts diff --git a/src/lib/balance-subscription.ts b/packages/chain/src/lib/balance-subscription.ts similarity index 100% rename from src/lib/balance-subscription.ts rename to packages/chain/src/lib/balance-subscription.ts diff --git a/src/lib/chain-clock.ts b/packages/chain/src/lib/chain-clock.ts similarity index 100% rename from src/lib/chain-clock.ts rename to packages/chain/src/lib/chain-clock.ts diff --git a/src/lib/chain-id.ts b/packages/chain/src/lib/chain-id.ts similarity index 100% rename from src/lib/chain-id.ts rename to packages/chain/src/lib/chain-id.ts diff --git a/src/lib/endpoint-check.ts b/packages/chain/src/lib/endpoint-check.ts similarity index 100% rename from src/lib/endpoint-check.ts rename to packages/chain/src/lib/endpoint-check.ts diff --git a/src/lib/event-tip.ts b/packages/chain/src/lib/event-tip.ts similarity index 100% rename from src/lib/event-tip.ts rename to packages/chain/src/lib/event-tip.ts diff --git a/src/lib/graphql-ws-subscription.ts b/packages/chain/src/lib/graphql-ws-subscription.ts similarity index 100% rename from src/lib/graphql-ws-subscription.ts rename to packages/chain/src/lib/graphql-ws-subscription.ts diff --git a/src/lib/indexer-graphql.ts b/packages/chain/src/lib/indexer-graphql.ts similarity index 100% rename from src/lib/indexer-graphql.ts rename to packages/chain/src/lib/indexer-graphql.ts diff --git a/src/lib/indexer-ready.ts b/packages/chain/src/lib/indexer-ready.ts similarity index 100% rename from src/lib/indexer-ready.ts rename to packages/chain/src/lib/indexer-ready.ts diff --git a/src/lib/ledger-guard.ts b/packages/chain/src/lib/ledger-guard.ts similarity index 100% rename from src/lib/ledger-guard.ts rename to packages/chain/src/lib/ledger-guard.ts diff --git a/src/lib/node-ready.ts b/packages/chain/src/lib/node-ready.ts similarity index 100% rename from src/lib/node-ready.ts rename to packages/chain/src/lib/node-ready.ts diff --git a/src/lib/node-rpc.ts b/packages/chain/src/lib/node-rpc.ts similarity index 100% rename from src/lib/node-rpc.ts rename to packages/chain/src/lib/node-rpc.ts diff --git a/src/lib/proof-server-ready.ts b/packages/chain/src/lib/proof-server-ready.ts similarity index 100% rename from src/lib/proof-server-ready.ts rename to packages/chain/src/lib/proof-server-ready.ts diff --git a/src/lib/tx-segments.ts b/packages/chain/src/lib/tx-segments.ts similarity index 100% rename from src/lib/tx-segments.ts rename to packages/chain/src/lib/tx-segments.ts diff --git a/packages/chain/tsconfig.build.json b/packages/chain/tsconfig.build.json new file mode 100644 index 00000000..16f7d7d6 --- /dev/null +++ b/packages/chain/tsconfig.build.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node", + "ws" + ] + }, + "include": [ + "src/**/*.ts" + ] +} diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 64118e08..a921c162 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -109,6 +109,7 @@ const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; // under src/, so the homes and rules above apply to it unchanged. export const WORKSPACE_PACKAGES = [ { name: '@kuiralabs/midnight-cli-core', dir: join(ROOT, 'packages', 'cli-core', 'src') }, + { name: '@kuiralabs/midnight-chain', dir: join(ROOT, 'packages', 'chain', 'src') }, ]; /** The package source folder a file is in, or undefined for one under src/. */ diff --git a/src/__tests__/balance-subscription.test.ts b/src/__tests__/balance-subscription.test.ts index 8cceadf3..65bf2536 100644 --- a/src/__tests__/balance-subscription.test.ts +++ b/src/__tests__/balance-subscription.test.ts @@ -28,9 +28,9 @@ vi.mock('ws', async () => { return { default: WS }; }); -let checkBalance: typeof import('../lib/balance-subscription.ts').checkBalance; +let checkBalance: typeof import('@kuiralabs/midnight-chain/lib/balance-subscription').checkBalance; beforeAll(async () => { - ({ checkBalance } = await import('../lib/balance-subscription.ts')); + ({ checkBalance } = await import('@kuiralabs/midnight-chain/lib/balance-subscription')); }); const OTHER_TOKEN = 'ff'.repeat(32); diff --git a/src/__tests__/chain-clock.test.ts b/src/__tests__/chain-clock.test.ts index 2d2ee292..70aae538 100644 --- a/src/__tests__/chain-clock.test.ts +++ b/src/__tests__/chain-clock.test.ts @@ -3,7 +3,7 @@ // clock read 02:33 UTC: about 14 hours behind. import { afterEach, describe, expect, it } from 'vitest'; -import { ChainClockBehindError, CHAIN_CLOCK_TOLERANCE_MS, assertChainClockCurrent, fetchChainTime } from '../lib/chain-clock.ts'; +import { ChainClockBehindError, CHAIN_CLOCK_TOLERANCE_MS, assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; import { classifyError, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 6a46eba3..0097c311 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -26,7 +26,7 @@ import type { WalletProtector } from '../lib/wallet-protector.ts'; import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import balanceCommand from '../commands/balance.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import statusCommand from '../commands/status.ts'; +import statusCommand from '@kuiralabs/midnight-chain/commands/status'; import generateCommand from '../commands/generate.ts'; import walletCommand from '../commands/wallet.ts'; import cacheCommand from '../commands/cache.ts'; diff --git a/src/__tests__/dust-logic.test.ts b/src/__tests__/dust-logic.test.ts index 3c6cb919..f9bf2743 100644 --- a/src/__tests__/dust-logic.test.ts +++ b/src/__tests__/dust-logic.test.ts @@ -378,7 +378,7 @@ describe('registerNightUtxos', () => { it('refuses before estimating anything while the chain\'s clock lags this computer\'s', async () => { const { startLocalIndexer } = await import('./helpers/local-indexer.ts'); - const { ChainClockBehindError } = await import('../lib/chain-clock.ts'); + const { ChainClockBehindError } = await import('@kuiralabs/midnight-chain/lib/chain-clock'); vi.useRealTimers(); const indexer = await startLocalIndexer(() => JSON.stringify({ data: { block: { timestamp: Date.now() - 14 * 3_600_000 } } })); try { diff --git a/src/__tests__/endpoint-check.test.ts b/src/__tests__/endpoint-check.test.ts index e0c472da..7687443c 100644 --- a/src/__tests__/endpoint-check.test.ts +++ b/src/__tests__/endpoint-check.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { assertNetworkAnswers } from '../lib/endpoint-check.ts'; +import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const LOCAL = { indexer: 'http://localhost:8088/api/v4/graphql', indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', node: 'ws://localhost:9944' }; diff --git a/src/__tests__/endpoint-refusals.test.ts b/src/__tests__/endpoint-refusals.test.ts index 44a67865..9d714a2e 100644 --- a/src/__tests__/endpoint-refusals.test.ts +++ b/src/__tests__/endpoint-refusals.test.ts @@ -5,10 +5,10 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import * as http from 'node:http'; import type { AddressInfo } from 'node:net'; -import { checkBalance } from '../lib/balance-subscription.ts'; +import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; -import { callNodeRpc } from '../lib/node-rpc.ts'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; const NO_ID = blockfrostEndpoints('preprod', undefined); const ADDRESS = 'mn_addr_preprod1m5cjx3u3hmfhm5268muqp499y82e3fuxj65jpqq7sd0r9x07n3fqk36yhe'; diff --git a/src/__tests__/event-tip.test.ts b/src/__tests__/event-tip.test.ts index 0bf72d9b..4f3af414 100644 --- a/src/__tests__/event-tip.test.ts +++ b/src/__tests__/event-tip.test.ts @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { WebSocketServer } from 'ws'; -import { fetchEventTip, isCursorBeyondTip, isStreamEmpty } from '../lib/event-tip.ts'; +import { fetchEventTip, isCursorBeyondTip, isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; let servers: WebSocketServer[] = []; afterEach(() => { for (const s of servers) s.close(); servers = []; }); diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index cae2074b..6226116e 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -58,8 +58,8 @@ describe('classifyError usage errors (positional-address balance)', () => { describe('classifyError: typed setup errors keep their own code', () => { // Agents read errorCode from --json / MCP; these must not collapse to UNKNOWN. it.each([ - ['UNSUPPORTED_LEDGER', async () => new (await import('../lib/ledger-guard.ts')).UnsupportedLedgerError('preview', 1000300n)], - ['LOCAL_STACK_UNREACHABLE', async () => new (await import('../lib/ledger-guard.ts')).LocalStackUnreachableError('indexer', 'http://localhost:8088/api/v4/graphql')], + ['UNSUPPORTED_LEDGER', async () => new (await import('@kuiralabs/midnight-chain/lib/ledger-guard')).UnsupportedLedgerError('preview', 1000300n)], + ['LOCAL_STACK_UNREACHABLE', async () => new (await import('@kuiralabs/midnight-chain/lib/ledger-guard')).LocalStackUnreachableError('indexer', 'http://localhost:8088/api/v4/graphql')], ['LOCALNET_UNAVAILABLE', async () => new (await import('../lib/localnet.ts')).LocalnetUnavailableError()], ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('@kuiralabs/midnight-cli-core/lib/network')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], ])('%s', async (code, make) => { diff --git a/src/__tests__/graphql-ws-subscription.test.ts b/src/__tests__/graphql-ws-subscription.test.ts index fa53fdc4..682804b4 100644 --- a/src/__tests__/graphql-ws-subscription.test.ts +++ b/src/__tests__/graphql-ws-subscription.test.ts @@ -7,7 +7,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; -import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; type ServerScript = (ws: WsSocket) => void; diff --git a/src/__tests__/indexer-graphql.test.ts b/src/__tests__/indexer-graphql.test.ts index 43426801..090add9b 100644 --- a/src/__tests__/indexer-graphql.test.ts +++ b/src/__tests__/indexer-graphql.test.ts @@ -3,7 +3,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; -import { IndexerQueryError, queryIndexer } from '../lib/indexer-graphql.ts'; +import { IndexerQueryError, queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; let indexer: LocalIndexer | undefined; diff --git a/src/__tests__/ledger-guard.test.ts b/src/__tests__/ledger-guard.test.ts index 51f69ea6..ee03fa01 100644 --- a/src/__tests__/ledger-guard.test.ts +++ b/src/__tests__/ledger-guard.test.ts @@ -11,7 +11,7 @@ import { UnsupportedLedgerError, LocalStackUnreachableError, walletsBelowLedger9, -} from '../lib/ledger-guard.ts'; +} from '@kuiralabs/midnight-chain/lib/ledger-guard'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; const PREVIEW = 1000300n; diff --git a/src/__tests__/read-cancellation.test.ts b/src/__tests__/read-cancellation.test.ts index 92c14fd4..a0cb1873 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/src/__tests__/read-cancellation.test.ts @@ -8,18 +8,18 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { WebSocketServer } from 'ws'; -import { callNodeRpc } from '../lib/node-rpc.ts'; -import { clearChainIdMemo, getChainGenesisHash } from '../lib/chain-id.ts'; -import { queryIndexer } from '../lib/indexer-graphql.ts'; -import { fetchProtocolVersion } from '../lib/ledger-guard.ts'; -import { checkBalance } from '../lib/balance-subscription.ts'; -import { waitForFirstBlock } from '../lib/node-ready.ts'; -import { waitForAddressFunded } from '../lib/indexer-ready.ts'; -import { waitForProofServerReady } from '../lib/proof-server-ready.ts'; +import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; +import { clearChainIdMemo, getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; +import { queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; +import { fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { waitForFirstBlock } from '@kuiralabs/midnight-chain/lib/node-ready'; +import { waitForAddressFunded } from '@kuiralabs/midnight-chain/lib/indexer-ready'; +import { waitForProofServerReady } from '@kuiralabs/midnight-chain/lib/proof-server-ready'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; import { getNetworkConfig, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { BalanceSummary } from '../lib/balance-subscription.ts'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; let http: Server; let ws: WebSocketServer; diff --git a/src/__tests__/status.test.ts b/src/__tests__/status.test.ts index 76c2f3cd..6035995b 100644 --- a/src/__tests__/status.test.ts +++ b/src/__tests__/status.test.ts @@ -115,7 +115,7 @@ describe('status command', () => { /** Runs status as the CLI would; the exit code it gives, which the shell sets. */ async function runStatus(flags: Record = {}) { // Dynamic import to get fresh module - const mod = await import('../commands/status.ts'); + const mod = await import('@kuiralabs/midnight-chain/commands/status'); return cliCall(mod.default, { command: 'status', subcommand: undefined, diff --git a/src/__tests__/tx-segments.test.ts b/src/__tests__/tx-segments.test.ts index 605967bb..63592e8b 100644 --- a/src/__tests__/tx-segments.test.ts +++ b/src/__tests__/tx-segments.test.ts @@ -4,7 +4,7 @@ // success lists segments. import { afterEach, describe, expect, it } from 'vitest'; -import { SegmentResultsUnavailableError, fetchPartialSuccessSegments } from '../lib/tx-segments.ts'; +import { SegmentResultsUnavailableError, fetchPartialSuccessSegments } from '@kuiralabs/midnight-chain/lib/tx-segments'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; const HASH = '2ee4f2b48b659ff6b6f6312b85b49cbfba53fc5f77f430603c845c1a3378464b'; diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index eb695c44..6f109753 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -11,9 +11,9 @@ import { Buffer } from 'node:buffer'; import * as ledger from '@midnightntwrk/ledger-v9'; import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '../engine/rc/wallet-data-repository.ts'; -import { UnsupportedLedgerError } from '../lib/ledger-guard.ts'; +import { UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { BalanceSummary } from '../lib/balance-subscription.ts'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; // ── Test fixtures ───────────────────────────────────────── diff --git a/src/commands/balance.ts b/src/commands/balance.ts index fefacb29..dffcea49 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -8,10 +8,10 @@ import { resolveSeedSource } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; import { shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; -import { isNativeToken } from '../lib/balance-subscription.ts'; +import { isNativeToken } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; -import { getChainGenesisHash } from '../lib/chain-id.ts'; +import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; import { createEtaEstimator, formatSyncStatus } from '../lib/sync-eta.ts'; import { header, keyValue, divider, formatNight, formatAddress, toNight } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; diff --git a/src/commands/dust.ts b/src/commands/dust.ts index b5551393..4ff2bd8b 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -8,7 +8,7 @@ import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveSeed } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { checkBalance } from '../lib/balance-subscription.ts'; +import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { header, keyValue, divider, formatDust, successMessage, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 98306d84..24b5f88b 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -9,7 +9,7 @@ import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context' import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { fetchLedgerParameters } from '../lib/chain-params.ts'; import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { assertLedgerSupported, fetchProtocolVersion } from '../lib/ledger-guard.ts'; +import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; const UNITS: Record = { readTime: 'picoseconds', diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index 4f129caf..3e892dbe 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -68,9 +68,9 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) // prove time with "Failed to prove transaction". spinner.update('Waiting for chain to produce first block...'); try { - const { waitForFirstBlock } = await import('../lib/node-ready.ts'); - const { waitForAddressFunded } = await import('../lib/indexer-ready.ts'); - const { waitForProofServerReady } = await import('../lib/proof-server-ready.ts'); + const { waitForFirstBlock } = await import('@kuiralabs/midnight-chain/lib/node-ready'); + const { waitForAddressFunded } = await import('@kuiralabs/midnight-chain/lib/indexer-ready'); + const { waitForProofServerReady } = await import('@kuiralabs/midnight-chain/lib/proof-server-ready'); const { getNetworkConfig } = await import('@kuiralabs/midnight-cli-core/lib/network'); const { engineFor } = await import('@kuiralabs/midnight-cli-core/lib/engine'); const { GENESIS_SEED } = await import('@kuiralabs/midnight-cli-core/lib/constants'); diff --git a/src/engine/rc/dapp-connector.ts b/src/engine/rc/dapp-connector.ts index 760d5e13..d7381fd7 100644 --- a/src/engine/rc/dapp-connector.ts +++ b/src/engine/rc/dapp-connector.ts @@ -24,8 +24,8 @@ import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { fetchPartialSuccessSegments, type SegmentResult } from '../../lib/tx-segments.ts'; -import { walletsBelowLedger9 } from '../../lib/ledger-guard.ts'; +import { fetchPartialSuccessSegments, type SegmentResult } from '@kuiralabs/midnight-chain/lib/tx-segments'; +import { walletsBelowLedger9 } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import { roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; diff --git a/src/engine/rc/dust-balance-direct.ts b/src/engine/rc/dust-balance-direct.ts index 4d514bad..29180ddb 100644 --- a/src/engine/rc/dust-balance-direct.ts +++ b/src/engine/rc/dust-balance-direct.ts @@ -25,7 +25,7 @@ import { INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS, } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; const SUBSCRIPTION_QUERY = ` subscription DustGenerations($a: DustAddress!, $s: Int!, $e: Int!) { diff --git a/src/engine/rc/dust-direct.ts b/src/engine/rc/dust-direct.ts index bf68c02e..d462fdc1 100644 --- a/src/engine/rc/dust-direct.ts +++ b/src/engine/rc/dust-direct.ts @@ -17,7 +17,7 @@ import { INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS, } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; // MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): settings().isDustCollapseOff. diff --git a/src/engine/rc/facade.ts b/src/engine/rc/facade.ts index 021381b2..a04852fe 100644 --- a/src/engine/rc/facade.ts +++ b/src/engine/rc/facade.ts @@ -31,8 +31,8 @@ import { PRE_SEND_SYNC_TIMEOUT_MS, } from '@kuiralabs/midnight-cli-core/lib/constants'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { assertNetworkAnswers } from '../../lib/endpoint-check.ts'; -import { isStreamEmpty } from '../../lib/event-tip.ts'; +import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; +import { isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export type SyncMode = 'full' | 'lite' | 'no-dust'; diff --git a/src/engine/rc/shielded-direct-cache.ts b/src/engine/rc/shielded-direct-cache.ts index c6116908..2bccba78 100644 --- a/src/engine/rc/shielded-direct-cache.ts +++ b/src/engine/rc/shielded-direct-cache.ts @@ -19,7 +19,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveShieldedSeed } from './derivation.ts'; import { readShieldedBalanceDirect, type ShieldedDirectOptions } from './shielded-direct.ts'; -import { fetchEventTip, isCursorBeyondTip } from '../../lib/event-tip.ts'; +import { fetchEventTip, isCursorBeyondTip } from '@kuiralabs/midnight-chain/lib/event-tip'; import { clearShieldedDirectCache, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; // v2: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis diff --git a/src/engine/rc/shielded-direct.ts b/src/engine/rc/shielded-direct.ts index bf55da57..c4e49a19 100644 --- a/src/engine/rc/shielded-direct.ts +++ b/src/engine/rc/shielded-direct.ts @@ -14,7 +14,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; -import { subscribeGraphqlWs } from '../../lib/graphql-ws-subscription.ts'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; const SUBSCRIPTION_QUERY = ` subscription ZswapLedgerEvents($id: Int) { diff --git a/src/engine/rc/transfer.ts b/src/engine/rc/transfer.ts index a39f6b19..61d00eae 100644 --- a/src/engine/rc/transfer.ts +++ b/src/engine/rc/transfer.ts @@ -57,7 +57,7 @@ export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midn import { isColdStartRace, isDustRelatedError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { assertChainClockCurrent, fetchChainTime } from '../../lib/chain-clock.ts'; +import { assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; import { awaitDustForFee, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; /** How long the transfer retry waits for Dust to grow when the fee is above the pre-flight threshold. */ diff --git a/src/engine/rc/wallet-data-repository.ts b/src/engine/rc/wallet-data-repository.ts index b0ebc901..26aff549 100644 --- a/src/engine/rc/wallet-data-repository.ts +++ b/src/engine/rc/wallet-data-repository.ts @@ -43,17 +43,17 @@ import { validateWalletCacheChainId, type WalletCacheData, } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { getChainGenesisHash } from '../../lib/chain-id.ts'; -import { assertLedgerSupported, fetchProtocolVersion } from '../../lib/ledger-guard.ts'; -import { checkBalance, type BalanceSummary } from '../../lib/balance-subscription.ts'; +import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; +import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { checkBalance, type BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { callNodeRpc } from '../../lib/node-rpc.ts'; +import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; import { deriveDustSeed } from './derivation.ts'; import { deriveUnshieldedAddress } from './derive-address.ts'; -import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '../../lib/event-tip.ts'; +import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain/lib/event-tip'; import type { DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; export type { DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; diff --git a/src/lib/chain-params.ts b/src/lib/chain-params.ts index 812a7b97..df2091cf 100644 --- a/src/lib/chain-params.ts +++ b/src/lib/chain-params.ts @@ -4,7 +4,7 @@ // parameters: on a ledger-9 localnet the block limits for read time and // block usage are 2x and 5x the initial ones. -import { queryIndexer } from './indexer-graphql.ts'; +import { queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; export interface ChainLedgerParameters { height: number; diff --git a/src/lib/dev/localnet-ready.ts b/src/lib/dev/localnet-ready.ts index d66c9f62..c013f98c 100644 --- a/src/lib/dev/localnet-ready.ts +++ b/src/lib/dev/localnet-ready.ts @@ -4,7 +4,7 @@ // the single local stack docker shows). import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { assertLedger9StackReachable } from '../ledger-guard.ts'; +import { assertLedger9StackReachable } from '@kuiralabs/midnight-chain/lib/ledger-guard'; export type LocalnetState = 'already-running'; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 222d204c..58aefe53 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -8,7 +8,7 @@ import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWall import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; import { passphraseForNewSecret } from '../passphrase.ts'; import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { checkBalance } from '../balance-subscription.ts'; +import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index c511c6f5..5d46e7c6 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -24,11 +24,11 @@ import { devDefinition } from '../commands/dev.definition.ts'; import { contractDefinition } from '../commands/contract.definition.ts'; import { grantDefinition } from '../commands/grant.definition.ts'; import { localnetDefinition } from '../commands/localnet.definition.ts'; -import { statusDefinition } from '../commands/status.definition.ts'; +import { statusDefinition } from '@kuiralabs/midnight-chain/commands/status.definition'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; import { coreGuidance } from '@kuiralabs/midnight-cli-core/commands/core.guidance'; -import { chainGuidance } from '../commands/chain.guidance.ts'; +import { chainGuidance } from '@kuiralabs/midnight-chain/commands/chain.guidance'; import { walletGuidance } from '../commands/wallet.guidance.ts'; import { contractGuidance } from '../commands/contract.guidance.ts'; import { connectGuidance } from '../commands/connect.guidance.ts'; diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index b53feaad..9669c591 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -6,7 +6,7 @@ import { Socket } from 'node:net'; import { loadWalletConfig, resolveWalletPath, unlockWallet } from './wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { assertLedgerSupported } from './ledger-guard.ts'; +import { assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index 174d9a15..5d3b23fc 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -6,7 +6,7 @@ import { clearWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache' import { resolveWalletPath, unlockWallet } from '../wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { assertLedger9StackReachable, assertLedgerSupported } from '../ledger-guard.ts'; +import { assertLedger9StackReachable, assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import type { DappTestConfig, PrepStepId, PrepStepResult, PrepContext, PrepCallbacks } from './types.ts'; import { startServeOrReuse } from '../serve-manager.ts'; diff --git a/tsconfig.json b/tsconfig.json index 57b186c3..38c12966 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts"], + "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts"], "exclude": ["node_modules"] } From bacce964fccea4745b4aab5657626a16635878c1 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:25:00 -0800 Subject: [PATCH 32/88] The rc engine is a package, and mn declares no SDK (phase E, EJ) The rc engine moves to packages/engine-rc as @kuiralabs/midnight-engine-rc 0.1.0-rc.0. It depends on core and chain and pins its SDK set exactly, with the ledger and the onchain runtime pinned directly (the spike's advice, Y32), and @scure/base and compact-js as the clean install and the contract scripts need them. mn depends on the engine and no longer on any SDK package (Y32): the DApp Connector API types are a dev dependency, for the test that keeps the connector's copy equal. - The shell's list of engines imports the engine by name; the checks read its files as engine/rc/, so their rules hold unchanged. - The sidecar's dev build is found from the package's own folder. - A test keeps the SDK out of mn's, core's and chain's manifests, and pinned exactly in each engine's. No behaviour changes: suite (2257) and snapshot unchanged; a clean install from the packed tarballs works, with one copy of the ledger and of each package. Publishing core, chain and the rc engine comes before the next mn release. --- package-lock.json | 57 ++++++++++++------ package.json | 24 ++------ packages/engine-rc/package.json | 59 +++++++++++++++++++ .../engine-rc/src}/addresses.ts | 0 .../rc => packages/engine-rc/src}/airdrop.ts | 0 .../engine-rc/src}/contract-providers.ts | 0 .../engine-rc/src}/contract-scripts.ts | 0 .../engine-rc/src}/dapp-connector.ts | 0 .../engine-rc/src}/derivation.ts | 0 .../engine-rc/src}/derive-address.ts | 0 .../engine-rc/src}/dust-balance-direct.ts | 0 .../engine-rc/src}/dust-collapse.ts | 0 .../engine-rc/src}/dust-direct-cache.ts | 0 .../engine-rc/src}/dust-direct.ts | 0 .../engine-rc/src}/dust-export.ts | 0 .../engine-rc/src}/dust-register.ts | 0 .../engine-rc/src}/dust-sync-native.ts | 7 +-- .../engine-rc/src}/dust-wallet.ts | 0 .../rc => packages/engine-rc/src}/facade.ts | 0 .../engine-rc/src}/fee-only-check.ts | 0 .../engine-rc/src}/fork-schedule.ts | 0 .../rc => packages/engine-rc/src}/index.ts | 0 .../engine-rc/src}/ledger-parameters.ts | 0 .../engine-rc/src}/raw-state.ts | 0 .../engine-rc/src}/shielded-direct-cache.ts | 0 .../engine-rc/src}/shielded-direct.ts | 0 .../engine-rc/src}/sign-recipe.ts | 0 .../rc => packages/engine-rc/src}/transfer.ts | 0 .../engine-rc/src}/tx-inspect.ts | 0 .../engine-rc/src}/wallet-data-repository.ts | 0 .../rc => packages/engine-rc/src}/wallet.ts | 0 packages/engine-rc/tsconfig.build.json | 28 +++++++++ scripts/check-layering.d.mts | 2 +- scripts/check-layering.mjs | 9 ++- scripts/measure-preprod-dust.ts | 2 +- src/__tests__/account-backup.test.ts | 2 +- src/__tests__/airdrop-command.test.ts | 2 +- src/__tests__/balance-command.live.test.ts | 2 +- src/__tests__/balance-command.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 2 +- src/__tests__/contract-raw-state.test.ts | 2 +- .../contract-runner-endpoints.test.ts | 2 +- src/__tests__/contract-runner.test.ts | 4 +- .../contract-script-packages.test.ts | 8 +-- src/__tests__/dapp-connector.test.ts | 10 ++-- src/__tests__/derive-address.test.ts | 2 +- src/__tests__/dust-collapse.test.ts | 2 +- src/__tests__/dust-command.test.ts | 2 +- src/__tests__/dust-direct-cache.test.ts | 2 +- src/__tests__/dust-export.test.ts | 10 ++-- src/__tests__/dust-logic.test.ts | 4 +- src/__tests__/dust-sync-native.test.ts | 2 +- src/__tests__/dust-wallet.test.ts | 4 +- src/__tests__/engine.test.ts | 2 +- src/__tests__/facade.test.ts | 12 ++-- src/__tests__/fee-only-check.test.ts | 2 +- src/__tests__/fee-only-signing.test.ts | 4 +- src/__tests__/helpers/offline-facade.ts | 4 +- src/__tests__/info-command.test.ts | 2 +- src/__tests__/json-output.test.ts | 2 +- .../mcp-server-concurrent-calls.test.ts | 2 +- src/__tests__/multi-wallet.test.ts | 2 +- src/__tests__/network-id.test.ts | 2 +- src/__tests__/notices.test.ts | 2 +- src/__tests__/package-metadata.test.ts | 27 +++++++++ src/__tests__/read-cancellation.test.ts | 2 +- src/__tests__/run-command.test.ts | 2 +- src/__tests__/sealed-account.test.ts | 2 +- src/__tests__/sealed-wallet.test.ts | 2 +- src/__tests__/serve-manager.test.ts | 2 +- src/__tests__/shielded-direct-cache.test.ts | 2 +- src/__tests__/shielded-direct.test.ts | 4 +- src/__tests__/sign-recipe.test.ts | 4 +- src/__tests__/transfer-command.test.ts | 2 +- src/__tests__/transfer-lib.test.ts | 4 +- src/__tests__/transfer-request.test.ts | 2 +- src/__tests__/verbose-per-call.test.ts | 4 +- src/__tests__/wallet-config.test.ts | 2 +- src/__tests__/wallet-create.test.ts | 2 +- src/__tests__/wallet-data-repository.test.ts | 4 +- src/__tests__/wallet-protect.test.ts | 2 +- .../wallet-state-to-restore.live.test.ts | 4 +- src/lib/installed-engines.ts | 2 +- tsconfig.json | 2 +- 84 files changed, 244 insertions(+), 121 deletions(-) create mode 100644 packages/engine-rc/package.json rename {src/engine/rc => packages/engine-rc/src}/addresses.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/airdrop.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/contract-providers.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/contract-scripts.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dapp-connector.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/derivation.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/derive-address.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-balance-direct.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-collapse.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-direct-cache.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-direct.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-export.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-register.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/dust-sync-native.ts (98%) rename {src/engine/rc => packages/engine-rc/src}/dust-wallet.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/facade.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/fee-only-check.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/fork-schedule.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/index.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/ledger-parameters.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/raw-state.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/shielded-direct-cache.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/shielded-direct.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/sign-recipe.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/transfer.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/tx-inspect.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/wallet-data-repository.ts (100%) rename {src/engine/rc => packages/engine-rc/src}/wallet.ts (100%) create mode 100644 packages/engine-rc/tsconfig.build.json diff --git a/package-lock.json b/package-lock.json index 98a1a781..1ace5e49 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,32 +11,17 @@ "workspaces": [ "packages/connector", "packages/cli-core", - "packages/chain" + "packages/chain", + "packages/engine-rc" ], "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.0", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@midnight-ntwrk/compact-runtime": "0.20.0", - "@midnight-ntwrk/ledger-v8": "8.1.0", - "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-utils": "5.0.0-rc.1", - "@midnightntwrk/dapp-connector-api": "4.1.0-beta.1", - "@midnightntwrk/ledger-v9": "1.0.0-rc.5", - "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", - "@midnightntwrk/wallet-sdk": "2.0.0-rc.0", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.0", "@modelcontextprotocol/sdk": "^1.27.1", - "@scure/base": "2.0.0", "@scure/bip39": "^2.0.1", - "rxjs": "7.8.2", "ws": "^8.19.0" }, "bin": { @@ -46,6 +31,7 @@ "mn": "dist/wallet.js" }, "devDependencies": { + "@midnightntwrk/dapp-connector-api": "4.1.0-beta.1", "@types/node": "^22.19.13", "@types/ws": "^8.18.1", "tsx": "^4.21.0", @@ -686,6 +672,10 @@ "resolved": "packages/cli-core", "link": true }, + "node_modules/@kuiralabs/midnight-engine-rc": { + "resolved": "packages/engine-rc", + "link": true + }, "node_modules/@midnight-ntwrk/compact-js": { "version": "3.0.0-rc.3", "resolved": "https://registry.npmjs.org/@midnight-ntwrk/compact-js/-/compact-js-3.0.0-rc.3.tgz", @@ -982,6 +972,7 @@ "version": "4.1.0-beta.1", "resolved": "https://registry.npmjs.org/@midnightntwrk/dapp-connector-api/-/dapp-connector-api-4.1.0-beta.1.tgz", "integrity": "sha512-gpFAoELf++5/6GuLZWYSLOD1uBbIoUs3iW056OCwlENadwGSVvuEvWXcmdfZJzKXhT3znZw2uKeZNCqIhDc8Jg==", + "dev": true, "license": "Apache-2.0" }, "node_modules/@midnightntwrk/ledger-v8": { @@ -5747,6 +5738,36 @@ "optional": true } } + }, + "packages/engine-rc": { + "name": "@kuiralabs/midnight-engine-rc", + "version": "0.1.0-rc.0", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@midnight-ntwrk/compact-js": "3.0.0-rc.3", + "@midnight-ntwrk/compact-runtime": "0.20.0", + "@midnight-ntwrk/ledger-v8": "8.1.0", + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-rc.1", + "@midnightntwrk/ledger-v9": "1.0.0-rc.5", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", + "@midnightntwrk/wallet-sdk": "2.0.0-rc.0", + "@scure/base": "2.0.0", + "rxjs": "7.8.2", + "ws": "^8.19.0" + }, + "engines": { + "node": ">=22" + } } } } diff --git a/package.json b/package.json index eecb2792..05c6d996 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,8 @@ "workspaces": [ "packages/connector", "packages/cli-core", - "packages/chain" + "packages/chain", + "packages/engine-rc" ], "bin": { "midnight": "dist/wallet.js", @@ -47,7 +48,7 @@ }, "scripts": { "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", - "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", @@ -63,28 +64,13 @@ "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.0", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@midnight-ntwrk/compact-runtime": "0.20.0", - "@midnight-ntwrk/ledger-v8": "8.1.0", - "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-utils": "5.0.0-rc.1", - "@midnightntwrk/dapp-connector-api": "4.1.0-beta.1", - "@midnightntwrk/ledger-v9": "1.0.0-rc.5", - "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", - "@midnightntwrk/wallet-sdk": "2.0.0-rc.0", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.0", "@modelcontextprotocol/sdk": "^1.27.1", - "@scure/base": "2.0.0", "@scure/bip39": "^2.0.1", - "rxjs": "7.8.2", "ws": "^8.19.0" }, "devDependencies": { + "@midnightntwrk/dapp-connector-api": "4.1.0-beta.1", "@types/node": "^22.19.13", "@types/ws": "^8.18.1", "tsx": "^4.21.0", diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json new file mode 100644 index 00000000..7d75c2ff --- /dev/null +++ b/packages/engine-rc/package.json @@ -0,0 +1,59 @@ +{ + "name": "@kuiralabs/midnight-engine-rc", + "version": "0.1.0-rc.0", + "type": "module", + "description": "The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, ledger 9 rc, midnight-js 5 rc): everything the CLI does with that SDK set, behind the engine interface", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/engine-rc" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": { + "midnight-cli-source": "./src/*.ts", + "types": "./dist/*.d.ts", + "default": "./dist/*.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@midnight-ntwrk/compact-js": "3.0.0-rc.3", + "@midnight-ntwrk/compact-runtime": "0.20.0", + "@midnight-ntwrk/ledger-v8": "8.1.0", + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-rc.1", + "@midnightntwrk/ledger-v9": "1.0.0-rc.5", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", + "@midnightntwrk/wallet-sdk": "2.0.0-rc.0", + "@scure/base": "2.0.0", + "rxjs": "7.8.2", + "ws": "^8.19.0" + } +} diff --git a/src/engine/rc/addresses.ts b/packages/engine-rc/src/addresses.ts similarity index 100% rename from src/engine/rc/addresses.ts rename to packages/engine-rc/src/addresses.ts diff --git a/src/engine/rc/airdrop.ts b/packages/engine-rc/src/airdrop.ts similarity index 100% rename from src/engine/rc/airdrop.ts rename to packages/engine-rc/src/airdrop.ts diff --git a/src/engine/rc/contract-providers.ts b/packages/engine-rc/src/contract-providers.ts similarity index 100% rename from src/engine/rc/contract-providers.ts rename to packages/engine-rc/src/contract-providers.ts diff --git a/src/engine/rc/contract-scripts.ts b/packages/engine-rc/src/contract-scripts.ts similarity index 100% rename from src/engine/rc/contract-scripts.ts rename to packages/engine-rc/src/contract-scripts.ts diff --git a/src/engine/rc/dapp-connector.ts b/packages/engine-rc/src/dapp-connector.ts similarity index 100% rename from src/engine/rc/dapp-connector.ts rename to packages/engine-rc/src/dapp-connector.ts diff --git a/src/engine/rc/derivation.ts b/packages/engine-rc/src/derivation.ts similarity index 100% rename from src/engine/rc/derivation.ts rename to packages/engine-rc/src/derivation.ts diff --git a/src/engine/rc/derive-address.ts b/packages/engine-rc/src/derive-address.ts similarity index 100% rename from src/engine/rc/derive-address.ts rename to packages/engine-rc/src/derive-address.ts diff --git a/src/engine/rc/dust-balance-direct.ts b/packages/engine-rc/src/dust-balance-direct.ts similarity index 100% rename from src/engine/rc/dust-balance-direct.ts rename to packages/engine-rc/src/dust-balance-direct.ts diff --git a/src/engine/rc/dust-collapse.ts b/packages/engine-rc/src/dust-collapse.ts similarity index 100% rename from src/engine/rc/dust-collapse.ts rename to packages/engine-rc/src/dust-collapse.ts diff --git a/src/engine/rc/dust-direct-cache.ts b/packages/engine-rc/src/dust-direct-cache.ts similarity index 100% rename from src/engine/rc/dust-direct-cache.ts rename to packages/engine-rc/src/dust-direct-cache.ts diff --git a/src/engine/rc/dust-direct.ts b/packages/engine-rc/src/dust-direct.ts similarity index 100% rename from src/engine/rc/dust-direct.ts rename to packages/engine-rc/src/dust-direct.ts diff --git a/src/engine/rc/dust-export.ts b/packages/engine-rc/src/dust-export.ts similarity index 100% rename from src/engine/rc/dust-export.ts rename to packages/engine-rc/src/dust-export.ts diff --git a/src/engine/rc/dust-register.ts b/packages/engine-rc/src/dust-register.ts similarity index 100% rename from src/engine/rc/dust-register.ts rename to packages/engine-rc/src/dust-register.ts diff --git a/src/engine/rc/dust-sync-native.ts b/packages/engine-rc/src/dust-sync-native.ts similarity index 98% rename from src/engine/rc/dust-sync-native.ts rename to packages/engine-rc/src/dust-sync-native.ts index d7b03aa8..a66f304b 100644 --- a/src/engine/rc/dust-sync-native.ts +++ b/packages/engine-rc/src/dust-sync-native.ts @@ -55,11 +55,10 @@ export function resolveSidecarBinary(): string | null { if (fromEnv && existsSync(fromEnv)) return fromEnv; const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; - // Dev build (repo checkout): sidecar/dust-sync/target/release/dust-sync. - // Try both nesting depths so it resolves from `src/lib` (tsx) AND the bundled - // `dist/` — import.meta.url differs between them. + // Dev build (repo checkout): sidecar/dust-sync/target/release/dust-sync, + // three levels up from the engine package's src/ (tsx) and from its dist/. const here = dirname(fileURLToPath(import.meta.url)); - for (const up of [['..', '..'], ['..']]) { + for (const up of [['..', '..', '..']]) { const devBuild = join(here, ...up, 'sidecar', 'dust-sync', 'target', 'release', exe); if (existsSync(devBuild)) return devBuild; } diff --git a/src/engine/rc/dust-wallet.ts b/packages/engine-rc/src/dust-wallet.ts similarity index 100% rename from src/engine/rc/dust-wallet.ts rename to packages/engine-rc/src/dust-wallet.ts diff --git a/src/engine/rc/facade.ts b/packages/engine-rc/src/facade.ts similarity index 100% rename from src/engine/rc/facade.ts rename to packages/engine-rc/src/facade.ts diff --git a/src/engine/rc/fee-only-check.ts b/packages/engine-rc/src/fee-only-check.ts similarity index 100% rename from src/engine/rc/fee-only-check.ts rename to packages/engine-rc/src/fee-only-check.ts diff --git a/src/engine/rc/fork-schedule.ts b/packages/engine-rc/src/fork-schedule.ts similarity index 100% rename from src/engine/rc/fork-schedule.ts rename to packages/engine-rc/src/fork-schedule.ts diff --git a/src/engine/rc/index.ts b/packages/engine-rc/src/index.ts similarity index 100% rename from src/engine/rc/index.ts rename to packages/engine-rc/src/index.ts diff --git a/src/engine/rc/ledger-parameters.ts b/packages/engine-rc/src/ledger-parameters.ts similarity index 100% rename from src/engine/rc/ledger-parameters.ts rename to packages/engine-rc/src/ledger-parameters.ts diff --git a/src/engine/rc/raw-state.ts b/packages/engine-rc/src/raw-state.ts similarity index 100% rename from src/engine/rc/raw-state.ts rename to packages/engine-rc/src/raw-state.ts diff --git a/src/engine/rc/shielded-direct-cache.ts b/packages/engine-rc/src/shielded-direct-cache.ts similarity index 100% rename from src/engine/rc/shielded-direct-cache.ts rename to packages/engine-rc/src/shielded-direct-cache.ts diff --git a/src/engine/rc/shielded-direct.ts b/packages/engine-rc/src/shielded-direct.ts similarity index 100% rename from src/engine/rc/shielded-direct.ts rename to packages/engine-rc/src/shielded-direct.ts diff --git a/src/engine/rc/sign-recipe.ts b/packages/engine-rc/src/sign-recipe.ts similarity index 100% rename from src/engine/rc/sign-recipe.ts rename to packages/engine-rc/src/sign-recipe.ts diff --git a/src/engine/rc/transfer.ts b/packages/engine-rc/src/transfer.ts similarity index 100% rename from src/engine/rc/transfer.ts rename to packages/engine-rc/src/transfer.ts diff --git a/src/engine/rc/tx-inspect.ts b/packages/engine-rc/src/tx-inspect.ts similarity index 100% rename from src/engine/rc/tx-inspect.ts rename to packages/engine-rc/src/tx-inspect.ts diff --git a/src/engine/rc/wallet-data-repository.ts b/packages/engine-rc/src/wallet-data-repository.ts similarity index 100% rename from src/engine/rc/wallet-data-repository.ts rename to packages/engine-rc/src/wallet-data-repository.ts diff --git a/src/engine/rc/wallet.ts b/packages/engine-rc/src/wallet.ts similarity index 100% rename from src/engine/rc/wallet.ts rename to packages/engine-rc/src/wallet.ts diff --git a/packages/engine-rc/tsconfig.build.json b/packages/engine-rc/tsconfig.build.json new file mode 100644 index 00000000..16f7d7d6 --- /dev/null +++ b/packages/engine-rc/tsconfig.build.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node", + "ws" + ] + }, + "include": [ + "src/**/*.ts" + ] +} diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 046be4fb..663d4609 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -6,6 +6,6 @@ export function importRule(fromRel: string, toRel: string): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; /** The workspace packages carved out of src/: their names and source folders. */ -export const WORKSPACE_PACKAGES: readonly { name: string; dir: string }[]; +export const WORKSPACE_PACKAGES: readonly { name: string; dir: string; prefix?: string }[]; /** A file's path as the homes read it: under its package's source folder, or under src/. */ export function relOf(file: string): string; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index a921c162..3977423a 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -110,6 +110,8 @@ const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; export const WORKSPACE_PACKAGES = [ { name: '@kuiralabs/midnight-cli-core', dir: join(ROOT, 'packages', 'cli-core', 'src') }, { name: '@kuiralabs/midnight-chain', dir: join(ROOT, 'packages', 'chain', 'src') }, + // The rc engine: its files read as engine/rc/, its index the package itself. + { name: '@kuiralabs/midnight-engine-rc', dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/' }, ]; /** The package source folder a file is in, or undefined for one under src/. */ @@ -117,7 +119,8 @@ const packageOf = (file) => WORKSPACE_PACKAGES.find((pkg) => file.startsWith(pkg /** A file's path as the homes read it: under its package's source folder, or under src/. */ export function relOf(file) { - return relative(packageOf(file)?.dir ?? SRC, file); + const pkg = packageOf(file); + return (pkg?.prefix ?? '') + relative(pkg?.dir ?? SRC, file); } /** Where a file is, for a report: from the repository's root. */ @@ -203,14 +206,14 @@ export function findLayeringProblems() { } for (const { specifier, line } of importsOf(file)) { const where = `${shown(file)}:${line}`; - const pkg = WORKSPACE_PACKAGES.find((p) => specifier.startsWith(p.name + '/')); + const pkg = WORKSPACE_PACKAGES.find((p) => specifier === p.name || specifier.startsWith(p.name + '/')); const from = packageOf(file); if (specifier.startsWith('.') && from !== undefined && packageOf(resolve(dirname(file), specifier)) !== from) { violations.push({ home, rule: `${home} package → outside it (a package imports another only by name)`, where, specifier }); continue; } if (specifier.startsWith('.') || pkg !== undefined) { - const target = pkg !== undefined ? `${specifier.slice(pkg.name.length + 1)}.ts` : relOf(resolve(dirname(file), specifier)); + const target = pkg !== undefined ? `${pkg.prefix ?? ''}${specifier === pkg.name ? 'index' : specifier.slice(pkg.name.length + 1)}.ts` : relOf(resolve(dirname(file), specifier)); const rule = importRule(rel, target); if (rule !== undefined) violations.push({ home, rule, where, specifier }); } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine') { diff --git a/scripts/measure-preprod-dust.ts b/scripts/measure-preprod-dust.ts index e11b3714..cea56d12 100644 --- a/scripts/measure-preprod-dust.ts +++ b/scripts/measure-preprod-dust.ts @@ -25,7 +25,7 @@ import { join } from 'node:path'; import { homedir } from 'node:os'; import { execSync } from 'node:child_process'; -import { WalletDataRepository, defaultRepository } from '../src/engine/rc/wallet-data-repository.ts'; +import { WalletDataRepository, defaultRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import { getNetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { unlockWallet, resolveWalletPath } from '../src/lib/wallet-config.ts'; diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index 0dd9b277..dab1fcf0 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -7,7 +7,7 @@ // passphrase it was made with. import * as fs from 'node:fs'; -import { rcEngine } from '../engine/rc/index.ts'; +import { rcEngine } from '@kuiralabs/midnight-engine-rc'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; diff --git a/src/__tests__/airdrop-command.test.ts b/src/__tests__/airdrop-command.test.ts index e99ba27c..bef1ad63 100644 --- a/src/__tests__/airdrop-command.test.ts +++ b/src/__tests__/airdrop-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import airdropCommand from '../commands/airdrop.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index 57f0a992..8526addb 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/balance-command.test.ts b/src/__tests__/balance-command.test.ts index 843b9622..6a6a2a27 100644 --- a/src/__tests__/balance-command.test.ts +++ b/src/__tests__/balance-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 0097c311..ea13861d 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -18,7 +18,7 @@ import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; import { setPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { establishPassphrase, isPassphraseSet } from '../lib/passphrase.ts'; -import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { loadWalletConfig, protectAllWallets } from '../lib/wallet-config.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; diff --git a/src/__tests__/contract-raw-state.test.ts b/src/__tests__/contract-raw-state.test.ts index f3447c9b..fd317a43 100644 --- a/src/__tests__/contract-raw-state.test.ts +++ b/src/__tests__/contract-raw-state.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { ChargedState, ContractState, StateBoundedMerkleTree, StateMap, StateValue } from '@midnight-ntwrk/compact-runtime'; -import { describeRawState } from '../engine/rc/raw-state.ts'; +import { describeRawState } from '@kuiralabs/midnight-engine-rc/raw-state'; const atom = (bytes: number[]) => ({ value: [new Uint8Array(bytes)], alignment: [{ tag: 'atom' as const, value: { tag: 'bytes' as const, length: bytes.length } }] }); diff --git a/src/__tests__/contract-runner-endpoints.test.ts b/src/__tests__/contract-runner-endpoints.test.ts index 833526e0..7c9014b7 100644 --- a/src/__tests__/contract-runner-endpoints.test.ts +++ b/src/__tests__/contract-runner-endpoints.test.ts @@ -6,7 +6,7 @@ import { describe, expect, it } from 'vitest'; import { BlockfrostProjectIdRequiredError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { SCRIPT_PARTS, indexerEnvironment } from '../lib/contract/runner.ts'; -import * as rcScripts from '../engine/rc/contract-scripts.ts'; +import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; // The rc engine's scripts, with the parts the runner gives every engine. diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index 3cffdf32..13c66b7f 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -32,8 +32,8 @@ import { runDeploy, runState, } from '../lib/contract/runner.ts'; -import * as rcScripts from '../engine/rc/contract-scripts.ts'; -import { PROVIDER_IMPORTS, walletProviderCode } from '../engine/rc/contract-scripts.ts'; +import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; +import { PROVIDER_IMPORTS, walletProviderCode } from '@kuiralabs/midnight-engine-rc/contract-scripts'; import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; // The rc engine's scripts, with the parts the runner gives every engine. diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index 777382e5..6650b301 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -20,9 +20,9 @@ import { scriptRuntime, undoOverlay, } from '../lib/contract/runner.ts'; -import * as rcScripts from '../engine/rc/contract-scripts.ts'; -import { SCRIPT_PACKAGES, packageFolder } from '../engine/rc/contract-scripts.ts'; -import { rcEngine } from '../engine/rc/index.ts'; +import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; +import { SCRIPT_PACKAGES, packageFolder } from '@kuiralabs/midnight-engine-rc/contract-scripts'; +import { rcEngine } from '@kuiralabs/midnight-engine-rc'; import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; // The rc engine's scripts, with the parts the runner gives every engine. @@ -33,7 +33,7 @@ const generateStateScript = (opts: StateScript & { dappDir?: string }): string = const overlayScriptPackages = (userNodeModules: string) => overlayScriptPackagesFor(userNodeModules, rcEngine.contracts.scripts); const acquireOverlay = (dir: string): void => acquireOverlayFor(dir, rcEngine.contracts.scripts); -import { platformPackageBinary } from '../engine/rc/dust-sync-native.ts'; +import { platformPackageBinary } from '@kuiralabs/midnight-engine-rc/dust-sync-native'; const NETWORK = { indexer: 'http://localhost:28088/api/v4/graphql', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', node: 'ws://localhost:29944', proofServer: 'http://localhost:26300', networkId: 'Undeployed' }; let dir: string; diff --git a/src/__tests__/dapp-connector.test.ts b/src/__tests__/dapp-connector.test.ts index f06cb926..bf3c5897 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/src/__tests__/dapp-connector.test.ts @@ -10,20 +10,20 @@ import { Effect } from 'effect'; // Stub SDK address encoding — MidnightBech32m.encode returns a mock -import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '../engine/rc/dapp-connector.ts'; +import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; -import { PartlySignedTransactionError } from '../engine/rc/sign-recipe.ts'; +import { PartlySignedTransactionError } from '@kuiralabs/midnight-engine-rc/sign-recipe'; import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { Intent, UnshieldedOffer, verifySignature } from '@midnightntwrk/ledger-v9'; -import type { FacadeBundle } from '../engine/rc/facade.ts'; +import type { FacadeBundle } from '@kuiralabs/midnight-engine-rc/facade'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { RpcHandlerContext } from '../lib/ws-rpc.ts'; import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { FORK_SCHEDULE } from '../engine/rc/fork-schedule.ts'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '../engine/rc/derive-address.ts'; +import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; +import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; diff --git a/src/__tests__/derive-address.test.ts b/src/__tests__/derive-address.test.ts index 3f5d90b5..f1c67154 100644 --- a/src/__tests__/derive-address.test.ts +++ b/src/__tests__/derive-address.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); diff --git a/src/__tests__/dust-collapse.test.ts b/src/__tests__/dust-collapse.test.ts index 84c49e33..1ecc80d1 100644 --- a/src/__tests__/dust-collapse.test.ts +++ b/src/__tests__/dust-collapse.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { computeForeignRanges, collapseForeignGenerations } from '../engine/rc/dust-collapse.ts'; +import { computeForeignRanges, collapseForeignGenerations } from '@kuiralabs/midnight-engine-rc/dust-collapse'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; // Same initial dust params the sync path uses (dust-direct.ts). diff --git a/src/__tests__/dust-command.test.ts b/src/__tests__/dust-command.test.ts index 155e79b9..90c45f65 100644 --- a/src/__tests__/dust-command.test.ts +++ b/src/__tests__/dust-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import dustCommand from '../commands/dust.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/dust-direct-cache.test.ts b/src/__tests__/dust-direct-cache.test.ts index d70875de..861a899d 100644 --- a/src/__tests__/dust-direct-cache.test.ts +++ b/src/__tests__/dust-direct-cache.test.ts @@ -7,7 +7,7 @@ import * as path from 'path'; import * as os from 'os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { loadDustCache, saveDustCache, dustPublicKeyHex } from '../engine/rc/dust-direct-cache.ts'; +import { loadDustCache, saveDustCache, dustPublicKeyHex } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; import { clearDustDirectCache, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; const CACHE_DIR = path.join(os.tmpdir(), `midnight-dust-cache-test-${process.pid}-${Date.now()}`); diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index 14114bed..fbd3ef07 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { overlayDustDirectSnapshot } from '../engine/rc/facade.ts'; -import type { DustCacheEntry } from '../engine/rc/dust-direct-cache.ts'; +import { overlayDustDirectSnapshot } from '@kuiralabs/midnight-engine-rc/facade'; +import type { DustCacheEntry } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; // overlayDustDirectSnapshot is the seam behind `dust export` (and the write-command @@ -96,10 +96,10 @@ import { beforeEach, afterEach } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { exportDustSnapshot } from '../engine/rc/dust-export.ts'; -import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; +import { exportDustSnapshot } from '@kuiralabs/midnight-engine-rc/dust-export'; +import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; +import type { DustDirectResult } from '@kuiralabs/midnight-engine-rc/dust-direct'; const EXPORT_NETWORK: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', diff --git a/src/__tests__/dust-logic.test.ts b/src/__tests__/dust-logic.test.ts index f9bf2743..d9c8fe3b 100644 --- a/src/__tests__/dust-logic.test.ts +++ b/src/__tests__/dust-logic.test.ts @@ -4,9 +4,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import * as rx from 'rxjs'; -import { isDustRelatedError, ensureDust, registerNightUtxos } from '../engine/rc/transfer.ts'; +import { isDustRelatedError, ensureDust, registerNightUtxos } from '@kuiralabs/midnight-engine-rc/transfer'; import { DustFeeNotGeneratedError } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; -import type { FacadeBundle } from '../engine/rc/facade.ts'; +import type { FacadeBundle } from '@kuiralabs/midnight-engine-rc/facade'; import type { DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; diff --git a/src/__tests__/dust-sync-native.test.ts b/src/__tests__/dust-sync-native.test.ts index cedbb65e..459b2e09 100644 --- a/src/__tests__/dust-sync-native.test.ts +++ b/src/__tests__/dust-sync-native.test.ts @@ -10,7 +10,7 @@ import { nativeDustSyncAvailable, runDustSyncNative, type SidecarCheckpoint, -} from '../engine/rc/dust-sync-native.ts'; +} from '@kuiralabs/midnight-engine-rc/dust-sync-native'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; describe('resumeDecision (kill-safe resume)', () => { diff --git a/src/__tests__/dust-wallet.test.ts b/src/__tests__/dust-wallet.test.ts index ce81900a..f22b0cd9 100644 --- a/src/__tests__/dust-wallet.test.ts +++ b/src/__tests__/dust-wallet.test.ts @@ -10,8 +10,8 @@ import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import { Transacting } from '@midnightntwrk/wallet-sdk/dust/v2'; import { WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk/facade'; import { EitherOps } from '@midnightntwrk/wallet-sdk/utilities'; -import { ConvergingDustTransacting, DustWallet } from '../engine/rc/dust-wallet.ts'; -import { FORK_SCHEDULE } from '../engine/rc/fork-schedule.ts'; +import { ConvergingDustTransacting, DustWallet } from '@kuiralabs/midnight-engine-rc/dust-wallet'; +import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; import { dustShortfallOf, isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { CAPTURED_AT, type FeeRange, coinsAt, computeArguments, feeRange, paymentToBalance, timeWhenSmallestReaches, transacting, diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index 5ed01371..fd1bea7a 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { anyEngine, engineFor, sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { rcEngine } from '../engine/rc/index.ts'; +import { rcEngine } from '@kuiralabs/midnight-engine-rc'; describe('the engine for a network', () => { it('is the rc engine for every network mn knows today', async () => { diff --git a/src/__tests__/facade.test.ts b/src/__tests__/facade.test.ts index 9d3948e8..35d09185 100644 --- a/src/__tests__/facade.test.ts +++ b/src/__tests__/facade.test.ts @@ -7,7 +7,7 @@ import { WebSocketServer } from 'ws'; import { SyncProgress } from '@midnightntwrk/wallet-sdk'; import { SyncProgress as UnshieldedSyncProgress } from '@midnightntwrk/wallet-sdk/unshielded/v2'; import type { FacadeState } from '@midnightntwrk/wallet-sdk/facade'; -import { isFacadeSynced, detectStaleCache } from '../engine/rc/facade.ts'; +import { isFacadeSynced, detectStaleCache } from '@kuiralabs/midnight-engine-rc/facade'; type IndexProgress = ReturnType; type TxProgress = ReturnType; @@ -157,7 +157,7 @@ describe('startAndSyncFacade: starting the wallets exactly once', () => { async function startWith(restoredFromCache: boolean) { const { vi } = await import('vitest'); const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); + const { startAndSyncFacade } = await import('@kuiralabs/midnight-engine-rc/facade'); const seeds = { shielded: new Uint8Array([1]), unshielded: new Uint8Array([2]), dust: new Uint8Array([3]) }; const calls = { facadeStart: vi.fn(async () => {}), @@ -231,7 +231,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { async function syncWith(indexerWsUrl: string) { const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); + const { startAndSyncFacade } = await import('@kuiralabs/midnight-engine-rc/facade'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, seeds: {}, @@ -260,7 +260,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const url = await indexerWith({ zswapLedgerEvents: { id: 0, maxId: 384 }, dustLedgerEvents: { id: 0, maxId: 385 } }); const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('../engine/rc/facade.ts'); + const { startAndSyncFacade } = await import('@kuiralabs/midnight-engine-rc/facade'); const { CancelledError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, @@ -281,7 +281,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { describe('waitForDustAvailable', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const rx = await import('rxjs'); - const { waitForDustAvailable } = await import('../engine/rc/facade.ts'); + const { waitForDustAvailable } = await import('@kuiralabs/midnight-engine-rc/facade'); const { CancelledError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); // A wallet with no Dust, and no later state. const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; @@ -293,7 +293,7 @@ describe('waitForDustAvailable', () => { it('returns the latest state when its timeout passes without Dust, as before', async () => { const rx = await import('rxjs'); - const { waitForDustAvailable } = await import('../engine/rc/facade.ts'); + const { waitForDustAvailable } = await import('@kuiralabs/midnight-engine-rc/facade'); const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; await expect(waitForDustAvailable(bundle, 50, new AbortController().signal)).resolves.toBe(noDust); diff --git a/src/__tests__/fee-only-check.test.ts b/src/__tests__/fee-only-check.test.ts index 36c6e2a9..ff818f8a 100644 --- a/src/__tests__/fee-only-check.test.ts +++ b/src/__tests__/fee-only-check.test.ts @@ -14,7 +14,7 @@ import { shieldedToken, signData, } from '@midnightntwrk/ledger-v9'; -import { expiredIntents, feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; +import { expiredIntents, feeOnlyRefusals, readDAppTransaction } from '@kuiralabs/midnight-engine-rc/fee-only-check'; import { AGENT_SK, AGENT_VK, NETWORK, NIGHT, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, sealedBytes, spend, unsealedBytes, diff --git a/src/__tests__/fee-only-signing.test.ts b/src/__tests__/fee-only-signing.test.ts index 4dd379c9..31ce4a5e 100644 --- a/src/__tests__/fee-only-signing.test.ts +++ b/src/__tests__/fee-only-signing.test.ts @@ -23,8 +23,8 @@ import { type SignatureVerifyingKey, } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; -import { signRecipe } from '../engine/rc/sign-recipe.ts'; +import { feeOnlyRefusals, readDAppTransaction } from '@kuiralabs/midnight-engine-rc/fee-only-check'; +import { signRecipe } from '@kuiralabs/midnight-engine-rc/sign-recipe'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, spend, unsealedBytes, diff --git a/src/__tests__/helpers/offline-facade.ts b/src/__tests__/helpers/offline-facade.ts index 13f0a473..80020a20 100644 --- a/src/__tests__/helpers/offline-facade.ts +++ b/src/__tests__/helpers/offline-facade.ts @@ -7,11 +7,11 @@ // loopback port. import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; -import { DustWallet } from '../../engine/rc/dust-wallet.ts'; +import { DustWallet } from '@kuiralabs/midnight-engine-rc/dust-wallet'; import { WalletFacade, WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk/facade'; import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; import { PublicKey, UnshieldedWallet, createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; -import { FORK_SCHEDULE } from '../../engine/rc/fork-schedule.ts'; +import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/lib/constants'; import { NETWORK } from './ledger-tx.ts'; diff --git a/src/__tests__/info-command.test.ts b/src/__tests__/info-command.test.ts index ae87947d..ca9d88c6 100644 --- a/src/__tests__/info-command.test.ts +++ b/src/__tests__/info-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import infoCommand from '../commands/info.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index 8a139567..a9c1bd7b 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -16,7 +16,7 @@ import inspectCostCommand from '../commands/inspect-cost.ts'; import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; import helpCommand from '../commands/help.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { localIndexerFlags } from './helpers/local-indexer.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/mcp-server-concurrent-calls.test.ts b/src/__tests__/mcp-server-concurrent-calls.test.ts index 63634694..617364ce 100644 --- a/src/__tests__/mcp-server-concurrent-calls.test.ts +++ b/src/__tests__/mcp-server-concurrent-calls.test.ts @@ -21,7 +21,7 @@ import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.js'; -import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { toNight } from '@kuiralabs/midnight-cli-core/ui/format'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; diff --git a/src/__tests__/multi-wallet.test.ts b/src/__tests__/multi-wallet.test.ts index 900b41f4..fd954eab 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/src/__tests__/multi-wallet.test.ts @@ -26,7 +26,7 @@ import { FILE_MODE, isValidWalletName, } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; // Use a temp dir that simulates ~/.midnight const TEST_HOME = path.join(os.tmpdir(), `midnight-multi-wallet-test-${process.pid}`); diff --git a/src/__tests__/network-id.test.ts b/src/__tests__/network-id.test.ts index 7fbd085f..198ceb36 100644 --- a/src/__tests__/network-id.test.ts +++ b/src/__tests__/network-id.test.ts @@ -36,7 +36,7 @@ describe('the plain values the base keeps match the SDK', () => { it("keeps the ledger-9 fork at the SDK's version, and the facade's schedule starts there", async () => { const { ProtocolVersion } = await import('@midnightntwrk/wallet-sdk'); const { LEDGER_9_FORK_VERSION } = await import('@kuiralabs/midnight-cli-core/lib/network'); - const { FORK_SCHEDULE } = await import('../engine/rc/fork-schedule.ts'); + const { FORK_SCHEDULE } = await import('@kuiralabs/midnight-engine-rc/fork-schedule'); expect(LEDGER_9_FORK_VERSION).toBe(ProtocolVersion.V9NativeForkVersion); expect(FORK_SCHEDULE.v9).toBe(LEDGER_9_FORK_VERSION); }); diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index e6f810ae..b09a5343 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -9,7 +9,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { notice, setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { unlockWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; const ROOT = path.resolve(import.meta.dirname, '..', '..'); diff --git a/src/__tests__/package-metadata.test.ts b/src/__tests__/package-metadata.test.ts index f9db46cd..f9857039 100644 --- a/src/__tests__/package-metadata.test.ts +++ b/src/__tests__/package-metadata.test.ts @@ -33,3 +33,30 @@ describe('repository links', () => { expect(manual).toContain(`Repository: ${PKG_REPOSITORY_URL.replace(/^https:\/\//, '')}`); }); }); + +// One SDK set per engine package, and none at mn's root: with no SDK at the +// root, an import of it outside an engine fails to resolve instead of loading +// another copy beside the engine's. +describe('the SDK in the manifests', () => { + const isSdk = (name: string) => /^@midnight(-ntwrk|ntwrk)\//.test(name); + const manifest = (dir: string) => JSON.parse(readFileSync(join('packages', dir, 'package.json'), 'utf8')); + + it('is no dependency of mn itself', () => { + expect(Object.keys(root.dependencies ?? {}).filter(isSdk)).toStrictEqual([]); + expect(Object.keys(root.optionalDependencies ?? {}).filter(isSdk)).toStrictEqual([]); + }); + + it('is pinned exactly by each engine package, its ledger and onchain runtime directly', () => { + const engines = packageDirs.filter((dir) => dir.startsWith('engine-')); + expect(engines.length).toBeGreaterThan(0); + for (const dir of engines) { + const sdk = Object.entries(manifest(dir).dependencies).filter(([name]) => isSdk(name)); + for (const [name, range] of sdk) expect(range, `${dir} ${name}`).toMatch(/^\d+\.\d+\.\d+(-[\w.]+)?$/); + expect(sdk.map(([name]) => name), dir).toEqual(expect.arrayContaining(['@midnightntwrk/ledger-v9', '@midnightntwrk/onchain-runtime-v4'])); + } + }); + + it('is no dependency of core or chain', () => { + for (const dir of ['cli-core', 'chain']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); + }); +}); diff --git a/src/__tests__/read-cancellation.test.ts b/src/__tests__/read-cancellation.test.ts index a0cb1873..a1b2f1d6 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/src/__tests__/read-cancellation.test.ts @@ -17,7 +17,7 @@ import { waitForFirstBlock } from '@kuiralabs/midnight-chain/lib/node-ready'; import { waitForAddressFunded } from '@kuiralabs/midnight-chain/lib/indexer-ready'; import { waitForProofServerReady } from '@kuiralabs/midnight-chain/lib/proof-server-ready'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; -import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; +import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import { getNetworkConfig, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index f77fe1a2..b10e5c33 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -16,7 +16,7 @@ import addressCommand from '../commands/address.ts'; import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { localIndexerFlags } from './helpers/local-indexer.ts'; import { ownCall } from './helpers/own-call.ts'; diff --git a/src/__tests__/sealed-account.test.ts b/src/__tests__/sealed-account.test.ts index d9dd3bba..7dd8d087 100644 --- a/src/__tests__/sealed-account.test.ts +++ b/src/__tests__/sealed-account.test.ts @@ -7,7 +7,7 @@ // node:test as that suite is written. import { execFileSync } from 'node:child_process'; -import { rcEngine } from '../engine/rc/index.ts'; +import { rcEngine } from '@kuiralabs/midnight-engine-rc'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; diff --git a/src/__tests__/sealed-wallet.test.ts b/src/__tests__/sealed-wallet.test.ts index 289aee81..559ee191 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/src/__tests__/sealed-wallet.test.ts @@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { loadWalletConfig, protectAllWallets, sealWalletInPlace, unlockWallet, writeSealedWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { stateRootIn } from './helpers/state-root-in.ts'; diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index b84b5036..4231d845 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; diff --git a/src/__tests__/shielded-direct-cache.test.ts b/src/__tests__/shielded-direct-cache.test.ts index 49c5275c..8f23b4c8 100644 --- a/src/__tests__/shielded-direct-cache.test.ts +++ b/src/__tests__/shielded-direct-cache.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync, mkdirSync import { join } from 'node:path'; import { tmpdir } from 'node:os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { shieldedCoinPublicKeyHexFromSeed, loadShieldedCache, saveShieldedCache } from '../engine/rc/shielded-direct-cache.ts'; +import { shieldedCoinPublicKeyHexFromSeed, loadShieldedCache, saveShieldedCache } from '@kuiralabs/midnight-engine-rc/shielded-direct-cache'; import { getShieldedCachePath, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; const PUBKEY = 'aabbccddeeff00112233445566778899aabbccddeeff001122334455667788ff'; diff --git a/src/__tests__/shielded-direct.test.ts b/src/__tests__/shielded-direct.test.ts index 37e900c2..a545b936 100644 --- a/src/__tests__/shielded-direct.test.ts +++ b/src/__tests__/shielded-direct.test.ts @@ -2,8 +2,8 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; import type { AddressInfo } from 'node:net'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { readShieldedBalanceDirect } from '../engine/rc/shielded-direct.ts'; -import { deriveShieldedSeed } from '../engine/rc/derivation.ts'; +import { readShieldedBalanceDirect } from '@kuiralabs/midnight-engine-rc/shielded-direct'; +import { deriveShieldedSeed } from '@kuiralabs/midnight-engine-rc/derivation'; import zswapEvents from './fixtures/zswap-events-localnet.json'; // Real zswap ledger events (ledger 9, event[v14]) captured from a fresh localnet chain. Seeds 0x01 and diff --git a/src/__tests__/sign-recipe.test.ts b/src/__tests__/sign-recipe.test.ts index 97c1b514..9a4b3386 100644 --- a/src/__tests__/sign-recipe.test.ts +++ b/src/__tests__/sign-recipe.test.ts @@ -20,10 +20,10 @@ import { type SignatureVerifyingKey, } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { feeOnlyRefusals, readDAppTransaction } from '../engine/rc/fee-only-check.ts'; +import { feeOnlyRefusals, readDAppTransaction } from '@kuiralabs/midnight-engine-rc/fee-only-check'; import { PartlySignedTransactionError, SignedTransactionNeedsUnshieldedError, assertSignable, signRecipe, unshieldedImbalanceSegments, unshieldedSignatures, -} from '../engine/rc/sign-recipe.ts'; +} from '@kuiralabs/midnight-engine-rc/sign-recipe'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, spend, unsealedBytes, diff --git a/src/__tests__/transfer-command.test.ts b/src/__tests__/transfer-command.test.ts index 6ade2715..7ed3baa3 100644 --- a/src/__tests__/transfer-command.test.ts +++ b/src/__tests__/transfer-command.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import transferCommand from '../commands/transfer.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import * as fs from 'fs'; diff --git a/src/__tests__/transfer-lib.test.ts b/src/__tests__/transfer-lib.test.ts index d99bcb95..a0db6ced 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/src/__tests__/transfer-lib.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect } from 'vitest'; -import { validateRecipientAddress, isDustRelatedError } from '../engine/rc/transfer.ts'; +import { validateRecipientAddress, isDustRelatedError } from '@kuiralabs/midnight-engine-rc/transfer'; import { nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; +import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index 04cf106a..dcd2f0f5 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -9,7 +9,7 @@ import * as path from 'path'; import { resolveTransferRequest } from '../lib/transfer-request.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '@kuiralabs/midnight-cli-core/lib/constants'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index f86f0a5b..a96d70cf 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -12,8 +12,8 @@ import { captureCommand } from '../lib/run-command.ts'; import { callDiagnostics } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; -import { deriveUnshieldedAddress } from '../engine/rc/derive-address.ts'; -import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; +import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import balanceCommand from '../commands/balance.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index aed47d3d..428c2dbc 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -6,7 +6,7 @@ import { loadWalletConfig, matchWalletAddress, unlockWallet, writeSealedWallet, import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { stateRootIn } from './helpers/state-root-in.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-wallet-test-${process.pid}`); diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index d6800c39..7046ae3e 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -10,7 +10,7 @@ import * as path from 'node:path'; import { mnemonicToSeedSync } from '@scure/bip39'; import { createWallet, walletFilePath, walletSecretFrom } from '../lib/wallet-create.ts'; import { getActiveWalletName, unlockWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index 6f109753..a72dd092 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -10,11 +10,11 @@ import { join } from 'node:path'; import { Buffer } from 'node:buffer'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '../engine/rc/wallet-data-repository.ts'; +import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import { UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import type { DustDirectResult } from '../engine/rc/dust-direct.ts'; +import type { DustDirectResult } from '@kuiralabs/midnight-engine-rc/dust-direct'; // ── Test fixtures ───────────────────────────────────────── diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index c92aa62c..354287c3 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -13,7 +13,7 @@ import walletCommand from '../commands/wallet.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { PASSPHRASE_ENV, isPassphraseSet } from '../lib/passphrase.ts'; import { loadWalletConfig } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '../engine/rc/derive-address.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { accountProtector } from '../lib/grant/account-protector.ts'; diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index 91d56831..ce76ab17 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -11,8 +11,8 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { WalletDataRepository } from '../engine/rc/wallet-data-repository.ts'; -import { dustPublicKeyHexFromSeed, saveDustCache } from '../engine/rc/dust-direct-cache.ts'; +import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; +import { dustPublicKeyHexFromSeed, saveDustCache } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; diff --git a/src/lib/installed-engines.ts b/src/lib/installed-engines.ts index 9050f8de..ff2ba28f 100644 --- a/src/lib/installed-engines.ts +++ b/src/lib/installed-engines.ts @@ -8,6 +8,6 @@ import type { Engine, SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; export async function loadInstalledEngine(set: SdkSet): Promise { switch (set) { case 'rc': - return (await import('../engine/rc/index.ts')).rcEngine; + return (await import('@kuiralabs/midnight-engine-rc')).rcEngine; } } diff --git a/tsconfig.json b/tsconfig.json index 38c12966..417ff391 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts"], + "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts"], "exclude": ["node_modules"] } From 6735b244a3843d9c10c98016161057e5cc553551 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:30:05 -0800 Subject: [PATCH 33/88] A contract compiled for another runtime is refused up front (phase E, EE) Each SDK set runs contracts on its own compact runtime. A contract compiled for another failed inside its script, after the wallet had synced ("Version mismatch"). Now it is refused before anything starts, as a usage mistake naming both runtimes and the compiler the network's engine needs: by contract deploy and call before the wallet starts, by their MCP tools before a confirmation token, and by the runner before any script (dev, test, a program). The engine says its compact runtime, its compiler, and whether it runs a version, by the runtime's own rule. Also: tests ran some engine code from its build, not its source, since vitest's server-side resolution and its workers ignored the source condition; both now use it, and the suite passes with no package built. --- packages/cli-core/src/lib/engine.ts | 6 ++ packages/engine-rc/src/index.ts | 12 ++++ src/__tests__/contract-runtime-check.test.ts | 58 ++++++++++++++++++++ src/commands/contract.definition.ts | 12 +++- src/commands/contract.ts | 3 + src/lib/contract/runner.ts | 11 ++++ src/lib/contract/runtime-check.ts | 26 +++++++++ vitest.config.ts | 9 ++- vitest.live.config.ts | 1 + 9 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 src/__tests__/contract-runtime-check.test.ts create mode 100644 src/lib/contract/runtime-check.ts diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 2e12cf65..c8288ce6 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -113,6 +113,12 @@ export interface EngineContractScripts { readonly packages: readonly string[]; /** The folder of one of them as this engine's install has it; null when it isn't installed. */ packageFolder(name: string): string | null; + /** The compact runtime this engine runs contracts on. */ + readonly compactRuntimeVersion: string; + /** The compiler whose contracts that runtime runs, as a person would ask for it: `compactc 0.35`. */ + readonly compiler: string; + /** Whether this engine's compact runtime runs a contract compiled for `runtimeVersion` (the runtime's own rule). */ + acceptsRuntime(runtimeVersion: string): boolean; deploy(script: DeployScript, parts: ScriptParts): string; call(script: CallScript, parts: ScriptParts): string; state(script: StateScript, parts: ScriptParts): string; diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index 7c0dc975..172eb135 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -3,6 +3,7 @@ import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; import * as ledger from '@midnightntwrk/ledger-v9'; +import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { blockLimitsOf } from './ledger-parameters.ts'; import { rawContractState } from './contract-providers.ts'; @@ -41,6 +42,17 @@ export const rcEngine: Engine = { scripts: { packages: SCRIPT_PACKAGES, packageFolder, + compactRuntimeVersion, + // The compiler release whose contracts compact-runtime 0.20 runs (compactc 0.35.0 writes runtime-version 0.20.0). + compiler: 'compactc 0.35', + acceptsRuntime(runtimeVersion) { + try { + checkRuntimeVersion(runtimeVersion); + return true; + } catch { + return false; + } + }, deploy: generateDeployScript, call: generateCallScript, state: generateStateScript, diff --git a/src/__tests__/contract-runtime-check.test.ts b/src/__tests__/contract-runtime-check.test.ts new file mode 100644 index 00000000..b0d9d325 --- /dev/null +++ b/src/__tests__/contract-runtime-check.test.ts @@ -0,0 +1,58 @@ +// A contract compiled for another compact runtime than the network's engine +// runs is refused up front, naming the compiler that engine needs. + +import { describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; +import { runDeploy } from '../lib/contract/runner.ts'; + +const contract = (runtimeVersion: string, compilerVersion = '0.30.0') => ({ name: 'counter', compilerVersion, runtimeVersion }); + +describe('the rc engine\'s compact runtime', () => { + it('is the one it says, and takes contracts compiled for it, by the runtime\'s own rule', () => { + const { scripts } = rcEngine.contracts; + expect(scripts.compactRuntimeVersion).toBe('0.20.0'); + expect(scripts.compiler).toBe('compactc 0.35'); + expect(scripts.acceptsRuntime('0.20.0')).toBe(true); + expect(scripts.acceptsRuntime('0.19.0')).toBe(false); + expect(scripts.acceptsRuntime('0.16.0')).toBe(false); + expect(scripts.acceptsRuntime('0.20.1')).toBe(false); + }); +}); + +describe('a contract for another compact runtime', () => { + it('is refused as a usage mistake, naming both runtimes and the compiler to use', async () => { + const refused = await assertContractRunsOn(contract('0.16.0'), 'undeployed').then(() => undefined, (err: unknown) => err); + expect(refused).toBeInstanceOf(UsageError); + expect((refused as Error).message).toBe( + 'counter was compiled by compactc 0.30.0 for compact-runtime 0.16.0, but undeployed runs contracts on compact-runtime 0.20.0.\nRecompile it with compactc 0.35.', + ); + expect(classifyError(refused as Error).errorCode).toBe('INVALID_ARGS'); + }); + + it('lets through one compiled for the engine\'s runtime, and one whose compiler recorded none', async () => { + await expect(assertContractRunsOn(contract('0.20.0', '0.35.0'), 'undeployed')).resolves.toBeUndefined(); + await expect(assertContractRunsOn(contract('unknown', 'unknown'), 'undeployed')).resolves.toBeUndefined(); + }); + + it('is refused by the runner too, before any script runs', async () => { + const dappDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-runtime-check-')); + try { + const managedDir = path.join(dappDir, 'managed', 'counter'); + fs.mkdirSync(path.join(managedDir, 'compiler'), { recursive: true }); + fs.writeFileSync(path.join(managedDir, 'compiler', 'contract-info.json'), JSON.stringify({ 'compiler-version': '0.30.0', 'language-version': '0.22.0', 'runtime-version': '0.16.0', circuits: [], witnesses: [] })); + const networkConfig = { indexer: 'http://127.0.0.1:1', indexerWS: 'ws://127.0.0.1:1', node: 'ws://127.0.0.1:1', proofServer: 'http://127.0.0.1:1', networkId: 'Undeployed' }; + await expect(runDeploy({ dappDir, network: 'undeployed', networkConfig, managedDir, contractName: 'counter', servePort: 1 })) + .rejects.toThrow('Recompile it with compactc 0.35.'); + // No script was written into the dApp. + expect(fs.readdirSync(dappDir).filter((f) => f.endsWith('.mjs'))).toEqual([]); + } finally { + fs.rmSync(dappDir, { recursive: true, force: true }); + } + }); +}); diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index d27c5d3f..4b666e8d 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -214,7 +214,11 @@ export const contractDefinition: CommandDefinition = { }, async check(params, call) { const { resolveContractDeployRequest } = await import('../lib/contract/request.ts'); - resolveContractDeployRequest(call.argv()); + const args = call.argv(); + const { info } = resolveContractDeployRequest(args); + const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); + const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy').network); await checkSendingWallet(params); }, }, @@ -244,7 +248,11 @@ export const contractDefinition: CommandDefinition = { }, async check(params, call) { const { resolveContractCallRequest } = await import('../lib/contract/request.ts'); - resolveContractCallRequest(call.argv()); + const args = call.argv(); + const { info } = resolveContractCallRequest(args); + const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); + const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call').network); await checkSendingWallet(params); }, }, diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 5569115c..3ab6761d 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -14,6 +14,7 @@ import { callContract } from '../lib/contract/call.ts'; import { validateContractAddress } from '../lib/contract/validate.ts'; import { engineFor, type RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; +import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { findContractInfo, formatCircuitSignature, @@ -119,6 +120,7 @@ async function handleDeploy(args: ParsedArgs, payer: Payer, ctx: CallContext): P const target = resolvePayingTarget(args, 'contract', 'deploy'); const { network } = target; + await assertContractRunsOn(info, network); if (!jsonMode) { ctx.output.stderr(keyValue('Contract', info.name) + '\n'); @@ -192,6 +194,7 @@ async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Pro const target = resolvePayingTarget(args, 'contract', 'call'); const { network } = target; + await assertContractRunsOn(info, network); if (!jsonMode) { ctx.output.stderr(keyValue('Contract', info.name) + '\n'); diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 6eff291b..35d0d607 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -14,6 +14,8 @@ import { createRequire } from 'node:module'; import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { engineFor, type EngineContractScripts, type ScriptParts } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { findContractInfo } from './inspect.ts'; +import { assertContractRunsOn } from './runtime-check.ts'; import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; import { coerceArg } from './arg-coerce.ts'; import { resolvePrivateStateSecretKey } from './private-state-secret.ts'; @@ -107,6 +109,9 @@ export function indexerEnvironment(networkConfig: NetworkConfig): Record { + // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. + throwIfCancelled(options.signal); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); const { scripts } = (await engineFor(options.network)).contracts; const script = scripts.state(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); @@ -118,6 +123,9 @@ export async function runState(options: StateOptions): Promise { } export async function runDeploy(options: DeployOptions): Promise { + // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. + throwIfCancelled(options.signal); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); const { scripts } = (await engineFor(options.network)).contracts; const script = scripts.deploy(options, SCRIPT_PARTS); // The private-state secret goes to the subprocess via env (never the on-disk @@ -135,6 +143,9 @@ export async function runDeploy(options: DeployOptions): Promise { } export async function runCall(options: CallOptions): Promise { + // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. + throwIfCancelled(options.signal); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); const { scripts } = (await engineFor(options.network)).contracts; const script = scripts.call(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); diff --git a/src/lib/contract/runtime-check.ts b/src/lib/contract/runtime-check.ts new file mode 100644 index 00000000..e3730876 --- /dev/null +++ b/src/lib/contract/runtime-check.ts @@ -0,0 +1,26 @@ +// A compiled contract runs only on the compact runtime it was compiled for, +// and each SDK set has its own. A contract compiled for another refused up +// front, naming the compiler this network's set needs, instead of failing in +// its script after the wallet has synced ("Version mismatch"). + +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { ContractInfo } from './inspect.ts'; + +/** + * Throws a UsageError unless the engine for `network` runs a contract + * compiled for `info.runtimeVersion`. A contract from a compiler that records + * no runtime version is let through: its own code checks the runtime when it + * loads. + */ +export async function assertContractRunsOn(info: Pick, network: NetworkName): Promise { + if (info.runtimeVersion === 'unknown') return; + const { scripts } = (await engineFor(network)).contracts; + if (scripts.acceptsRuntime(info.runtimeVersion)) return; + throw new UsageError( + `${info.name} was compiled by compactc ${info.compilerVersion} for compact-runtime ${info.runtimeVersion}, ` + + `but ${network} runs contracts on compact-runtime ${scripts.compactRuntimeVersion}.\n` + + `Recompile it with ${scripts.compiler}.`, + ); +} diff --git a/vitest.config.ts b/vitest.config.ts index d2aa6b61..2c28b339 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,8 +2,11 @@ import { configDefaults, defineConfig } from 'vitest/config'; export default defineConfig({ // Inside this repository the workspace packages run from their source: - // here, and in every process a test starts (NODE_OPTIONS). + // in what vite resolves (both kinds of module it runs tests as), in the + // workers' own Node resolution, and in every process a test starts + // (NODE_OPTIONS). Without all three, some imports load a package's build. resolve: { conditions: ['midnight-cli-source'] }, + ssr: { resolve: { conditions: ['midnight-cli-source'], externalConditions: ['midnight-cli-source'] } }, test: { // Tests must never spawn the native dust-sync sidecar (it would make real // network calls / behave differently by machine). Force the WASM path; the @@ -18,6 +21,10 @@ export default defineConfig({ // 3 s on a laptop, 8 s on a CI runner, and 32 s on a runner that was four // times slower at everything (npm ci included). Nothing hangs, but vitest's // default 5 s fails them; a test that does hang still fails here. + poolOptions: { + forks: { execArgv: ['--conditions=midnight-cli-source'] }, + threads: { execArgv: ['--conditions=midnight-cli-source'] }, + }, testTimeout: 120_000, hookTimeout: 120_000, // Nested checkouts under .claude/ run their own tests; count only this diff --git a/vitest.live.config.ts b/vitest.live.config.ts index b0e6effe..495bb623 100644 --- a/vitest.live.config.ts +++ b/vitest.live.config.ts @@ -7,6 +7,7 @@ import base from './vitest.config.ts'; export default defineConfig({ resolve: base.resolve, + ssr: base.ssr, test: { ...base.test, include: ['src/**/*.live.test.ts'], From 9e3b47ceaba4576e21b5d0106d72138117787358 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:31:48 -0800 Subject: [PATCH 34/88] The runner's overlay stays out of the engine's install, one SDK set at a time (EE) - A scope folder the overlay links whole is the engine's own: nothing is linked inside it any more, which wrote into the engine's install. - The overlay record names the SDK set whose packages it linked. A run needing another set is refused while a run uses the overlay, saying so; once none does, the old overlay is undone and replaced. A record an older mn left is the rc set's. --- .../contract-script-packages.test.ts | 36 ++++++++++++++++-- src/lib/contract/runner.ts | 37 ++++++++++++++----- 2 files changed, 61 insertions(+), 12 deletions(-) diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index 6650b301..ec3db323 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -30,8 +30,9 @@ const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); // The overlay of the rc engine's packages. -const overlayScriptPackages = (userNodeModules: string) => overlayScriptPackagesFor(userNodeModules, rcEngine.contracts.scripts); -const acquireOverlay = (dir: string): void => acquireOverlayFor(dir, rcEngine.contracts.scripts); +const RC_PACKAGES = { ...rcEngine.contracts.scripts, set: 'rc' }; +const overlayScriptPackages = (userNodeModules: string) => overlayScriptPackagesFor(userNodeModules, RC_PACKAGES); +const acquireOverlay = (dir: string): void => acquireOverlayFor(dir, RC_PACKAGES); import { platformPackageBinary } from '@kuiralabs/midnight-engine-rc/dust-sync-native'; @@ -139,8 +140,37 @@ describe('a dApp laid out unlike ours', () => { expect(fs.readdirSync(dir)).toEqual([]); }); + it('links nothing inside a scope it linked whole, which would write into the engine\'s install', () => { + // A tree holding @x/a, and @x/b found elsewhere: the dApp has no @x, so @x is linked whole to the tree. + const tree = path.join(dir, 'tree', '@x'); + fs.mkdirSync(path.join(tree, 'a'), { recursive: true }); + const elsewhere = path.join(dir, 'elsewhere', '@x', 'b'); + fs.mkdirSync(elsewhere, { recursive: true }); + const dapp = path.join(dir, 'dapp', 'node_modules'); + fs.mkdirSync(dapp, { recursive: true }); + const packages = { set: 'rc', packages: ['@x/a', '@x/b'], packageFolder: (name: string) => (name === '@x/a' ? path.join(tree, 'a') : elsewhere) }; + const made = overlayScriptPackagesFor(dapp, packages); + expect(made.map((m) => path.relative(dir, m.path))).toEqual([path.join('dapp', 'node_modules', '@x')]); + expect(fs.readdirSync(tree)).toEqual(['a']); + undoOverlay(made); + }); + + it('refuses another SDK set\'s packages while a run uses its overlay, and replaces it once none does', () => { + acquireOverlay(dir); + const beta = { ...RC_PACKAGES, set: 'beta' }; + expect(() => acquireOverlayFor(dir, beta)).toThrow('uses the rc SDK set\'s packages, and this one needs the beta set\'s'); + // The rc run dies: its share is stale, so the beta run undoes the rc overlay and makes its own. + const record = path.join(dir, '.mn-overlay.json'); + const held = JSON.parse(fs.readFileSync(record, 'utf8')) as { pids: number[]; made: unknown[]; set: string }; + fs.writeFileSync(record, JSON.stringify({ ...held, pids: [2 ** 22 + 12345] })); + acquireOverlayFor(dir, beta); + expect(JSON.parse(fs.readFileSync(record, 'utf8'))).toMatchObject({ set: 'beta', pids: [process.pid] }); + releaseOverlay(dir); + expect(fs.readdirSync(dir)).toEqual([]); + }); + it('with no Node to run under, refuses before writing anything to the dApp', async () => { - await expect(executeScript({ dir, script: 'console.log(1)', packages: rcEngine.contracts.scripts, findRuntime: () => { throw new NoNodeRuntimeError(); } })).rejects.toThrow(NoNodeRuntimeError); + await expect(executeScript({ dir, script: 'console.log(1)', packages: RC_PACKAGES, findRuntime: () => { throw new NoNodeRuntimeError(); } })).rejects.toThrow(NoNodeRuntimeError); expect(fs.readdirSync(dir)).toEqual([]); }); }); diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 35d0d607..a69dbcab 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -112,7 +112,8 @@ export async function runState(options: StateOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); - const { scripts } = (await engineFor(options.network)).contracts; + const engine = await engineFor(options.network); + const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.state(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); try { @@ -126,7 +127,8 @@ export async function runDeploy(options: DeployOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); - const { scripts } = (await engineFor(options.network)).contracts; + const engine = await engineFor(options.network); + const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.deploy(options, SCRIPT_PARTS); // The private-state secret goes to the subprocess via env (never the on-disk // script) so a caller-chosen owner is not written to the filesystem. @@ -146,7 +148,8 @@ export async function runCall(options: CallOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); - const { scripts } = (await engineFor(options.network)).contracts; + const engine = await engineFor(options.network); + const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.call(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); try { @@ -283,8 +286,8 @@ export const SCRIPT_PARTS: ScriptParts = { /** What the overlay made, to undo afterwards newest first: a link, or a folder it created. */ type Made = { path: string; kind: 'link' | 'folder' }; -/** The packages a script imports, and where the engine's install has each. */ -type ScriptPackages = Pick; +/** The packages a script imports, where the engine's install has each, and the SDK set they are. */ +type ScriptPackages = Pick & { readonly set: string }; /** The installed copy of each scope the script packages use (`@midnight-ntwrk`, …), and the node_modules holding them. */ function installedTrees({ packages, packageFolder }: ScriptPackages): { root: string | null; scopes: Map } { @@ -326,11 +329,18 @@ export function overlayScriptPackages(userNodeModules: string, scriptPackages: S if (root !== null) link(root, userNodeModules); return made; } + // A scope linked whole is the engine's own folder: nothing is linked inside + // it, which would write into the engine's install. + const linkedWhole = new Set(); for (const [scope, folder] of scopes) { const at = join(userNodeModules, scope); - if (!existsSync(at)) link(folder, at); + if (!existsSync(at)) { + link(folder, at); + linkedWhole.add(scope); + } } for (const name of scriptPackages.packages) { + if (name.startsWith('@') && linkedWhole.has(name.slice(0, name.indexOf('/')))) continue; const at = join(userNodeModules, name); const target = existsSync(at) ? null : scriptPackages.packageFolder(name); if (target !== null) link(target, at); @@ -350,7 +360,7 @@ export function undoOverlay(made: readonly Made[]): void { /** The record, in a dApp folder, of the overlay its running scripts share. */ const OVERLAY_RECORD = '.mn-overlay.json'; -interface OverlayRecord { pids: number[]; made: Made[] } +interface OverlayRecord { pids: number[]; made: Made[]; set?: string } const isAlive = (pid: number): boolean => { try { process.kill(pid, 0); return true; } catch { return false; } @@ -367,8 +377,17 @@ export function acquireOverlay(dappDir: string, scriptPackages: ScriptPackages): let held: OverlayRecord | null = null; try { held = JSON.parse(readFileSync(record, 'utf8')) as OverlayRecord; } catch { /* none yet */ } const live = (held?.pids ?? []).filter(isAlive); + // An overlay of another SDK set's packages: refused while a run uses it, + // undone once none does (an older mn recorded no set: its packages are the rc set's). + if (held !== null && (held.set ?? 'rc') !== scriptPackages.set) { + if (live.length > 0) { + throw new Error(`Another contract run in ${dappDir} uses the ${held.set ?? 'rc'} SDK set's packages, and this one needs the ${scriptPackages.set} set's. Run it when that one has finished.`); + } + undoOverlay(held.made); + held = null; + } const made = held !== null ? held.made : overlayScriptPackages(join(dappDir, 'node_modules'), scriptPackages); - writeFileSync(record, JSON.stringify({ pids: [...live, process.pid], made } satisfies OverlayRecord)); + writeFileSync(record, JSON.stringify({ pids: [...live, process.pid], made, set: scriptPackages.set } satisfies OverlayRecord)); } /** Gives back this run's share; the last run out undoes the overlay and removes the record. */ @@ -379,7 +398,7 @@ export function releaseOverlay(dappDir: string): void { const mine = held.pids.indexOf(process.pid); const pids = held.pids.filter((pid, at) => at !== mine && isAlive(pid)); if (pids.length > 0) { - writeFileSync(record, JSON.stringify({ pids, made: held.made } satisfies OverlayRecord)); + writeFileSync(record, JSON.stringify({ pids, made: held.made, ...(held.set === undefined ? {} : { set: held.set }) } satisfies OverlayRecord)); return; } undoOverlay(held.made); From 824db40fb4f2e00fb2c5c38b8db1a229a4570b7c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 19:33:27 -0800 Subject: [PATCH 35/88] Each network names its SDK set; the engine follows it (phase E, ED) core's network table names the SDK set each network runs on (all rc today), and engineFor asks the host's loader for that set, once a process, refusing a second. Tests show the loader asked for the network's set once, and a second set refused. Whether config set can move a network to another set is still to decide. --- packages/cli-core/src/lib/engine.ts | 8 +++---- packages/cli-core/src/lib/network.ts | 13 ++++++++++++ src/__tests__/engine.test.ts | 31 ++++++++++++++++++++++++++-- 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index c8288ce6..57f0d0d7 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -5,7 +5,7 @@ // loader at start (the shell, the engines it ships), as it does the settings. // Loading an engine loads its SDK, so the loader imports it only when asked. -import type { NetworkConfig, NetworkName } from './network.ts'; +import { sdkSetOfNetwork, type NetworkConfig, type NetworkName } from './network.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; import type { VerboseLog } from './verbose.ts'; import type { ApprovalOptions } from './approval.ts'; @@ -424,9 +424,9 @@ export interface Engine { readonly wallet: EngineWallet; } -/** The SDK set a network runs on. */ -export function sdkSetOf(_network: NetworkName): SdkSet { - return 'rc'; +/** The SDK set a network runs on, as the network table names it. */ +export function sdkSetOf(network: NetworkName): SdkSet { + return sdkSetOfNetwork(network); } /** Loads the engine for an SDK set: the host's, which knows the engines it ships. */ diff --git a/packages/cli-core/src/lib/network.ts b/packages/cli-core/src/lib/network.ts index 9733f60b..915dbed8 100644 --- a/packages/cli-core/src/lib/network.ts +++ b/packages/cli-core/src/lib/network.ts @@ -3,6 +3,7 @@ import { execSync } from 'child_process'; import { loadCliConfig, getEndpointOverridesForNetwork } from './cli-config.ts'; import { INDEXER_GRAPHQL_PATH, INDEXER_GRAPHQL_WS_PATH } from './constants.ts'; import { settings } from './settings.ts'; +import type { SdkSet } from './engine.ts'; export type NetworkName = 'preprod' | 'preview' | 'undeployed'; @@ -46,6 +47,18 @@ const NETWORK_CONFIGS: Record = { }, }; +/** The SDK set each network runs on, whose engine a call on it loads (D28). */ +const NETWORK_SDK_SETS: Record = { + preprod: 'rc', + preview: 'rc', + undeployed: 'rc', +}; + +/** The SDK set a network runs on. */ +export function sdkSetOfNetwork(name: NetworkName): SdkSet { + return NETWORK_SDK_SETS[name]; +} + const VALID_NETWORK_NAMES: readonly NetworkName[] = ['preprod', 'preview', 'undeployed'] as const; export function isValidNetworkName(name: string): name is NetworkName { diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index fd1bea7a..611700f0 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -2,8 +2,9 @@ // same for work every set does alike. import { describe, expect, it } from 'vitest'; -import { anyEngine, engineFor, sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { anyEngine, engineFor, sdkSetOf, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { getValidNetworkNames, sdkSetOfNetwork, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { rcEngine } from '@kuiralabs/midnight-engine-rc'; describe('the engine for a network', () => { @@ -31,3 +32,29 @@ describe('the engine for a network', () => { } }); }); + +describe('the network picks the engine', () => { + it('asks the host\'s loader for the set the network table names, once a process', async () => { + const asked: string[] = []; + setEngineLoader(async (set) => { asked.push(set); return rcEngine; }); + try { + expect(await engineFor('preview')).toBe(rcEngine); + expect(await engineFor('undeployed')).toBe(rcEngine); + expect(asked).toStrictEqual(['rc']); + for (const network of getValidNetworkNames() as NetworkName[]) expect(sdkSetOf(network)).toBe(sdkSetOfNetwork(network)); + } finally { + setEngineLoader(loadInstalledEngine); + } + }); + + it('refuses a second set in a process that has loaded one', async () => { + const other = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; + setEngineLoader(async () => other); + try { + await expect(engineFor('undeployed')).rejects.toThrow("This process runs the beta SDK set and can't load the rc one"); + } finally { + setEngineLoader(loadInstalledEngine); + } + }); + +}); From e81b418c126467971c2ea0c6e24ad61b993f2bb2 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 20:54:20 -0800 Subject: [PATCH 36/88] Delete the unused Dust balance fast reader (Y34) readDustBalanceFast had no caller since the Dust reader moved to the repository's cached path. --- .../chain/src/lib/graphql-ws-subscription.ts | 2 +- packages/engine-rc/src/dust-balance-direct.ts | 153 ------------------ 2 files changed, 1 insertion(+), 154 deletions(-) delete mode 100644 packages/engine-rc/src/dust-balance-direct.ts diff --git a/packages/chain/src/lib/graphql-ws-subscription.ts b/packages/chain/src/lib/graphql-ws-subscription.ts index 70d1ecba..170e38b8 100644 --- a/packages/chain/src/lib/graphql-ws-subscription.ts +++ b/packages/chain/src/lib/graphql-ws-subscription.ts @@ -1,5 +1,5 @@ // Shared graphql-transport-ws subscription driver for the direct-from-indexer -// readers (shielded-direct, dust-direct, dust-balance-direct). Each reader used +// readers (shielded-direct, dust-direct). Each reader used // to hand-maintain the same connection_init → connection_ack → subscribe → // next/error/close handshake plus the settle-once / cleanup / idle-timer / // timeout / abort scaffolding; the guards drifted between copies. This centralizes diff --git a/packages/engine-rc/src/dust-balance-direct.ts b/packages/engine-rc/src/dust-balance-direct.ts deleted file mode 100644 index 29180ddb..00000000 --- a/packages/engine-rc/src/dust-balance-direct.ts +++ /dev/null @@ -1,153 +0,0 @@ -// Fast dust BALANCE reader — seconds instead of the ~22-min cold event replay. -// -// The dust balance is a pure function of the wallet's own dust generations and -// time: `sum over generations of updatedValue(ctime, initialValue, genInfo, now, -// params)`. The indexer's `dustGenerations(dustAddress, ...)` subscription streams -// exactly those generations (filtered to us, ~1 item vs 1.44M ledger events), so -// we can compute the balance directly without replaying the dust event history or -// building a `DustLocalState` at all. -// -// This is a READ path only. Spending dust (transfers) still needs the full -// `DustLocalState` (commitment tree + spend proofs) via the event-replay + cache. -// -// Params note: dust params are protocol constants replayed from `ParamChange` -// events, which this path skips. They are stable (verified equal to the initial -// values on preprod). Callers may pass current params if they have them; otherwise -// the initial constants are used. A `ParamChange` on-chain would require a full -// sync to pick up — acceptable for a fast balance read. - -import * as ledger from '@midnightntwrk/ledger-v9'; -import { DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; -import { NetworkId } from '@midnightntwrk/wallet-sdk'; - -import { - INITIAL_NIGHT_DUST_RATIO, - INITIAL_GENERATION_DECAY_RATE, - INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from '@kuiralabs/midnight-cli-core/lib/constants'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; - -const SUBSCRIPTION_QUERY = ` - subscription DustGenerations($a: DustAddress!, $s: Int!, $e: Int!) { - dustGenerations(dustAddress: $a, startIndex: $s, endIndex: $e) { - __typename - ... on DustGenerationsItem { generationMtIndex owner value initialValue backingNight ctime } - ... on DustGenerationDtimeUpdateItem { generationMtIndex newDtime } - ... on DustGenerationsProgress { highestIndex } - } - } -`; - -export interface DustBalanceFastResult { - /** Dust balance in atomic units. */ - balance: bigint; - /** Number of generations seen for this wallet. */ - generationCount: number; - /** Generations currently contributing > 0 to the balance. */ - activeGenerations: number; - /** True if we stopped before the stream signalled catch-up (timeout/abort). */ - partial: boolean; -} - -export interface DustBalanceFastOptions { - /** Current on-chain dust params. Defaults to the initial constants (stable on preprod). */ - params?: ledger.DustParameters; - /** Valuation time for accrual. Defaults to now. */ - now?: Date; - /** Generation-tree upper bound. Default 2^25 (well past any current tip); idle detection ends the read. */ - endIndex?: number; - /** Finish after this much silence once subscribed. Default 4s. */ - idleMs?: number; - /** Hard ceiling; on expiry resolve `partial: true`. Default 60s. */ - timeoutMs?: number; - /** Abort mid-flight. */ - signal?: AbortSignal; -} - -interface RawGeneration { - generationMtIndex: number; - owner: string; - value: string; - initialValue: string; - backingNight: string; - ctime: number; -} - -/** - * Read the wallet's dust balance directly from the `dustGenerations` subscription, - * summing `updatedValue` over its generations. Resolves in seconds. - */ -export function readDustBalanceFast( - dustSecretKey: ledger.DustSecretKey, - indexerWS: string, - networkId: NetworkId.NetworkId, - options: DustBalanceFastOptions = {}, -): Promise { - const { - params = new ledger.DustParameters( - INITIAL_NIGHT_DUST_RATIO, - INITIAL_GENERATION_DECAY_RATE, - INITIAL_DUST_GRACE_PERIOD_SECONDS, - ), - now = new Date(), - endIndex = 1 << 25, - idleMs = 4_000, - timeoutMs = 60_000, - signal, - } = options; - - const owner = dustSecretKey.publicKey; - const dustAddress = DustAddress.encodePublicKey(networkId, dustSecretKey.publicKey); - - // generation index -> its latest generation record and dtime (ms), if any. - const generations = new Map(); - const dtimes = new Map(); - - const computeBalance = (): { balance: bigint; active: number } => { - let balance = 0n; - let active = 0; - for (const [index, gen] of generations) { - const dt = dtimes.get(index); - const genInfo = { - value: BigInt(gen.value), - owner, - nonce: gen.backingNight, - dtime: dt !== undefined ? new Date(dt) : undefined, - } as ledger.DustGenerationInfo; - const v = ledger.updatedValue(new Date(gen.ctime * 1000), BigInt(gen.initialValue), genInfo, now, params); - if (v > 0n) active++; - balance += v; - } - return { balance, active }; - }; - - return subscribeGraphqlWs(indexerWS, { - query: SUBSCRIPTION_QUERY, - variables: { a: dustAddress, s: 0, e: endIndex }, - idleMs, - timeoutMs, - // Snapshot read: the stream delivers our (few) generations then goes quiet, - // so finish on idle even before a first item (an empty wallet has none). - idleBeforeFirstEvent: true, - signal, - onNext: (data) => { - const p = (data as { dustGenerations?: { __typename?: string; generationMtIndex?: unknown; newDtime?: unknown } } | undefined)?.dustGenerations; - if (!p) return false; - if (p.__typename === 'DustGenerationsItem') { - generations.set(Number(p.generationMtIndex), p as unknown as RawGeneration); - } else if (p.__typename === 'DustGenerationDtimeUpdateItem') { - dtimes.set(Number(p.generationMtIndex), Number(p.newDtime)); - } - // DustGenerationsProgress carries only tree/index bookkeeping; idle ends the read. - return false; // no tip concept — idle/timeout terminate the snapshot read - }, - buildResult: (partial) => { - try { - const { balance, active } = computeBalance(); - return { balance, generationCount: generations.size, activeGenerations: active, partial }; - } catch (err) { - throw new Error(`Failed to compute dust balance: ${(err as Error).message}`); - } - }, - }); -} From aff2b005ed8ac0cad267212d6196809783b02a2e Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 21:44:06 -0800 Subject: [PATCH 37/88] The wallet session: one typed API over the engine's connector (EF, D29) A program opens a wallet with openWalletSession({ seed, network }) from midnight-cli-core and calls addresses, balances, balanceTransaction, swap, sign, submit, readTransaction and close. The session is the engine's DApp connector in this process, approving everything, so its pending-revert rules hold; transactions travel as hex and the engine keeps the SDK's objects and the secret keys. It replaces WalletConnection: the payer's connect hands back a session, and the grant fee wallet uses it. The engine reads transactions (ledger.readTransaction) and checks the chain's ledger itself when it opens a connector, so a session opened from outside mn is refused on a ledger-8 chain as mn's own commands are. The shielded-sync policy moves to core, where the session's default sync mode reads it. The connector tests' facade stub moves to a shared helper. --- packages/cli-core/src/lib/engine.ts | 2 + packages/cli-core/src/lib/payer.ts | 15 +- .../cli-core/src}/lib/shielded-policy.ts | 0 packages/cli-core/src/lib/wallet-session.ts | 182 ++++++++++++++++++ packages/engine-rc/src/index.ts | 2 + packages/engine-rc/src/wallet.ts | 3 + scripts/check-layering.mjs | 2 +- src/__tests__/dapp-connector.test.ts | 108 +---------- src/__tests__/helpers/connector-stub.ts | 117 +++++++++++ src/__tests__/shielded-policy.test.ts | 2 +- src/__tests__/wallet-session.test.ts | 115 +++++++++++ src/commands/balance.ts | 2 +- src/commands/serve.ts | 2 +- src/lib/grant/fee-wallet.ts | 14 +- src/lib/serve-manager.ts | 5 +- src/lib/serve-payer.ts | 30 +-- src/lib/transfer-request.ts | 2 +- 17 files changed, 449 insertions(+), 154 deletions(-) rename {src => packages/cli-core/src}/lib/shielded-policy.ts (100%) create mode 100644 packages/cli-core/src/lib/wallet-session.ts create mode 100644 src/__tests__/helpers/connector-stub.ts create mode 100644 src/__tests__/wallet-session.test.ts diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 57f0d0d7..ec054783 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -55,6 +55,8 @@ export interface EngineLedger { blockLimits(parametersHex: string): BlockLimits; /** The raw id of the unshielded NIGHT token, as wallet balances are keyed. */ nightTokenId(): string; + /** What a serialized transaction (hex) is, as an approval prompt shows it; never throws. */ + readTransaction(txHex: string, stage: 'unsealed' | 'sealed'): TransactionDetail[]; } /** A contract's ledger state read without its compiled contract: cells as their field-aligned bytes in hex, maps by size. */ diff --git a/packages/cli-core/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts index bf0ff15b..a43cbccf 100644 --- a/packages/cli-core/src/lib/payer.ts +++ b/packages/cli-core/src/lib/payer.ts @@ -8,6 +8,7 @@ import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type Net import { resolveNetwork } from './resolve-network.ts'; import type { Spinner } from '../ui/spinner.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; +import type { WalletSession } from './wallet-session.ts'; /** The network a command acts on, with its endpoints resolved. */ export interface PayingTarget { @@ -44,16 +45,6 @@ export interface ServedWallet { stop: () => Promise; } -/** The DApp connector methods a command calls on the wallet that pays. */ -export type PayingMethod = 'getShieldedAddresses' | 'getShieldedBalances' | 'balanceUnsealedTransaction' | 'submitTransaction'; - -/** A wallet's DApp connector in this process, called by method name. */ -export interface WalletConnection { - call: (method: PayingMethod, params: Record) => Promise; - /** Reverts what was balanced but never submitted, then stops the wallet. */ - stop: () => Promise; -} - /** * Opens the wallet that pays, for the target network. `wallet` is the --wallet * flag; without it the active wallet pays. Progress goes to `progress`. @@ -78,8 +69,8 @@ export interface Payer { assertCanPay: (target: PayingTarget, wallet: string | undefined, progress: Spinner, signal: AbortSignal | undefined) => Promise; /** Serves the wallet; one that runs in this process keeps the SDK's warnings to the paying call's `sdkWarnings`. */ serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; - /** Opens the wallet in this process, keeping the SDK's warnings to the paying call's `sdkWarnings`. */ - connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; + /** Opens the wallet in this process as a session, keeping the SDK's warnings to the paying call's `sdkWarnings`. */ + connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; } /** What a command's caller gives it for one call. */ diff --git a/src/lib/shielded-policy.ts b/packages/cli-core/src/lib/shielded-policy.ts similarity index 100% rename from src/lib/shielded-policy.ts rename to packages/cli-core/src/lib/shielded-policy.ts diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts new file mode 100644 index 00000000..b27bb355 --- /dev/null +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -0,0 +1,182 @@ +// A wallet session: what a program holds of a wallet (D29). It opens a wallet +// through the engine for the network's SDK set and calls operations that read +// the same on every set; the engine keeps the SDK's objects and the secret +// keys. The session is the engine's DApp connector in this process, approving +// everything (the program is the operator), so its rules hold here too: a +// transaction balanced or built but never submitted is reverted on close, and +// one the chain refuses is reverted at once. Transactions travel as hex. + +import { engineFor, type DAppConnector, type OpenedConnector, type TransactionDetail } from './engine.ts'; +import type { NetworkConfig, NetworkName } from './network.ts'; +import { resolveNetwork } from './resolve-network.ts'; +import { shieldedSyncEnabled } from './shielded-policy.ts'; +import { throwIfCancelled } from './errors.ts'; + +/** The calls a session makes, under one connection name for the connector's pending transactions. */ +const SESSION_CONNECTION = 'wallet-session'; + +/** A wallet's addresses on the session's network, bech32m, and its shielded keys, hex. */ +export interface WalletAddresses { + unshielded: string; + shielded: string; + shieldedCoinPublicKey: string; + shieldedEncryptionPublicKey: string; + dust: string; +} + +/** What a wallet holds: tokens by their raw type, each in its smallest unit. */ +export interface WalletBalances { + unshielded: Record; + shielded: Record; + /** Dust, in its smallest unit. */ + dust: bigint; +} + +/** An amount of one token: its raw type (hex) and its kind. */ +export interface TokenAmount { + kind: 'shielded' | 'unshielded'; + type: string; + value: bigint; +} + +/** An amount paid to a recipient's address (bech32m) on the session's network. */ +export interface TokenPayment extends TokenAmount { + recipient: string; +} + +/** Data signed with the wallet's unshielded key. */ +export interface SignedData { + data: string; + signature: string; + verifyingKey: string; + scheme: string; +} + +export interface WalletSession { + readonly network: NetworkName; + addresses(): Promise; + balances(): Promise; + /** Pays the fees of an unsealed transaction (hex) and adds what its outputs need; the balanced transaction, sealed. */ + balanceTransaction(tx: string): Promise; + /** A swap offer: the wallet gives `give` for `take`, paying its fees; the transaction to submit or hand on. */ + swap(give: TokenAmount[], take: TokenPayment[]): Promise; + /** Signs `data` (hex, base64 or text, as `encoding` says) with the wallet's unshielded key. */ + sign(data: string, encoding: 'hex' | 'base64' | 'text'): Promise; + /** Submits a sealed transaction (hex) and waits for it to be finalized; its hash. */ + submit(tx: string): Promise; + /** What a transaction (hex) is, as an approval prompt shows it. */ + readTransaction(tx: string, stage: 'unsealed' | 'sealed'): Promise; + /** Reverts what was balanced or built but never submitted, then stops the wallet. */ + close(): Promise; +} + +/** The session over a connector opened in this process; closing it stops the connector. */ +export function sessionOver( + network: NetworkName, + opened: OpenedConnector, + readTransaction: (tx: string, stage: 'unsealed' | 'sealed') => TransactionDetail[], +): WalletSession { + const { connector } = opened; + let requestId = 0; + let closed = false; + const call = async (method: string, params: Record): Promise => { + if (closed) throw new Error('The wallet session is closed'); + const handler = handlerOf(connector, method); + return handler(params, { notify: () => {}, connectionId: SESSION_CONNECTION, requestId: ++requestId, metadata: {} }); + }; + + return { + network, + async addresses() { + const { unshieldedAddress } = (await call('getUnshieldedAddress', {})) as { unshieldedAddress: string }; + const shielded = (await call('getShieldedAddresses', {})) as { shieldedAddress: string; shieldedCoinPublicKey: string; shieldedEncryptionPublicKey: string }; + const { dustAddress } = (await call('getDustAddress', {})) as { dustAddress: string }; + return { + unshielded: unshieldedAddress, + shielded: shielded.shieldedAddress, + shieldedCoinPublicKey: shielded.shieldedCoinPublicKey, + shieldedEncryptionPublicKey: shielded.shieldedEncryptionPublicKey, + dust: dustAddress, + }; + }, + async balances() { + const unshielded = (await call('getUnshieldedBalances', {})) as Record; + const shielded = (await call('getShieldedBalances', {})) as Record; + const { balance } = (await call('getDustBalance', {})) as { balance: bigint }; + return { unshielded: { ...unshielded }, shielded: { ...shielded }, dust: balance }; + }, + async balanceTransaction(tx) { + return ((await call('balanceUnsealedTransaction', { tx })) as { tx: string }).tx; + }, + async swap(give, take) { + const result = await call('makeIntent', { + desiredInputs: give.map(({ kind, type, value }) => ({ kind, type, value })), + desiredOutputs: take.map(({ kind, type, value, recipient }) => ({ kind, type, value, recipient })), + options: { payFees: true }, + }); + return (result as { tx: string }).tx; + }, + async sign(data, encoding) { + return (await call('signData', { data, options: { encoding, keyType: 'unshielded' } })) as SignedData; + }, + async submit(tx) { + return ((await call('submitTransaction', { tx })) as { txHash: string }).txHash; + }, + async readTransaction(tx, stage) { + if (closed) throw new Error('The wallet session is closed'); + return readTransaction(tx, stage); + }, + async close() { + if (closed) return; + closed = true; + await connector.revertPendingTxs(SESSION_CONNECTION).catch(() => { /* best-effort: the wallet is stopping */ }); + await opened.stop(); + }, + }; +} + +function handlerOf(connector: DAppConnector, method: string) { + const handler = connector.handlers[method]; + if (handler === undefined) throw new Error(`The wallet's connector has no ${method}`); + return handler; +} + +export interface OpenWalletSessionOptions { + /** The wallet's seed: 64 bytes from a mnemonic, or 32 raw. */ + seed: Buffer; + network: NetworkName; + /** The network's endpoints; when absent, as a command without endpoint flags resolves them (the saved config, then the defaults). */ + networkConfig?: NetworkConfig; + /** Whether to sync the shielded wallet; off where the network has no shielded faucet, unless forced. */ + forceShielded?: boolean; + /** How long to wait for the wallet's Dust once synced, in milliseconds; the connector's default when absent. */ + dustWaitMs?: number; + /** Cancels the open: what was started is stopped. */ + signal?: AbortSignal; + /** What the open is doing now, for a progress line. */ + onMessage?: (message: string) => void; +} + +/** + * Opens a seed's wallet on a network: synced, its Dust ready. The host must + * have installed its engine loader, settings and state root first, as the CLI + * does at start. + */ +export async function openWalletSession(options: OpenWalletSessionOptions): Promise { + const { seed, network, signal } = options; + throwIfCancelled(signal); + const networkConfig = options.networkConfig + ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } } }).config; + const engine = await engineFor(network); + const opened = await engine.wallet.openConnector({ + seed, + network, + networkConfig, + address: engine.keys.unshieldedAddress(seed, network), + syncMode: shieldedSyncEnabled(network, options.forceShielded) ? 'full' : 'lite', + dustWaitMs: options.dustWaitMs, + signal, + onMessage: options.onMessage ?? (() => {}), + }); + return sessionOver(network, opened, (tx, stage) => engine.ledger.readTransaction(tx, stage)); +} diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index 172eb135..f047ecc7 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -8,6 +8,7 @@ import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; import { blockLimitsOf } from './ledger-parameters.ts'; import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; +import { inspectTxHex } from './tx-inspect.ts'; import { rcWallet } from './wallet.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; @@ -28,6 +29,7 @@ export const rcEngine: Engine = { ledger: { blockLimits: blockLimitsOf, nightTokenId: () => ledger.unshieldedToken().raw, + readTransaction: inspectTxHex, }, contracts: { rawState: rawContractState, diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index 58e3c28a..d13dcce7 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -18,6 +18,7 @@ import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { decodeShieldedAddress } from './addresses.ts'; import { buildFacade, hasDustAvailable, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; @@ -162,6 +163,8 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv const openConnector: EngineWallet['openConnector'] = async (options): Promise => { const { seed, network, networkConfig, address, syncMode, signal, onMessage } = options; + // On a ledger-8 chain the SDK's sync would retry forever. + await assertLedgerSupported(network, networkConfig, undefined, signal); // A failure before the connector is handed back stops what was started, so // the facade doesn't keep syncing. let bundle: Awaited> | undefined; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 3977423a..700d79a3 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -42,7 +42,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], diff --git a/src/__tests__/dapp-connector.test.ts b/src/__tests__/dapp-connector.test.ts index bf3c5897..1718b45a 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/src/__tests__/dapp-connector.test.ts @@ -11,19 +11,18 @@ import { Effect } from 'effect'; // Stub SDK address encoding — MidnightBech32m.encode returns a mock import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; +import { HISTORY, TEST_NETWORK_CONFIG, WALLET_DUST, WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, createConnector, finalizedTx, mockState } from './helpers/connector-stub.ts'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; import { PartlySignedTransactionError } from '@kuiralabs/midnight-engine-rc/sign-recipe'; import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { Intent, UnshieldedOffer, verifySignature } from '@midnightntwrk/ledger-v9'; -import type { FacadeBundle } from '@kuiralabs/midnight-engine-rc/facade'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { RpcHandlerContext } from '../lib/ws-rpc.ts'; import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses, deriveShieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; @@ -33,119 +32,16 @@ import { AGENT_SK, NIGHT, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, sealedBytes, spend, unsealedBytes, } from './helpers/ledger-tx.ts'; -/** The wallet's own addresses, as SDK address objects in its state. */ -const WALLET_SHIELDED = deriveShieldedAddress(Buffer.from('00'.repeat(31) + '07', 'hex')); -const WALLET_UNSHIELDED = new UnshieldedAddress(Buffer.alloc(32, 7)); -const WALLET_DUST = new DustAddress(7n); /** Real undeployed addresses for a fixed seed, so outputs decode as they would from a dApp. */ const RECIPIENT_SEED = Buffer.from('00'.repeat(31) + '42', 'hex'); const UNSHIELDED_RECIPIENT = deriveUnshieldedAddress(RECIPIENT_SEED, 'undeployed'); const SHIELDED_RECIPIENT = deriveAllShieldedAddresses(RECIPIENT_SEED).undeployed; -/** A finalized transaction handle as the SDK returns it: it serializes to these bytes. */ -const finalizedTx = (...bytes: number[]) => ({ serialize: () => new Uint8Array(bytes) }); /** Mock handler context with no-op notify */ const ctx = (connectionId = 'conn_test'): RpcHandlerContext => ({ notify: vi.fn(), connectionId, requestId: 1, metadata: {} }); -// ── Helpers ────────────────────────────────────────────────────────── - -const TEST_NETWORK_CONFIG: NetworkConfig = { - indexer: 'http://localhost:8088/api/v4/graphql', - indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', - node: 'ws://localhost:9944', - proofServer: 'http://localhost:6300', - networkId: 'Undeployed', -}; - -/** Create a minimal mock FacadeState. */ -function mockState(overrides?: { - unshieldedBalances?: Record; - shieldedBalances?: Record; - dustBalance?: bigint; - protocolVersion?: { shielded: bigint; unshielded: bigint; dust: bigint }; - isSynced?: boolean; -}) { - return { - isSynced: overrides?.isSynced ?? true, - // Each wallet's protocol version, as FacadeState reports it: on ledger 9 unless a test says otherwise. - protocolVersion: overrides?.protocolVersion ?? { shielded: FORK_SCHEDULE.v9, unshielded: FORK_SCHEDULE.v9, dust: FORK_SCHEDULE.v9 }, - unshielded: { - balances: overrides?.unshieldedBalances ?? { '0000000000000000000000000000000000000000000000000000000000000000': 5000000n }, - address: WALLET_UNSHIELDED, - progress: { appliedId: 1n, highestTransactionId: 1n }, - }, - shielded: { - balances: overrides?.shieldedBalances ?? {}, - address: WALLET_SHIELDED, - }, - dust: { - balance: (_time: Date) => overrides?.dustBalance ?? 1000n, - availableCoins: [], - address: WALLET_DUST, - }, - }; -} - -/** Wallet history as the SDK records it: one finalized, one rejected, one pending. */ -const HISTORY = [ - { hash: 'tx-hash-001', identifiers: [], status: 'SUCCESS', lifecycle: { status: 'finalized', finalizedBlock: { hash: 'b1', height: 1, timestamp: new Date(0) } } }, - { hash: 'tx-hash-002', identifiers: [], lifecycle: { status: 'rejected', rejectedAt: new Date(0) } }, - { hash: 'tx-hash-003', identifiers: [], lifecycle: { status: 'pending', submittedAt: new Date(0) } }, -]; - -/** Create a minimal FacadeBundle stub. */ -function createBundleStub(overrides?: { - stateFn?: () => rx.Observable; - transferTransaction?: () => Promise; - signRecipe?: () => Promise; - finalizeRecipe?: () => Promise; - submitTransaction?: () => Promise; - balanceUnboundTransaction?: () => Promise; - balanceFinalizedTransaction?: () => Promise; - initSwap?: () => Promise; - getAllFromTxHistory?: () => Promise; - estimateTransactionFee?: (...args: any[]) => Promise; -}): FacadeBundle { - const defaultStateFn = () => rx.of(mockState()); - - return { - facade: { - state: overrides?.stateFn ?? defaultStateFn, - start: vi.fn().mockResolvedValue(undefined), - stop: vi.fn().mockResolvedValue(undefined), - transferTransaction: overrides?.transferTransaction ?? vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }), - signRecipe: overrides?.signRecipe ?? vi.fn().mockResolvedValue({ type: 'SIGNED' }), - finalizeRecipe: overrides?.finalizeRecipe ?? vi.fn().mockResolvedValue(finalizedTx(0xab, 0xcd)), - submitTransaction: overrides?.submitTransaction ?? vi.fn().mockResolvedValue('mock-tx-hash'), - balanceUnboundTransaction: overrides?.balanceUnboundTransaction ?? vi.fn().mockResolvedValue({ type: 'UNBOUND' }), - balanceFinalizedTransaction: overrides?.balanceFinalizedTransaction ?? vi.fn().mockResolvedValue({ type: 'FINALIZED' }), - initSwap: overrides?.initSwap ?? vi.fn().mockResolvedValue({ type: 'SWAP' }), - registerNightUtxosForDustGeneration: vi.fn(), - adoptTransaction: vi.fn((bytes: Uint8Array, stage: string) => ({ stage, hex: Buffer.from(bytes).toString('hex') })), - estimateTransactionFee: overrides?.estimateTransactionFee ?? vi.fn().mockResolvedValue(1_000n), - getAllFromTxHistory: overrides?.getAllFromTxHistory ?? vi.fn().mockResolvedValue(HISTORY), - }, - keystore: { - signDataAsync: vi.fn().mockResolvedValue({ tag: 'schnorr', value: 'abcd1234signature' }), - getPublicKey: vi.fn().mockReturnValue({ tag: 'schnorr', value: '5678efghpubkey' }), - }, - } as unknown as FacadeBundle; -} - -function createConnector(overrides?: { - bundleOverrides?: Parameters[0]; - networkConfig?: NetworkConfig; - approvalOptions?: ApprovalOptions; -}): DAppConnector { - return createDAppConnector({ - bundle: createBundleStub(overrides?.bundleOverrides), - networkConfig: overrides?.networkConfig ?? TEST_NETWORK_CONFIG, - approvalOptions: overrides?.approvalOptions ?? { approveAll: true }, - }); -} - // ── Tests ──────────────────────────────────────────────────────────── /** A real unsealed ledger-9 dApp transaction (the agent pays from its own signed input), as hex. */ diff --git a/src/__tests__/helpers/connector-stub.ts b/src/__tests__/helpers/connector-stub.ts new file mode 100644 index 00000000..cd5f43e5 --- /dev/null +++ b/src/__tests__/helpers/connector-stub.ts @@ -0,0 +1,117 @@ +// The wallet SDK's facade, stubbed at the SDK boundary, and the DApp connector +// over it: shared by the connector's tests and the wallet session's. + +import { vi } from 'vitest'; +import * as rx from 'rxjs'; +import { createDAppConnector, type DAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; +import type { FacadeBundle } from '@kuiralabs/midnight-engine-rc/facade'; +import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; +import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { DustAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; + +/** The wallet's own addresses, as SDK address objects in its state. */ +export const WALLET_SHIELDED = deriveShieldedAddress(Buffer.from('00'.repeat(31) + '07', 'hex')); +export const WALLET_UNSHIELDED = new UnshieldedAddress(Buffer.alloc(32, 7)); +export const WALLET_DUST = new DustAddress(7n); + +/** A finalized transaction handle as the SDK returns it: it serializes to these bytes. */ +export const finalizedTx = (...bytes: number[]) => ({ serialize: () => new Uint8Array(bytes) }); + + + +export const TEST_NETWORK_CONFIG: NetworkConfig = { + indexer: 'http://localhost:8088/api/v4/graphql', + indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', + node: 'ws://localhost:9944', + proofServer: 'http://localhost:6300', + networkId: 'Undeployed', +}; + +/** Create a minimal mock FacadeState. */ +export function mockState(overrides?: { + unshieldedBalances?: Record; + shieldedBalances?: Record; + dustBalance?: bigint; + protocolVersion?: { shielded: bigint; unshielded: bigint; dust: bigint }; + isSynced?: boolean; +}) { + return { + isSynced: overrides?.isSynced ?? true, + // Each wallet's protocol version, as FacadeState reports it: on ledger 9 unless a test says otherwise. + protocolVersion: overrides?.protocolVersion ?? { shielded: FORK_SCHEDULE.v9, unshielded: FORK_SCHEDULE.v9, dust: FORK_SCHEDULE.v9 }, + unshielded: { + balances: overrides?.unshieldedBalances ?? { '0000000000000000000000000000000000000000000000000000000000000000': 5000000n }, + address: WALLET_UNSHIELDED, + progress: { appliedId: 1n, highestTransactionId: 1n }, + }, + shielded: { + balances: overrides?.shieldedBalances ?? {}, + address: WALLET_SHIELDED, + }, + dust: { + balance: (_time: Date) => overrides?.dustBalance ?? 1000n, + availableCoins: [], + address: WALLET_DUST, + }, + }; +} + +/** Wallet history as the SDK records it: one finalized, one rejected, one pending. */ +export const HISTORY = [ + { hash: 'tx-hash-001', identifiers: [], status: 'SUCCESS', lifecycle: { status: 'finalized', finalizedBlock: { hash: 'b1', height: 1, timestamp: new Date(0) } } }, + { hash: 'tx-hash-002', identifiers: [], lifecycle: { status: 'rejected', rejectedAt: new Date(0) } }, + { hash: 'tx-hash-003', identifiers: [], lifecycle: { status: 'pending', submittedAt: new Date(0) } }, +]; + +/** Create a minimal FacadeBundle stub. */ +export function createBundleStub(overrides?: { + stateFn?: () => rx.Observable; + transferTransaction?: () => Promise; + signRecipe?: () => Promise; + finalizeRecipe?: () => Promise; + submitTransaction?: () => Promise; + balanceUnboundTransaction?: () => Promise; + balanceFinalizedTransaction?: () => Promise; + initSwap?: () => Promise; + getAllFromTxHistory?: () => Promise; + estimateTransactionFee?: (...args: any[]) => Promise; +}): FacadeBundle { + const defaultStateFn = () => rx.of(mockState()); + + return { + facade: { + state: overrides?.stateFn ?? defaultStateFn, + start: vi.fn().mockResolvedValue(undefined), + stop: vi.fn().mockResolvedValue(undefined), + transferTransaction: overrides?.transferTransaction ?? vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }), + signRecipe: overrides?.signRecipe ?? vi.fn().mockResolvedValue({ type: 'SIGNED' }), + finalizeRecipe: overrides?.finalizeRecipe ?? vi.fn().mockResolvedValue(finalizedTx(0xab, 0xcd)), + submitTransaction: overrides?.submitTransaction ?? vi.fn().mockResolvedValue('mock-tx-hash'), + balanceUnboundTransaction: overrides?.balanceUnboundTransaction ?? vi.fn().mockResolvedValue({ type: 'UNBOUND' }), + balanceFinalizedTransaction: overrides?.balanceFinalizedTransaction ?? vi.fn().mockResolvedValue({ type: 'FINALIZED' }), + initSwap: overrides?.initSwap ?? vi.fn().mockResolvedValue({ type: 'SWAP' }), + registerNightUtxosForDustGeneration: vi.fn(), + adoptTransaction: vi.fn((bytes: Uint8Array, stage: string) => ({ stage, hex: Buffer.from(bytes).toString('hex') })), + estimateTransactionFee: overrides?.estimateTransactionFee ?? vi.fn().mockResolvedValue(1_000n), + getAllFromTxHistory: overrides?.getAllFromTxHistory ?? vi.fn().mockResolvedValue(HISTORY), + }, + keystore: { + signDataAsync: vi.fn().mockResolvedValue({ tag: 'schnorr', value: 'abcd1234signature' }), + getPublicKey: vi.fn().mockReturnValue({ tag: 'schnorr', value: '5678efghpubkey' }), + }, + } as unknown as FacadeBundle; +} + +export function createConnector(overrides?: { + bundleOverrides?: Parameters[0]; + networkConfig?: NetworkConfig; + approvalOptions?: ApprovalOptions; +}): DAppConnector { + return createDAppConnector({ + bundle: createBundleStub(overrides?.bundleOverrides), + networkConfig: overrides?.networkConfig ?? TEST_NETWORK_CONFIG, + approvalOptions: overrides?.approvalOptions ?? { approveAll: true }, + }); +} diff --git a/src/__tests__/shielded-policy.test.ts b/src/__tests__/shielded-policy.test.ts index 0be32daa..25eaeaa4 100644 --- a/src/__tests__/shielded-policy.test.ts +++ b/src/__tests__/shielded-policy.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { networkHasShielded, shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; +import { networkHasShielded, shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; describe('shielded-policy', () => { it('marks localnet (undeployed) as having shielded, hosted testnets as not', () => { diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts new file mode 100644 index 00000000..3ab94f9e --- /dev/null +++ b/src/__tests__/wallet-session.test.ts @@ -0,0 +1,115 @@ +// The wallet session over the rc engine's DApp connector, its facade stubbed +// at the SDK boundary: each operation answers in the session's own types, and +// closing reverts what was built but never submitted. + +import { describe, it, expect, vi, beforeAll } from 'vitest'; +import * as rx from 'rxjs'; +import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; +import { sessionOver, type WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; +import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { TEST_NETWORK_CONFIG, WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, mockState } from './helpers/connector-stub.ts'; +import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; +import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; + +const NIGHT_RAW = '0000000000000000000000000000000000000000000000000000000000000000'; +const OTHER_TOKEN = '02' + '00'.repeat(31); +const RECIPIENT = deriveUnshieldedAddress(Buffer.from('00'.repeat(31) + '42', 'hex'), 'undeployed'); + +/** A real unsealed ledger-9 dApp transaction, as hex. */ +let AGENT_TX: string; +beforeAll(async () => { + AGENT_TX = Buffer.from(await unsealedBytes(agentPaysMerchant())).toString('hex'); +}); + +function openSession(options: { bundleOverrides?: Parameters[0]; readTransaction?: (tx: string, stage: 'unsealed' | 'sealed') => TransactionDetail[] } = {}) { + const bundle = createBundleStub({ + stateFn: () => rx.of(mockState({ unshieldedBalances: { [NIGHT_RAW]: 7_000_000n }, shieldedBalances: { [NIGHT_RAW]: 3n }, dustBalance: 42n })), + ...options.bundleOverrides, + }); + const revert = vi.fn().mockResolvedValue(undefined); + (bundle.facade as unknown as { revert: typeof revert }).revert = revert; + const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + const stop = vi.fn(async () => { connector.dispose(); }); + const session: WalletSession = sessionOver('undeployed', { connector, stop }, options.readTransaction ?? (() => [])); + return { session, bundle, revert, stop }; +} + +describe('wallet session', () => { + it('names the wallet\'s addresses on its network', async () => { + const { session } = openSession(); + const addresses = await session.addresses(); + expect(MidnightBech32m.parse(addresses.unshielded).decode(UnshieldedAddress, 'undeployed').equals(WALLET_UNSHIELDED.hexString)).toBe(true); + expect(MidnightBech32m.parse(addresses.shielded).decode(ShieldedAddress, 'undeployed').coinPublicKeyString()).toBe(WALLET_SHIELDED.coinPublicKeyString()); + expect(addresses.shieldedCoinPublicKey).toBe(WALLET_SHIELDED.coinPublicKeyString()); + expect(addresses.shieldedEncryptionPublicKey).toBe(WALLET_SHIELDED.encryptionPublicKeyString()); + expect(addresses.dust.startsWith('mn_dust_undeployed1')).toBe(true); + await session.close(); + }); + + it('reads what the wallet holds', async () => { + const { session } = openSession(); + expect(await session.balances()).toEqual({ unshielded: { [NIGHT_RAW]: 7_000_000n }, shielded: { [NIGHT_RAW]: 3n }, dust: 42n }); + await session.close(); + }); + + it('balances a transaction and submits it, as hex', async () => { + const submitTransaction = vi.fn().mockResolvedValue('the-hash'); + const { session, revert } = openSession({ bundleOverrides: { submitTransaction } }); + const balanced = await session.balanceTransaction(AGENT_TX); + expect(balanced).toBe('abcd'); + expect(await session.submit(balanced)).toBe('the-hash'); + expect(submitTransaction).toHaveBeenCalledOnce(); + await session.close(); + // Submitted, so nothing is left to revert. + expect(revert).not.toHaveBeenCalled(); + }); + + it('builds a swap from what it gives and what it takes', async () => { + const initSwap = vi.fn().mockResolvedValue({ type: 'SWAP' }); + const { session } = openSession({ bundleOverrides: { initSwap } }); + const tx = await session.swap( + [{ kind: 'unshielded', type: NIGHT_RAW, value: 5n }], + [{ kind: 'unshielded', type: OTHER_TOKEN, value: 9n, recipient: RECIPIENT }], + ); + expect(tx).toBe('abcd'); + const [inputs, outputs, options] = initSwap.mock.calls[0]!; + expect(inputs).toEqual({ unshielded: { [NIGHT_RAW]: 5n } }); + expect(outputs).toHaveLength(1); + expect(outputs[0].type).toBe('unshielded'); + expect(outputs[0].outputs[0]).toMatchObject({ type: OTHER_TOKEN, amount: 9n }); + expect(options.payFees).toBe(true); + await session.close(); + }); + + it('signs data with the wallet\'s unshielded key', async () => { + const { session } = openSession(); + expect(await session.sign('68656c6c6f', 'hex')).toEqual({ data: '68656c6c6f', signature: 'abcd1234signature', verifyingKey: '5678efghpubkey', scheme: 'schnorr_bip340' }); + await session.close(); + }); + + it('reads a transaction through the engine', async () => { + const readTransaction = vi.fn(() => [{ label: 'Type', value: 'Transfer' }]); + const { session } = openSession({ readTransaction }); + expect(await session.readTransaction('beef', 'sealed')).toEqual([{ label: 'Type', value: 'Transfer' }]); + expect(readTransaction).toHaveBeenCalledWith('beef', 'sealed'); + await session.close(); + }); + + it('reverts on close what it built but never submitted, then stops the wallet', async () => { + const { session, revert, stop } = openSession(); + await session.balanceTransaction(AGENT_TX); + await session.close(); + expect(revert).toHaveBeenCalledOnce(); + expect(stop).toHaveBeenCalledOnce(); + }); + + it('refuses calls once closed, and closes once', async () => { + const { session, stop } = openSession(); + await session.close(); + await session.close(); + expect(stop).toHaveBeenCalledOnce(); + await expect(session.balances()).rejects.toThrow('The wallet session is closed'); + await expect(session.readTransaction('beef', 'sealed')).rejects.toThrow('The wallet session is closed'); + }); +}); diff --git a/src/commands/balance.ts b/src/commands/balance.ts index dffcea49..9a6a6aa2 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -7,7 +7,7 @@ import { saveShieldedAddress, findWalletByAddress } from '../lib/wallet-config.t import { resolveSeedSource } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; -import { shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; +import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { isNativeToken } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; diff --git a/src/commands/serve.ts b/src/commands/serve.ts index bab40936..a71f3b39 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -11,7 +11,7 @@ import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/conn import type { PhaseTiming } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { shieldedSyncEnabled } from '../lib/shielded-policy.ts'; +import { shieldedSyncEnabled } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { header, keyValue, divider, formatAddress, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; import { parseFeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { describeApprovalPolicy } from '@kuiralabs/midnight-cli-core/lib/approval'; diff --git a/src/lib/grant/fee-wallet.ts b/src/lib/grant/fee-wallet.ts index 646c56c4..a8ec37ca 100644 --- a/src/lib/grant/fee-wallet.ts +++ b/src/lib/grant/fee-wallet.ts @@ -18,18 +18,18 @@ export interface PayingWallet { /** The payer's wallet for `target`, as the account package's fee wallet, keeping the SDK's warnings to the paying call's `sdkWarnings`. Stopping it stops the wallet. */ export async function openPayingWallet(payer: Payer, target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { feeWalletOver } = await import('@kuiralabs/midnight-account-chain/connector'); - const connection = await payer.connect(target, wallet, progress, sdkWarnings, signal); + const session = await payer.connect(target, wallet, progress, sdkWarnings, signal); try { const feeWallet = await feeWalletOver({ - getShieldedAddresses: async () => (await connection.call('getShieldedAddresses', {})) as { shieldedCoinPublicKey: string; shieldedEncryptionPublicKey: string }, - balanceUnsealedTransaction: async (tx) => (await connection.call('balanceUnsealedTransaction', { tx })) as { tx: string }, - submitTransaction: (tx) => connection.call('submitTransaction', { tx }), + getShieldedAddresses: () => session.addresses(), + balanceUnsealedTransaction: async (tx) => ({ tx: await session.balanceTransaction(tx) }), + submitTransaction: (tx) => session.submit(tx), }); - const shieldedNight = async (): Promise => BigInt(((await connection.call('getShieldedBalances', {})) as Record)[NATIVE_TOKEN_TYPE] ?? 0n); + const shieldedNight = async (): Promise => (await session.balances()).shielded[NATIVE_TOKEN_TYPE] ?? 0n; progress.stop('Wallet ready'); - return { feeWallet, shieldedNight, stop: connection.stop }; + return { feeWallet, shieldedNight, stop: () => session.close() }; } catch (err) { - await connection.stop(); + await session.close(); throw err; } } diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 9669c591..73ca7e13 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -6,13 +6,12 @@ import { Socket } from 'node:net'; import { loadWalletConfig, resolveWalletPath, unlockWallet } from './wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { shieldedSyncEnabled } from './shielded-policy.ts'; +import { shieldedSyncEnabled } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** A running mn serve, and how to stop it. */ @@ -232,8 +231,6 @@ export async function openConnector(options: ServeManagerOptions): Promise { +async function connectWallet({ network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { openConnector } = await import('./serve-manager.ts'); + const engine = await engineFor(network); const opened = await openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, signal }); - let requestId = 0; - const call = (method: PayingMethod, params: Record): Promise => { - const handler = opened.connector.handlers[method]; - if (handler === undefined) throw new Error(`The wallet's connector has no ${method}`); - return handler(params, { notify: () => {}, connectionId: OWN_CONNECTION, requestId: ++requestId, metadata: {} }); - }; - const stop = async (): Promise => { - await opened.connector.revertPendingTxs(OWN_CONNECTION).catch(() => { /* best-effort: the connector is stopping */ }); - await opened.stop(); - }; - return { call, stop }; + return sessionOver(network, opened, (tx, stage) => engine.ledger.readTransaction(tx, stage)); } /** The payer whose served wallet is the mn serve on `port`. */ diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 07de95c4..02bd984a 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -7,7 +7,7 @@ import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { loadWalletConfig, resolveWalletPath, type WalletConfig } from './wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { engineFor, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { shieldedSyncEnabled, shieldedDisabledReason } from './shielded-policy.ts'; +import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; From 34ce3589afaf0ff05b857f912d97a1a6122b8f7a Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 22:15:17 -0800 Subject: [PATCH 38/88] The beta engine and stagenet: the network picks the set (EG) stagenet joins the network table (StageNet, mn_addr_stagenet1, proof server localhost:6300) on the beta SDK set, which a new package, @kuiralabs/midnight-engine-beta, carries: the spike's port onto the main line. The beta SDK starts wallets from secret keys and takes them on every call that spends, has no fork schedule or adoptTransaction, composes one ledger-9 Dust wallet (mn's fee-coin fix kept) and gives contract scripts plain provider objects. Its connector still refuses transaction work before the wallet's first state, as the rc one does. Each engine resolves one copy of its SDK in the workspace. Around it: - every new wallet gets a stagenet address; an existing one gets it derived and saved when read (a sealed wallet, when unlocked); - stagenet skips the shielded sync, and reads Dust in WASM with a notice until a sidecar replays ledger 9; - config set sdk-set [--network] runs a network on the other set, and its caches go to a folder of that set's own; - work every set does alike loads the set of the call's network, and a process that loaded one set refuses the other (OTHER_SDK_SET); the MCP server says to start a server for that network; - grant refuses networks on the beta set, saying why; - help, the manuals, the skills and the MCP enums name stagenet, from the network table. --- docs/SKILL.md | 1 + package-lock.json | 468 +++++++- package.json | 6 +- .../src/commands/config.definition.ts | 10 +- packages/cli-core/src/commands/config.ts | 4 +- .../cli-core/src/commands/core.guidance.ts | 4 + packages/cli-core/src/lib/cache-indexer.ts | 4 +- packages/cli-core/src/lib/call-context.ts | 5 + packages/cli-core/src/lib/cli-config.ts | 37 +- .../cli-core/src/lib/command-definition.ts | 3 +- packages/cli-core/src/lib/engine.ts | 37 +- packages/cli-core/src/lib/exit-codes.ts | 5 + packages/cli-core/src/lib/network-id.ts | 6 +- packages/cli-core/src/lib/network.ts | 33 +- .../cli-core/src/lib/reader-cache-files.ts | 10 +- packages/cli-core/src/lib/shielded-policy.ts | 4 +- packages/cli-core/src/lib/wallet-cache.ts | 18 +- packages/engine-beta/package.json | 66 ++ packages/engine-beta/src/addresses.ts | 22 + packages/engine-beta/src/airdrop.ts | 25 + .../engine-beta/src/contract-providers.ts | 26 + packages/engine-beta/src/contract-scripts.ts | 350 ++++++ packages/engine-beta/src/dapp-connector.ts | 1019 +++++++++++++++++ packages/engine-beta/src/derivation.ts | 41 + packages/engine-beta/src/derive-address.ts | 101 ++ packages/engine-beta/src/dust-collapse.ts | 107 ++ packages/engine-beta/src/dust-direct-cache.ts | 183 +++ packages/engine-beta/src/dust-direct.ts | 255 +++++ packages/engine-beta/src/dust-export.ts | 108 ++ packages/engine-beta/src/dust-register.ts | 53 + packages/engine-beta/src/dust-sync-native.ts | 256 +++++ packages/engine-beta/src/dust-wallet.ts | 123 ++ packages/engine-beta/src/facade.ts | 662 +++++++++++ packages/engine-beta/src/fee-only-check.ts | 124 ++ packages/engine-beta/src/index.ts | 68 ++ packages/engine-beta/src/ledger-parameters.ts | 29 + packages/engine-beta/src/raw-state.ts | 34 + .../engine-beta/src/shielded-direct-cache.ts | 186 +++ packages/engine-beta/src/shielded-direct.ts | 197 ++++ packages/engine-beta/src/sign-recipe.ts | 108 ++ packages/engine-beta/src/transfer.ts | 520 +++++++++ packages/engine-beta/src/tx-inspect.ts | 105 ++ .../engine-beta/src/wallet-data-repository.ts | 743 ++++++++++++ packages/engine-beta/src/wallet.ts | 303 +++++ packages/engine-beta/tsconfig.build.json | 28 + packages/engine-rc/src/dust-sync-native.ts | 4 +- scripts/check-layering.mjs | 1 + scripts/check-process-safety.mjs | 5 + src/__tests__/cli-config.test.ts | 53 + src/__tests__/derive-address.test.ts | 2 +- src/__tests__/engine-beta.test.ts | 110 ++ src/__tests__/engine.test.ts | 27 +- src/__tests__/grant-prepare.test.ts | 7 + src/__tests__/help.test.ts | 2 +- src/__tests__/mcp-server-advice.test.ts | 23 + .../mcp-server-unknown-parameter.test.ts | 4 +- src/__tests__/network.test.ts | 5 +- src/__tests__/state-root.test.ts | 5 +- src/__tests__/wallet-config.test.ts | 35 +- src/commands/airdrop.ts | 10 +- src/commands/connect.guidance.ts | 2 +- src/commands/generate.definition.ts | 5 +- src/commands/info.definition.ts | 5 +- src/commands/info.ts | 4 +- src/commands/manual.ts | 6 +- src/commands/test.ts | 5 +- src/commands/wallet.definition.ts | 7 +- src/commands/wallet.guidance.ts | 5 +- src/commands/wallet.ts | 3 +- src/lib/agent-manual.ts | 6 +- src/lib/grant/account.ts | 13 +- src/lib/installed-commands.ts | 3 +- src/lib/installed-engines.ts | 2 + src/lib/mcp/server-advice.ts | 14 + src/lib/mcp/skills.ts | 1 + src/lib/serve-manager.ts | 4 +- src/lib/test/discovery.ts | 3 +- src/lib/test/types.ts | 3 +- src/lib/transfer-request.ts | 8 +- src/lib/wallet-config.ts | 57 +- src/mcp-server.ts | 3 +- tsconfig.json | 2 +- 82 files changed, 6862 insertions(+), 89 deletions(-) create mode 100644 packages/engine-beta/package.json create mode 100644 packages/engine-beta/src/addresses.ts create mode 100644 packages/engine-beta/src/airdrop.ts create mode 100644 packages/engine-beta/src/contract-providers.ts create mode 100644 packages/engine-beta/src/contract-scripts.ts create mode 100644 packages/engine-beta/src/dapp-connector.ts create mode 100644 packages/engine-beta/src/derivation.ts create mode 100644 packages/engine-beta/src/derive-address.ts create mode 100644 packages/engine-beta/src/dust-collapse.ts create mode 100644 packages/engine-beta/src/dust-direct-cache.ts create mode 100644 packages/engine-beta/src/dust-direct.ts create mode 100644 packages/engine-beta/src/dust-export.ts create mode 100644 packages/engine-beta/src/dust-register.ts create mode 100644 packages/engine-beta/src/dust-sync-native.ts create mode 100644 packages/engine-beta/src/dust-wallet.ts create mode 100644 packages/engine-beta/src/facade.ts create mode 100644 packages/engine-beta/src/fee-only-check.ts create mode 100644 packages/engine-beta/src/index.ts create mode 100644 packages/engine-beta/src/ledger-parameters.ts create mode 100644 packages/engine-beta/src/raw-state.ts create mode 100644 packages/engine-beta/src/shielded-direct-cache.ts create mode 100644 packages/engine-beta/src/shielded-direct.ts create mode 100644 packages/engine-beta/src/sign-recipe.ts create mode 100644 packages/engine-beta/src/transfer.ts create mode 100644 packages/engine-beta/src/tx-inspect.ts create mode 100644 packages/engine-beta/src/wallet-data-repository.ts create mode 100644 packages/engine-beta/src/wallet.ts create mode 100644 packages/engine-beta/tsconfig.build.json create mode 100644 src/__tests__/engine-beta.test.ts create mode 100644 src/__tests__/mcp-server-advice.test.ts create mode 100644 src/lib/mcp/server-advice.ts diff --git a/docs/SKILL.md b/docs/SKILL.md index 843dfa80..69b2b0d2 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -29,6 +29,7 @@ Most commands are MCP tools (`tools/list` shows each, and what it takes). These - `undeployed` — local network. Use this for dev iteration. On this build it must be a ledger-9 stack the user runs (`mn localnet up` is refused, see the note at the top). - `preprod` — public testnet (ledger 8 today, so refused by this build). Its indexer and node are served by Blockfrost and need the user's own project id (see "Preprod needs a Blockfrost project id" below). First-time wallet sync processes the full event history and can take significantly longer than subsequent syncs (which restore from cached wallet state). Exact time depends on wallet age, event density, network, and hardware. - `preview` — public preview testnet (ledger 8 today, so refused by this build). Same first-sync trade-off as preprod. + - `stagenet` — Sig Network's testnet, on the beta SDK set (mn loads its beta engine for it). No shielded faucet, so shielded sync is off by default; NIGHT from https://faucet.stagenet.shielded.tools. Its proof server must match its node (`midnightntwrk/proof-server:9.0.0-rc.5_experimental`). Grant is refused there for now. - **Proof server** — local HTTP service that generates ZK proofs for transactions. Default port 6300. Version must match the network's ledger version or writes fail with "Custom error 170". ### mn's secrets are encrypted under one passphrase diff --git a/package-lock.json b/package-lock.json index 1ace5e49..2a4fef89 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,13 +12,15 @@ "packages/connector", "packages/cli-core", "packages/chain", - "packages/engine-rc" + "packages/engine-rc", + "packages/engine-beta" ], "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.0", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.0", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.0", "@modelcontextprotocol/sdk": "^1.27.1", "@scure/bip39": "^2.0.1", @@ -672,6 +674,10 @@ "resolved": "packages/cli-core", "link": true }, + "node_modules/@kuiralabs/midnight-engine-beta": { + "resolved": "packages/engine-beta", + "link": true + }, "node_modules/@kuiralabs/midnight-engine-rc": { "resolved": "packages/engine-rc", "link": true @@ -5739,6 +5745,466 @@ } } }, + "packages/engine-beta": { + "name": "@kuiralabs/midnight-engine-beta", + "version": "0.1.0-rc.0", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@midnight-ntwrk/compact-js": "2.5.5-rc.7", + "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6", + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-dust-wallet": "5.0.0-beta.2", + "@midnightntwrk/wallet-sdk-facade": "5.0.0-beta.2", + "@midnightntwrk/wallet-sdk-hd": "3.1.0-beta.1", + "@midnightntwrk/wallet-sdk-shielded": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "@scure/base": "2.0.0", + "rxjs": "7.8.2", + "ws": "^8.19.0" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@effect/platform": { + "version": "0.96.3", + "resolved": "https://registry.npmjs.org/@effect/platform/-/platform-0.96.3.tgz", + "integrity": "sha512-LzvIj4HYE++TcTv/cVTCI/GRvQTV0ymwRmgjZMzNB5dU4OS05pTN36RKN0npiOm5orLJgw4yjIv1dNZoYGh/vg==", + "license": "MIT", + "dependencies": { + "find-my-way-ts": "^0.1.6", + "msgpackr": "^1.11.10", + "multipasta": "^0.2.7" + }, + "peerDependencies": { + "effect": "^3.21.5" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/compact-js": { + "version": "2.5.5-rc.7", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/compact-js/-/compact-js-2.5.5-rc.7.tgz", + "integrity": "sha512-INcbIxsgK2NGm5J7pCHRsq1kxKQEXKQjFRgU84TsbP6GadqnWFg1hh0eJ/H2SS6AxAQGQjI0iasLodVTviKAIw==", + "license": "Apache-2.0", + "dependencies": { + "@effect/platform": "^0.96.1", + "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", + "@midnight-ntwrk/platform-js": "^3.0.0", + "@midnightntwrk/ledger-v9": "^1.0.0-rc.3", + "@noble/hashes": "^2.2.0", + "effect": "^3.21.4", + "tslib": "^2.8.1" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/compact-runtime": { + "version": "0.18.0-rc.1", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/compact-runtime/-/compact-runtime-0.18.0-rc.1.tgz", + "integrity": "sha512-PXPjyiD8lrdM216eSpRGi1JSRes1fAwMImj1FWRML0BA3s6doOXFbX01A8suY/47xU/NCEKB9RKKU+vhW8Ec4A==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/onchain-runtime-v4": "^4.0.0-rc.3", + "@noble/curves": "^2.2.0", + "@noble/hashes": "^2.0.1", + "@types/object-inspect": "^1.8.1", + "object-inspect": "^1.12.3" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-contracts": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-contracts/-/midnight-js-contracts-5.0.0-beta.6.tgz", + "integrity": "sha512-z8feJLi/vDhPluYMH/0lrVQ003zMyT4PLB20/aCXVSLQy5sxvNCOiahKIU4+dasUM9vXtlVinDGYB6uFHVKbwg==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6", + "effect": "^3.20.0" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-http-client-proof-provider": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-http-client-proof-provider/-/midnight-js-http-client-proof-provider-5.0.0-beta.6.tgz", + "integrity": "sha512-5PHS28YspoNw6D1C4QluolcsaSvsbcXsCv0CKKTesrxA7iwgT/5ZXFbFbengTLsgr3Qgd2IZdv2Ed09gApxBJA==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6", + "cross-fetch": "^4.1.0", + "fetch-retry": "^6.0.0" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-indexer-public-data-provider": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-indexer-public-data-provider/-/midnight-js-indexer-public-data-provider-5.0.0-beta.6.tgz", + "integrity": "sha512-4oIyzpiQi2W2NEL9WIhKqhzArFrexETZRN5WyGqnN/OIu9sP3Sy1DDUKqViMxl1xiAJwebzFTpJkSAyAT/l5eQ==", + "license": "Apache-2.0", + "dependencies": { + "@apollo/client": "^4.2.3", + "@graphql-typed-document-node/core": "^3.2.0", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6", + "buffer": "^6.0.3", + "cross-fetch": "^4.1.0", + "graphql": "^17.0.1", + "graphql-ws": "^6.0.8", + "isomorphic-ws": "^5.0.0", + "rxjs": "^7.8.2", + "ws": "^8.20.0" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-level-private-state-provider": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-level-private-state-provider/-/midnight-js-level-private-state-provider-5.0.0-beta.6.tgz", + "integrity": "sha512-86FZwi36MpsWozUdhuoh06tddZSfRup6/bJRWco5fx9F5/ad2p2F0kEc8Shvtl6Lyp+gik3RJVXvdFKqSX91UA==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6", + "@noble/ciphers": "^2.2.0", + "@noble/hashes": "^2.2.0", + "abstract-level": "^3.1.1", + "buffer": "^6.0.3", + "level": "^10.0.0", + "superjson": "^2.2.6" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-network-id": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-network-id/-/midnight-js-network-id-5.0.0-beta.6.tgz", + "integrity": "sha512-XgvvAyHLovjdGLz96nc9K0s3LIYl5fxhXIYHF/X5VxlXHY5NZlLIjptXERcGcAQRTjZWhZbIXcUwZxXDpiSjZw==", + "license": "Apache-2.0", + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-node-zk-config-provider": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-node-zk-config-provider/-/midnight-js-node-zk-config-provider-5.0.0-beta.6.tgz", + "integrity": "sha512-opaiQo2MXRrBLMw8zol3DzqftCa3UhN+DZloZw/izAOTsbuqTX093ESKujuz/qcG/9+IbzUiDe59N1VCJy2GkQ==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-protocol": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-protocol/-/midnight-js-protocol-5.0.0-beta.6.tgz", + "integrity": "sha512-qqT4S7FqclCkwUx5ISVI3xwpE1iiZ2SU/5EjSiWMf9bUdi00RANyGv+ZRKkXEMOj9OigHhu4UXmIieWGAVEhgA==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/compact-js": "2.5.5-rc.7", + "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", + "@midnight-ntwrk/platform-js": "3.0.0", + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-types": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-types/-/midnight-js-types-5.0.0-beta.6.tgz", + "integrity": "sha512-ea8SVd8etHO2fhwNwRre2TN0lKiwUnWoPQudTjWJMZlF19U4jHW7nRWCMPO7qYgKDAsVec7o16PUY3TR7twijA==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "effect": "^3.20.0", + "pino": "^10.3.1", + "rxjs": "^7.8.2" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnight-ntwrk/midnight-js-utils": { + "version": "5.0.0-beta.6", + "resolved": "https://registry.npmjs.org/@midnight-ntwrk/midnight-js-utils/-/midnight-js-utils-5.0.0-beta.6.tgz", + "integrity": "sha512-TFjYhlHg7gATk52juKyMUU8aKGjHc2L+B8S6N2lNW8t+/RcqxoIJDcXLded0Zpgcp0936TxaymFm3bR/Hdysjw==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@noble/hashes": "^2.2.0" + }, + "engines": { + "node": ">=22" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/ledger-v9": { + "version": "1.0.0-rc.3", + "resolved": "https://registry.npmjs.org/@midnightntwrk/ledger-v9/-/ledger-v9-1.0.0-rc.3.tgz", + "integrity": "sha512-i/Cl/d2XQ19gIm5SCruMHr+XiruxIn9Ec3i15DrZ/44Yggzu1u5+dG7QUx7Rw1htkgALXivEt7Kw4NzxPr4pBw==" + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-abstractions": { + "version": "3.0.0-beta.0", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-abstractions/-/wallet-sdk-abstractions-3.0.0-beta.0.tgz", + "integrity": "sha512-9gzVaSd9dk1rymqd6CrqSSNGPoMtIbr24wVSwCfuB3L1y9wcNgzCw9l/RH744XJE+4RyDZODEIWo7WU5LCYvNw==", + "license": "Apache-2.0", + "dependencies": { + "effect": "^3.19.19" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-address-format": { + "version": "4.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-address-format/-/wallet-sdk-address-format-4.0.0-beta.2.tgz", + "integrity": "sha512-yK4jlntQ0Pgks8dKrPx6J7IMdzIznEYZ4yO9/msIJrn2IM4o1d8+MEh07OMFvZ9ui1YNQB272aUv5muopBCrdA==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@scure/base": "^2.0.0", + "@subsquid/scale-codec": "^4.0.1" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-capabilities": { + "version": "4.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-capabilities/-/wallet-sdk-capabilities-4.0.0-beta.2.tgz", + "integrity": "sha512-QoeautcgfOgUMzbU5JAqhVP7n8K8fNdpQgoOwDwIdjJGpP+mH0f2/QtGia373OVTt1olf3cQN+7bLL9B0ihvlg==", + "license": "Apache-2.0", + "dependencies": { + "@midnight-ntwrk/zkir-v2": "^2.1.0", + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-indexer-client": "1.3.0-beta.1", + "@midnightntwrk/wallet-sdk-node-client": "2.0.0-beta.2", + "@midnightntwrk/wallet-sdk-prover-client": "2.0.0-beta.2", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-dust-wallet": { + "version": "5.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-dust-wallet/-/wallet-sdk-dust-wallet-5.0.0-beta.2.tgz", + "integrity": "sha512-ILtpnmrx5mkMbDDAt1Az0qAdev3CtbTSsjk0PHh6sIowiaooQBSJ1GH043unYkpUj++OLlTcS2Dwf1VT2ya0oA==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-indexer-client": "1.3.0-beta.1", + "@midnightntwrk/wallet-sdk-runtime": "1.0.6-beta.0", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-facade": { + "version": "5.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-facade/-/wallet-sdk-facade-5.0.0-beta.2.tgz", + "integrity": "sha512-iDtxlilzBz2oPRJkGaktLS5hUkNXLwAZovYv99XLpoSg/+QYGpX3zWhFW5+OUV3kt9QYFLDSilRKdmtXa+WHJQ==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-dust-wallet": "5.0.0-beta.2", + "@midnightntwrk/wallet-sdk-indexer-client": "1.3.0-beta.1", + "@midnightntwrk/wallet-sdk-shielded": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.0-beta.2", + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-hd": { + "version": "3.1.0-beta.1", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-hd/-/wallet-sdk-hd-3.1.0-beta.1.tgz", + "integrity": "sha512-zQCucKVf7BXmTA6Clf5yHUsNspAiV0q+noEZVvHxd2yQTS6pXBmibUZ0wBWs1KG3V2tCfBllzoil7rS+L82IRQ==", + "license": "Apache-2.0", + "dependencies": { + "@scure/bip32": "^2.0.1", + "@scure/bip39": "^2.0.1" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-indexer-client": { + "version": "1.3.0-beta.1", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-indexer-client/-/wallet-sdk-indexer-client-1.3.0-beta.1.tgz", + "integrity": "sha512-Kn3RT3kpRlyTAmN9xhV98q8k8ZiLE40zOGte/++tHHE2k69jtCFNWHlKlJXTDpmFVBqGmJFb8Ih658n4xGgdJg==", + "license": "Apache-2.0", + "dependencies": { + "@graphql-typed-document-node/core": "^3.2.0", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "graphql": "^17.0.0", + "graphql-http": "^1.22.4", + "graphql-ws": "^6.0.7" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-node-client": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-node-client/-/wallet-sdk-node-client-2.0.0-beta.2.tgz", + "integrity": "sha512-jW9Mu37a1B9kpUSVAg0PTu7agPza4ffUCLS8rCAWDbAfa65xoECFXUH2FzWR95uxVPes8XY7+onNeBQN7ffJ3w==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "@polkadot/api": "^16.5.4", + "@polkadot/types": "^16.5.4", + "@polkadot/util": "^14.0.1", + "@types/bn.js": "^5.2.0", + "bn.js": "^5.2.3", + "effect": "^3.19.19" + }, + "peerDependencies": { + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-prover-client": "2.0.0-beta.2" + }, + "peerDependenciesMeta": { + "@midnightntwrk/ledger-v9": { + "optional": true + }, + "@midnightntwrk/wallet-sdk-prover-client": { + "optional": true + } + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-prover-client": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-prover-client/-/wallet-sdk-prover-client-2.0.0-beta.2.tgz", + "integrity": "sha512-hNHwsxRbg6HkkgTG4tE13ycKI1IwzMUVFLBgfLtt2/7TkbymyI9XkgollShNrcIQ5RzAg3WYX7d1sx9XIUxblA==", + "license": "Apache-2.0", + "dependencies": { + "@effect/platform": "^0.96.0", + "@midnight-ntwrk/zkir-v2": "^2.1.0", + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "web-worker": "^1.5.0" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-runtime": { + "version": "1.0.6-beta.0", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-runtime/-/wallet-sdk-runtime-1.0.6-beta.0.tgz", + "integrity": "sha512-4Q/hTopMvLaiyncaIFiWQVPvXBHOg8tgPq4Aqx9ta+smuiPFbCAZRq7ezA7PMmKYAEqWeqaY93oK98NmeKUakg==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-shielded": { + "version": "4.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-shielded/-/wallet-sdk-shielded-4.0.0-beta.2.tgz", + "integrity": "sha512-ecxajW6CS4+tNg0nMrofdwXzdhPCbpXADI1saMqP7bP9FJ3+BBIFfZtKIsHL+dN2RySa7+YOlFgeG4kzh/sIYA==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-indexer-client": "1.3.0-beta.1", + "@midnightntwrk/wallet-sdk-runtime": "1.0.6-beta.0", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet": { + "version": "4.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-unshielded-wallet/-/wallet-sdk-unshielded-wallet-4.0.0-beta.2.tgz", + "integrity": "sha512-SBhXPqzEWUybgYO5iLdcPwy1jy2gP4viqTiaWHWGwdkr6kTO1nsXLgq2ZCteWuypbRyMnKhP28z+uGzsrtaZcg==", + "license": "Apache-2.0", + "dependencies": { + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-indexer-client": "1.3.0-beta.1", + "@midnightntwrk/wallet-sdk-runtime": "1.0.6-beta.0", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-utilities": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-utilities/-/wallet-sdk-utilities-1.2.0.tgz", + "integrity": "sha512-Xh5uuCwg4FtAOQCYQ2wkBZtIEt0oCCt1mO3jHLnP+7cyMUQfMNbKwOVi85W3zq+84YFy5DVsN9xifFm75c1MQg==", + "license": "Apache-2.0", + "dependencies": { + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, + "packages/engine-beta/node_modules/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "packages/engine-beta/node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "packages/engine-beta/node_modules/graphql": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-17.0.2.tgz", + "integrity": "sha512-FRWbddMxfkjiB7z+aQDWIR+E34xo9I8c9mtK2RPv8PmMzKRvrdsreHL/Ui/TmwHJfhHChEtsFPyMHKI+xuarQQ==", + "license": "MIT", + "engines": { + "node": "^22.0.0 || ^24.0.0 || ^25.0.0 || >=26.0.0" + } + }, "packages/engine-rc": { "name": "@kuiralabs/midnight-engine-rc", "version": "0.1.0-rc.0", diff --git a/package.json b/package.json index 05c6d996..99577f50 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,8 @@ "packages/connector", "packages/cli-core", "packages/chain", - "packages/engine-rc" + "packages/engine-rc", + "packages/engine-beta" ], "bin": { "midnight": "dist/wallet.js", @@ -48,7 +49,7 @@ }, "scripts": { "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", - "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", @@ -64,6 +65,7 @@ "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.0", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.0", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.0", "@modelcontextprotocol/sdk": "^1.27.1", "@scure/bip39": "^2.0.1", diff --git a/packages/cli-core/src/commands/config.definition.ts b/packages/cli-core/src/commands/config.definition.ts index c2f42cdc..79fdcda6 100644 --- a/packages/cli-core/src/commands/config.definition.ts +++ b/packages/cli-core/src/commands/config.definition.ts @@ -13,7 +13,7 @@ export const configDefinition: CommandDefinition = { takesValue: true, agent: { type: 'string', - description: 'For node / indexer-ws / proof-server: the network to read or write them for (default: the selected network)', + description: 'For node / indexer-ws / proof-server / sdk-set: the network to read or write them for (default: the selected network)', }, }, ], @@ -26,7 +26,7 @@ export const configDefinition: CommandDefinition = { 'unset Reset a config value to its default', '', 'Keys: network, wallet, proof-server, node, indexer-ws,', - ' blockfrost-project-id', + ' blockfrost-project-id, sdk-set', '', 'Endpoint keys (proof-server, node, indexer-ws) are scoped to a', 'network: the selected one, or the one given with --network — a', @@ -37,6 +37,11 @@ export const configDefinition: CommandDefinition = { 'https://blockfrost.io). It is filed under the network its prefix names,', 'shown masked, and never printed. MN_BLOCKFROST_PROJECT_ID or', 'BLOCKFROST_PROJECT_ID in the environment is used instead when set.', + '', + 'sdk-set (rc or beta): the SDK set mn runs a network on, scoped like the', + 'endpoints. Each network has its own (stagenet beta, the others rc); set', + 'this only for a chain that moved to the other set. Each set keeps its', + 'own caches, so a switch never reads the other set\'s state.', ], examples: [ 'midnight config get network', @@ -46,6 +51,7 @@ export const configDefinition: CommandDefinition = { 'midnight config set proof-server http://localhost:6300', 'midnight config set node wss://rpc.preview.midnight.network', `midnight config set indexer-ws wss://indexer.preview.midnight.network${INDEXER_GRAPHQL_WS_PATH}`, + 'midnight config set sdk-set beta --network undeployed', 'midnight config unset proof-server', ], jsonFields: { action: 'get, set, or unset', key: 'Config key name', value: 'Config value' }, diff --git a/packages/cli-core/src/commands/config.ts b/packages/cli-core/src/commands/config.ts index 2b9ce598..5cbc3d46 100644 --- a/packages/cli-core/src/commands/config.ts +++ b/packages/cli-core/src/commands/config.ts @@ -3,7 +3,7 @@ // config set → success message on stderr import { type ParsedArgs, getFlag, hasFlag } from '../lib/argv.ts'; -import { isValidNetworkName, type NetworkName } from '../lib/network.ts'; +import { getValidNetworkNames, isValidNetworkName, type NetworkName } from '../lib/network.ts'; import { UsageError } from '../lib/errors.ts'; import { getConfigValue, setConfigValue, unsetConfigValue, getValidConfigKeys } from '../lib/cli-config.ts'; import { green } from '../ui/colors.ts'; @@ -30,7 +30,7 @@ export default async function configCommand(args: ParsedArgs, ctx: CallContext): // An endpoint key can be read or written for a network other than the selected one. const networkFlag = getFlag(args, 'network'); if (networkFlag !== undefined && !isValidNetworkName(networkFlag)) { - throw new UsageError(`Invalid network: "${networkFlag}"\nValid networks: preprod, preview, undeployed`); + throw new UsageError(`Invalid network: "${networkFlag}"\nValid networks: ${getValidNetworkNames().join(', ')}`); } const scope = networkFlag as NetworkName | undefined; diff --git a/packages/cli-core/src/commands/core.guidance.ts b/packages/cli-core/src/commands/core.guidance.ts index 1abe43b7..cf74778a 100644 --- a/packages/cli-core/src/commands/core.guidance.ts +++ b/packages/cli-core/src/commands/core.guidance.ts @@ -48,6 +48,10 @@ export const coreGuidance: PackageGuidance = { BLOCKFROST_LIMIT_REACHED 4 Blockfrost's plan or rate limit; wait and retry ENDPOINT_SHUT_DOWN 4 An endpoint set by flag or config was shut down by its operator; unset it + OTHER_SDK_SET 1 The process runs one SDK set's engine and the + network runs on the other (an MCP server that + served rc now asked for stagenet); start a + server for that network CANCELLED 7 Operation cancelled (SIGINT) UNKNOWN 1 Unclassified error `, diff --git a/packages/cli-core/src/lib/cache-indexer.ts b/packages/cli-core/src/lib/cache-indexer.ts index 7a4d76c7..85fc6d83 100644 --- a/packages/cli-core/src/lib/cache-indexer.ts +++ b/packages/cli-core/src/lib/cache-indexer.ts @@ -14,7 +14,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { DIR_MODE, FILE_MODE } from './constants.ts'; -import { cacheRootDir } from './wallet-cache.ts'; +import { cacheRootDir, networkCacheFolder } from './wallet-cache.ts'; const MARKER = 'indexer.host'; @@ -49,7 +49,7 @@ export interface IndexerChange { */ export function bindCachesToIndexer(network: string, indexerUrl: string, cacheDir?: string): IndexerChange | undefined { const current = indexerIdentity(indexerUrl); - const dir = join(cacheRootDir(cacheDir), network); + const dir = join(cacheRootDir(cacheDir), networkCacheFolder(network)); const marker = join(dir, MARKER); const recorded = existsSync(marker) ? readFileSync(marker, 'utf-8').trim() : undefined; diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index beb13c2f..460de970 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -13,6 +13,8 @@ import { isVerbose, type ParsedArgs } from './argv.ts'; import { CancelledError } from './errors.ts'; +import { preferEngineOf } from './engine.ts'; +import { resolveNetworkName } from './resolve-network.ts'; import type { Payer } from './payer.ts'; import { settings, type Settings } from './settings.ts'; import { hostPaths, type HostPaths } from './state-root.ts'; @@ -147,5 +149,8 @@ export function createCallContext(parts: CallParts(handler: CommandHandler, args: ParsedArgs, ctx: CallContext): Promise { if (ctx.signal.aborted) throw new CancelledError(); + try { + preferEngineOf(resolveNetworkName({ args })); + } catch { /* an invalid --network: the command says so */ } return handler(args, ctx); } diff --git a/packages/cli-core/src/lib/cli-config.ts b/packages/cli-core/src/lib/cli-config.ts index 9413f7cb..83634cf7 100644 --- a/packages/cli-core/src/lib/cli-config.ts +++ b/packages/cli-core/src/lib/cli-config.ts @@ -2,7 +2,8 @@ import * as fs from 'fs'; import * as path from 'path'; import { DEFAULT_CONFIG_FILENAME, DIR_MODE, FILE_MODE, isValidWalletName } from './constants.ts'; import { blockfrostNetworks, checkProjectId, maskProjectId, networkOfProjectId } from './blockfrost.ts'; -import { type NetworkName, isValidNetworkName } from './network.ts'; +import { type NetworkName, SDK_SETS, getValidNetworkNames, isValidNetworkName } from './network.ts'; +import type { SdkSet } from './engine.ts'; import { UsageError } from './errors.ts'; import { stateRoot } from './state-root.ts'; @@ -13,12 +14,16 @@ export interface NetworkEndpointOverrides { 'indexer-ws'?: string; } -/** What is kept per network: endpoint overrides, and the Blockfrost project id of a network Blockfrost serves. */ +/** What is kept per network: endpoint overrides, the Blockfrost project id of a network Blockfrost serves, and the SDK set it runs on when not the network's own. */ export interface NetworkSettings extends NetworkEndpointOverrides { 'blockfrost-project-id'?: string; + 'sdk-set'?: SdkSet; } const PROJECT_ID_KEY = 'blockfrost-project-id'; +const SDK_SET_KEY = 'sdk-set'; + +const isSdkSet = (value: unknown): value is SdkSet => typeof value === 'string' && (SDK_SETS as readonly string[]).includes(value); export interface CliConfig { network: NetworkName; @@ -44,7 +49,7 @@ const DEFAULT_CLI_CONFIG: CliConfig = { network: 'undeployed', }; -const VALID_CONFIG_KEYS: readonly string[] = ['network', 'proof-server', 'node', 'indexer-ws', 'wallet', PROJECT_ID_KEY] as const; +const VALID_CONFIG_KEYS: readonly string[] = ['network', 'proof-server', 'node', 'indexer-ws', 'wallet', PROJECT_ID_KEY, SDK_SET_KEY] as const; /** * Aliases mapped to canonical config keys. Keeps integrations that learned @@ -144,6 +149,8 @@ export function loadCliConfig(configDir?: string): CliConfig { // A project id is kept only under the network its prefix names. const projectId = (overrides as Record)[PROJECT_ID_KEY]; if (typeof projectId === 'string' && networkOfProjectId(projectId) === name) scoped[PROJECT_ID_KEY] = projectId; + const sdkSet = (overrides as Record)[SDK_SET_KEY]; + if (isSdkSet(sdkSet)) scoped[SDK_SET_KEY] = sdkSet; if (Object.keys(scoped).length > 0) networks[name] = scoped; } if (Object.keys(networks).length > 0) config.networks = networks; @@ -172,6 +179,11 @@ export function getEndpointOverridesForNetwork( }; } +/** The SDK set `midnight config set sdk-set` gave `networkName`, if any. */ +export function getSdkSetOverride(config: CliConfig, networkName: NetworkName): SdkSet | undefined { + return config.networks?.[networkName]?.[SDK_SET_KEY]; +} + /** The Blockfrost project id set for `networkName`, if any. */ export function getBlockfrostProjectId(config: CliConfig, networkName: NetworkName): string | undefined { return config.networks?.[networkName]?.[PROJECT_ID_KEY]; @@ -207,6 +219,7 @@ export function getConfigValue(key: string, configDir?: string, scope?: NetworkN }); return set.length > 0 ? set.join(', ') : '(not set)'; } + if (canonical === SDK_SET_KEY) return getSdkSetOverride(config, scope ?? config.network) ?? '(not set)'; if (ENDPOINT_KEYS.has(canonical)) { const overrides = getEndpointOverridesForNetwork(config, scope ?? config.network); const value = overrides[canonical as keyof NetworkEndpointOverrides]; @@ -256,7 +269,7 @@ export function setConfigValue(key: string, value: string, configDir?: string, s if (canonical === 'network') { if (!isValidNetworkName(value)) { throw new Error( - `Invalid network: "${value}"\nValid networks: preprod, preview, undeployed` + `Invalid network: "${value}"\nValid networks: ${getValidNetworkNames().join(', ')}` ); } migrateFlatEndpointsToScope(config, config.network); @@ -273,6 +286,10 @@ export function setConfigValue(key: string, value: string, configDir?: string, s const { projectId, network } = checkProjectId(value); if (scope !== undefined && scope !== network) throw new UsageError(`That is a ${network} project id, and --network says ${scope}.`); config.networks = { ...(config.networks ?? {}), [network]: { ...(config.networks?.[network] ?? {}), [PROJECT_ID_KEY]: projectId } }; + } else if (canonical === SDK_SET_KEY) { + if (!isSdkSet(value)) throw new UsageError(`Invalid SDK set: "${value}"\nValid SDK sets: ${SDK_SETS.join(', ')}`); + const target = scope ?? config.network; + config.networks = { ...(config.networks ?? {}), [target]: { ...(config.networks?.[target] ?? {}), [SDK_SET_KEY]: value } }; } else if (ENDPOINT_KEYS.has(canonical)) { if (!isValidUrl(value)) { throw new Error( @@ -320,6 +337,14 @@ export function unsetConfigValue(key: string, configDir?: string, scope?: Networ if (Object.keys(scoped).length === 0) delete config.networks![network]; } if (config.networks && Object.keys(config.networks).length === 0) delete config.networks; + } else if (canonical === SDK_SET_KEY) { + const target = scope ?? config.network; + const scoped = config.networks?.[target]; + if (scoped) { + delete scoped[SDK_SET_KEY]; + if (Object.keys(scoped).length === 0) delete config.networks![target]; + if (Object.keys(config.networks!).length === 0) delete config.networks; + } } else if (ENDPOINT_KEYS.has(canonical)) { const k = canonical as keyof NetworkEndpointOverrides; const target = scope ?? config.network; @@ -343,8 +368,8 @@ export function unsetConfigValue(key: string, configDir?: string, scope?: Networ /** A network scope (`--network`) only means something for the keys kept per network. */ function assertScopeApplies(canonical: string, scope: NetworkName | undefined): void { - if (scope !== undefined && !ENDPOINT_KEYS.has(canonical) && canonical !== PROJECT_ID_KEY) { - throw new UsageError(`--network only applies to the endpoint keys (${[...ENDPOINT_KEYS].join(', ')}) and ${PROJECT_ID_KEY}, not "${canonical}".`); + if (scope !== undefined && !ENDPOINT_KEYS.has(canonical) && canonical !== PROJECT_ID_KEY && canonical !== SDK_SET_KEY) { + throw new UsageError(`--network only applies to the endpoint keys (${[...ENDPOINT_KEYS].join(', ')}), ${PROJECT_ID_KEY} and ${SDK_SET_KEY}, not "${canonical}".`); } } diff --git a/packages/cli-core/src/lib/command-definition.ts b/packages/cli-core/src/lib/command-definition.ts index b72fd467..b4737e96 100644 --- a/packages/cli-core/src/lib/command-definition.ts +++ b/packages/cli-core/src/lib/command-definition.ts @@ -10,6 +10,7 @@ // from what it takes and its command's flags. A package is installed with its // commands and its agent guidance. +import { getValidNetworkNames } from './network.ts'; import { FULL_FLAG, type ParsedArgs } from './argv.ts'; import { type PackageGuidance, type ToolsTableRow, assertDistinctPlaces } from './agent-guidance.ts'; import type { CallContext, CommandOutcome } from './call-context.ts'; @@ -22,7 +23,7 @@ export interface ParamSchema { } /** A network as tools show it: one of the networks mn knows (a test keeps it equal to network.ts's). */ -export const NETWORK_PARAM: ParamSchema = { type: 'string', enum: ['preprod', 'preview', 'undeployed'] }; +export const NETWORK_PARAM: ParamSchema = { type: 'string', enum: [...getValidNetworkNames()] }; /** The endpoint flags, as the tools that used to take them unseen describe them. */ export const ENDPOINT_PARAMS = { diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index ec054783..c24772c5 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -13,8 +13,8 @@ import type { FeeLimits } from './fee-limits.ts'; import type { RpcHandler } from './connector-api.ts'; import type { Spinner } from '../ui/spinner.ts'; -/** An SDK set mn runs on. */ -export type SdkSet = 'rc'; +/** An SDK set mn runs on: the SDK's release candidates, or the beta set stagenet runs. */ +export type SdkSet = 'rc' | 'beta'; /** A wallet's keys and addresses, derived from its seed. Every set derives the same ones. */ export interface EngineKeys { @@ -440,6 +440,27 @@ let loader: EngineLoader | undefined; // WASM ledgers can't share one. let loaded: Promise | undefined; +// The set work every set does alike loads while nothing is loaded: the set of +// the network the call is for, so it doesn't commit the process to another. +let preferred: SdkSet | undefined; + +/** A call on a network whose SDK set isn't the one this process has loaded. */ +export class OtherSdkSetError extends Error { + readonly code = 'OTHER_SDK_SET'; + readonly loadedSet: SdkSet; + readonly wantedSet: SdkSet; + constructor( + loadedSet: SdkSet, + wantedSet: SdkSet, + message = `This process runs the ${loadedSet} SDK set and can't load the ${wantedSet} one beside it: two sets' ledgers can't share a process. Run the call in a process of its own.`, + ) { + super(message); + this.name = 'OtherSdkSetError'; + this.loadedSet = loadedSet; + this.wantedSet = wantedSet; + } +} + /** The host's loader of engines, set once at start; a new loader forgets the engine an old one loaded. */ export function setEngineLoader(next: EngineLoader): void { loader = next; @@ -450,7 +471,7 @@ function loadEngine(set: SdkSet): Promise { if (loader === undefined) throw new Error('No SDK engine is installed: the host sets an engine loader at start (setEngineLoader)'); loaded ??= loader(set); return loaded.then((engine) => { - if (engine.set !== set) throw new Error(`This process runs the ${engine.set} SDK set and can't load the ${set} one`); + if (engine.set !== set) throw new OtherSdkSetError(engine.set, set); return engine; }); } @@ -460,10 +481,16 @@ export function engineFor(network: NetworkName): Promise { return loadEngine(sdkSetOf(network)); } +/** The network a call is for, whose set work every set does alike loads while no engine is loaded. */ +export function preferEngineOf(network: NetworkName): void { + preferred = sdkSetOf(network); +} + /** * An engine for work every set does alike, such as deriving addresses: the - * one this process has loaded, else the rc set's. + * one this process has loaded, else the set of the network the call is for + * (the rc set's when none was said). */ export function anyEngine(): Promise { - return loaded ?? loadEngine('rc'); + return loaded ?? loadEngine(preferred ?? 'rc'); } diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index 0f4b88e6..165dc58d 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -55,6 +55,8 @@ export const ERROR_CODES = { BLOCKFROST_LIMIT_REACHED: 'BLOCKFROST_LIMIT_REACHED', /** An endpoint set by flag or config was shut down by its operator. Recovery: unset it (`mn config unset indexer-ws`). */ ENDPOINT_SHUT_DOWN: 'ENDPOINT_SHUT_DOWN', + /** The process has loaded one SDK set's engine and the call's network runs on the other. Recovery: run the call in a process of its own (for MCP, a server for that network). */ + OTHER_SDK_SET: 'OTHER_SDK_SET', /** mn's passphrase was wrong, or a sealed secret was changed. Recovery: run it again with the passphrase mn was protected with. */ WRONG_PASSPHRASE: 'WRONG_PASSPHRASE', /** A secret was needed and no passphrase could be had. Recovery: set MN_PASSPHRASE, or run at a terminal. */ @@ -105,6 +107,9 @@ export function classifyError(err: Error): ClassifiedError { if (code === ERROR_CODES.UNSUPPORTED_NODE) { return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNSUPPORTED_NODE }; } + if (code === ERROR_CODES.OTHER_SDK_SET) { + return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.OTHER_SDK_SET }; + } if (code === ERROR_CODES.NO_ACCOUNT) { return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.NO_ACCOUNT }; } diff --git a/packages/cli-core/src/lib/network-id.ts b/packages/cli-core/src/lib/network-id.ts index 429d8cc4..b102da46 100644 --- a/packages/cli-core/src/lib/network-id.ts +++ b/packages/cli-core/src/lib/network-id.ts @@ -5,18 +5,20 @@ import type { NetworkName } from './network.ts'; -/** A network id as the SDK takes it ("preprod", "preview", "undeployed"). */ -export type MidnightNetworkId = 'preprod' | 'preview' | 'undeployed'; +/** A network id as the SDK takes it ("preprod", "preview", "stagenet", "undeployed"). */ +export type MidnightNetworkId = 'preprod' | 'preview' | 'stagenet' | 'undeployed'; const NETWORK_ID_MAP: Record = { PreProd: 'preprod', Preview: 'preview', + StageNet: 'stagenet', Undeployed: 'undeployed', }; const NETWORK_ID_BY_NAME: Record = { preprod: 'preprod', preview: 'preview', + stagenet: 'stagenet', undeployed: 'undeployed', }; diff --git a/packages/cli-core/src/lib/network.ts b/packages/cli-core/src/lib/network.ts index 915dbed8..9a705202 100644 --- a/packages/cli-core/src/lib/network.ts +++ b/packages/cli-core/src/lib/network.ts @@ -1,11 +1,11 @@ import { blockfrostEndpoints, usesBlockfrost } from './blockfrost.ts'; import { execSync } from 'child_process'; -import { loadCliConfig, getEndpointOverridesForNetwork } from './cli-config.ts'; +import { loadCliConfig, getEndpointOverridesForNetwork, getSdkSetOverride } from './cli-config.ts'; import { INDEXER_GRAPHQL_PATH, INDEXER_GRAPHQL_WS_PATH } from './constants.ts'; import { settings } from './settings.ts'; import type { SdkSet } from './engine.ts'; -export type NetworkName = 'preprod' | 'preview' | 'undeployed'; +export type NetworkName = 'preprod' | 'preview' | 'stagenet' | 'undeployed'; /** * The protocol version ledger 9 starts at on the chains this build targets: @@ -38,6 +38,14 @@ const NETWORK_CONFIGS: Record = { proofServer: 'http://localhost:6300', networkId: 'Preview', }, + // Sig Network's stagenet, which runs the beta SDK set. + stagenet: { + indexer: `https://indexer.stagenet.shielded.tools${INDEXER_GRAPHQL_PATH}`, + indexerWS: `wss://indexer.stagenet.shielded.tools${INDEXER_GRAPHQL_WS_PATH}`, + node: 'wss://rpc.stagenet.shielded.tools', + proofServer: 'http://localhost:6300', + networkId: 'StageNet', + }, undeployed: { indexer: `http://localhost:8088${INDEXER_GRAPHQL_PATH}`, indexerWS: `ws://localhost:8088${INDEXER_GRAPHQL_WS_PATH}`, @@ -51,15 +59,29 @@ const NETWORK_CONFIGS: Record = { const NETWORK_SDK_SETS: Record = { preprod: 'rc', preview: 'rc', + stagenet: 'beta', undeployed: 'rc', }; -/** The SDK set a network runs on. */ -export function sdkSetOfNetwork(name: NetworkName): SdkSet { +/** Every SDK set mn has an engine for. */ +export const SDK_SETS: readonly SdkSet[] = ['rc', 'beta']; + +/** The SDK set the network table names for a network. */ +export function defaultSdkSetOf(name: NetworkName): SdkSet { return NETWORK_SDK_SETS[name]; } -const VALID_NETWORK_NAMES: readonly NetworkName[] = ['preprod', 'preview', 'undeployed'] as const; +/** The networks that run on `set` now. */ +export function networksOnSdkSet(set: SdkSet): NetworkName[] { + return VALID_NETWORK_NAMES.filter((name) => sdkSetOfNetwork(name) === set); +} + +/** The SDK set a network runs on: the one `midnight config set sdk-set` gave it, else the table's. */ +export function sdkSetOfNetwork(name: NetworkName): SdkSet { + return getSdkSetOverride(loadCliConfig(), name) ?? NETWORK_SDK_SETS[name]; +} + +const VALID_NETWORK_NAMES: readonly NetworkName[] = ['preprod', 'preview', 'stagenet', 'undeployed'] as const; export function isValidNetworkName(name: string): name is NetworkName { return VALID_NETWORK_NAMES.includes(name as NetworkName); @@ -80,6 +102,7 @@ export function getValidNetworkNames(): readonly string[] { export function detectNetworkFromAddress(address: string): NetworkName | null { if (address.startsWith('mn_addr_preprod1')) return 'preprod'; if (address.startsWith('mn_addr_preview1')) return 'preview'; + if (address.startsWith('mn_addr_stagenet1')) return 'stagenet'; if (address.startsWith('mn_addr_undeployed1')) return 'undeployed'; return null; } diff --git a/packages/cli-core/src/lib/reader-cache-files.ts b/packages/cli-core/src/lib/reader-cache-files.ts index e355d921..bea25e16 100644 --- a/packages/cli-core/src/lib/reader-cache-files.ts +++ b/packages/cli-core/src/lib/reader-cache-files.ts @@ -4,12 +4,12 @@ import { existsSync, readdirSync, unlinkSync } from 'node:fs'; import { join } from 'node:path'; -import { cacheKeyOf, cacheRootDir } from './wallet-cache.ts'; +import { cacheKeyOf, cacheRootDir, networkCacheFolder } from './wallet-cache.ts'; /** The folder of a network's reader caches. */ export function dustCacheDir(network: string, cacheDir?: string): string { const base = cacheRootDir(cacheDir); - return join(base, network); + return join(base, networkCacheFolder(network)); } /** The Dust reader's cache file for a network and Dust public key. */ @@ -67,7 +67,7 @@ export function clearDustDirectCache( function shieldedCacheDir(network: string, cacheDir?: string): string { const base = cacheRootDir(cacheDir); - return join(base, network); + return join(base, networkCacheFolder(network)); } /** The shielded reader's cache file for a network and coin public key. */ @@ -135,7 +135,7 @@ export const nativeCheckpointName = (pubkeyHex: string): string => `dust-native- export function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, cacheDir?: string): void { const base = cacheRootDir(cacheDir); if (network && pubkeyHex) { - try { unlinkSync(join(base, network, nativeCheckpointName(pubkeyHex))); } catch { /* not found is ok */ } + try { unlinkSync(join(base, networkCacheFolder(network), nativeCheckpointName(pubkeyHex))); } catch { /* not found is ok */ } return; } const wipeDir = (dir: string) => { @@ -148,7 +148,7 @@ export function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, } } catch { /* best-effort */ } }; - if (network) { wipeDir(join(base, network)); return; } + if (network) { wipeDir(join(base, networkCacheFolder(network))); return; } if (!existsSync(base)) return; try { for (const net of readdirSync(base)) wipeDir(join(base, net)); } catch { /* best-effort */ } } diff --git a/packages/cli-core/src/lib/shielded-policy.ts b/packages/cli-core/src/lib/shielded-policy.ts index cd7ff62a..8c82a426 100644 --- a/packages/cli-core/src/lib/shielded-policy.ts +++ b/packages/cli-core/src/lib/shielded-policy.ts @@ -1,5 +1,5 @@ // Shielded-sync policy. Shielded (zswap) sync is the slow part of a facade sync, -// and on preview/preprod it is pointless: there is no shielded faucet, so a +// and on preview, preprod and stagenet it is pointless: there is no shielded faucet, so a // wallet can never hold shielded funds there. Skipping it makes those networks // fast (unshielded is GraphQL, dust is already optimized) without hiding // anything real. `undeployed` (localnet genesis) and any future funded network @@ -9,7 +9,7 @@ import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; /** Networks with no shielded faucet — shielded sync is skipped by default. */ -const NO_SHIELDED_FAUCET: readonly NetworkName[] = ['preview', 'preprod']; +const NO_SHIELDED_FAUCET: readonly NetworkName[] = ['preview', 'preprod', 'stagenet']; /** True when shielded funds are actually reachable on this network. */ export function networkHasShielded(network: NetworkName): boolean { diff --git a/packages/cli-core/src/lib/wallet-cache.ts b/packages/cli-core/src/lib/wallet-cache.ts index df51342c..b9315d10 100644 --- a/packages/cli-core/src/lib/wallet-cache.ts +++ b/packages/cli-core/src/lib/wallet-cache.ts @@ -7,6 +7,7 @@ import { randomBytes } from 'node:crypto'; import { CACHE_VERSION, CACHE_DIR_NAME, DIR_MODE, FILE_MODE } from './constants.ts'; import { stateRoot } from './state-root.ts'; +import { defaultSdkSetOf, isValidNetworkName, sdkSetOfNetwork } from './network.ts'; export interface WalletCacheData { shielded: string; @@ -34,6 +35,17 @@ export function cacheRootDir(cacheDir?: string): string { return cacheDir ?? join(stateRoot(), CACHE_DIR_NAME); } +/** + * A network's folder under the cache folder: the network's name, or + * `.` while `midnight config set sdk-set` runs it on another SDK + * set, so one set never reads the state the other wrote. + */ +export function networkCacheFolder(network: string): string { + if (!isValidNetworkName(network)) return network; + const set = sdkSetOfNetwork(network); + return set === defaultSdkSetOf(network) ? network : `${network}.${set}`; +} + /** How much of an address or key names its cache file: enough to keep them apart, short enough for any filesystem. */ export const CACHE_KEY_PREFIX_LENGTH = 20; @@ -49,7 +61,7 @@ export function cacheKeyOf(addressOrKey: string): string { export function getCachePath(address: string, network: string, cacheDir?: string): string { const base = cacheRootDir(cacheDir); const prefix = cacheKeyOf(address); - return join(base, network, `${prefix}.json`); + return join(base, networkCacheFolder(network), `${prefix}.json`); } /** @@ -160,7 +172,7 @@ export function validateWalletCacheChainId( if (!currentChainId) return []; // node unreachable — skip validation const base = cacheRootDir(cacheDir); - const dir = join(base, network); + const dir = join(base, networkCacheFolder(network)); if (!existsSync(dir)) return []; const wiped: string[] = []; @@ -201,7 +213,7 @@ export function clearWalletCache(address?: string, network?: string, cacheDir?: if (network) { // Delete all caches for a network - const dir = join(base, network); + const dir = join(base, networkCacheFolder(network)); if (!existsSync(dir)) return; try { for (const file of readdirSync(dir)) { diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json new file mode 100644 index 00000000..cf5dd69d --- /dev/null +++ b/packages/engine-beta/package.json @@ -0,0 +1,66 @@ +{ + "name": "@kuiralabs/midnight-engine-beta", + "version": "0.1.0-rc.0", + "type": "module", + "description": "The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK 5.0 beta split packages, ledger 9 rc.3, midnight-js 5 beta): everything the CLI does with that SDK set, behind the engine interface", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/engine-beta" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./*": { + "midnight-cli-source": "./src/*.ts", + "types": "./dist/*.d.ts", + "default": "./dist/*.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@midnight-ntwrk/compact-js": "2.5.5-rc.7", + "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-utils": "5.0.0-beta.6", + "@midnightntwrk/ledger-v9": "1.0.0-rc.3", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", + "@midnightntwrk/wallet-sdk-address-format": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-dust-wallet": "5.0.0-beta.2", + "@midnightntwrk/wallet-sdk-facade": "5.0.0-beta.2", + "@midnightntwrk/wallet-sdk-hd": "3.1.0-beta.1", + "@midnightntwrk/wallet-sdk-shielded": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.0-beta.2", + "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "@scure/base": "2.0.0", + "rxjs": "7.8.2", + "ws": "^8.19.0" + } +} diff --git a/packages/engine-beta/src/addresses.ts b/packages/engine-beta/src/addresses.ts new file mode 100644 index 00000000..7a714567 --- /dev/null +++ b/packages/engine-beta/src/addresses.ts @@ -0,0 +1,22 @@ +// Reading bech32m addresses as the SDK's address types, for the network they +// must be on. + +import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk-address-format'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; + +/** A shielded address on `network`, as the SDK reads it. Throws when it is not one. */ +export function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress { + return MidnightBech32m.parse(address).decode(ShieldedAddress, networkIdForName(network)); +} + +/** An unshielded address on `network`, as the SDK reads it. Throws when it is not one. */ +export function decodeUnshieldedAddress(address: string, network: NetworkName): UnshieldedAddress { + return MidnightBech32m.parse(address).decode(UnshieldedAddress, networkIdForName(network)); +} + +/** Throws, saying why, unless `address` is an address of that kind on `network`. */ +export function assertAddress(address: string, kind: 'shielded' | 'unshielded', network: NetworkName): void { + if (kind === 'shielded') decodeShieldedAddress(address, network); + else decodeUnshieldedAddress(address, network); +} diff --git a/packages/engine-beta/src/airdrop.ts b/packages/engine-beta/src/airdrop.ts new file mode 100644 index 00000000..f31eb5aa --- /dev/null +++ b/packages/engine-beta/src/airdrop.ts @@ -0,0 +1,25 @@ +// Airdrop: unshielded NIGHT from the genesis wallet (seed 0x01) of a local +// devnet. `mn airdrop` and `mn dev` both fund wallets through here; the +// caller has already checked that the network is the local one. + +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; +import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; + + +/** Sends `amountNight` NIGHT from genesis to `recipientAddress`. */ +export async function airdropNight(params: AirdropParams): Promise { + try { + return await executeTransfer({ ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); + } catch (err) { + if (err instanceof Error && err.message.toLowerCase().includes('dust')) { + throw new Error( + `${err.message}\n\n` + + `On a fresh localnet, the minimum airdrop is ~1 NIGHT.\n` + + `Try: midnight airdrop 1` + ); + } + throw err; + } +} diff --git a/packages/engine-beta/src/contract-providers.ts b/packages/engine-beta/src/contract-providers.ts new file mode 100644 index 00000000..dd94b435 --- /dev/null +++ b/packages/engine-beta/src/contract-providers.ts @@ -0,0 +1,26 @@ +// Contract providers — lightweight provider setup for state queries. +// Deploy/call use the runner (generated scripts in dApp context) which build their own providers. + +import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; +import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { describeRawState } from './raw-state.ts'; + +/** + * Build a lightweight indexer-only provider for state queries. + * No wallet or proof server needed. + */ +export function buildStateProvider(networkConfig: NetworkConfig) { + assertEndpointUsable(networkConfig.indexer); + return indexerPublicDataProvider({ + queryURL: networkConfig.indexer, + subscriptionURL: networkConfig.indexerWS ?? networkConfig.indexer.replace('http', 'ws'), + }); +} + +/** A deployed contract's ledger state as plain JSON, read without its compiled contract; null when no contract is at `address`. */ +export async function rawContractState(networkConfig: NetworkConfig, address: string): Promise { + const found = await buildStateProvider(networkConfig).queryContractState(address); + return found ? describeRawState(found.data.state) : null; +} diff --git a/packages/engine-beta/src/contract-scripts.ts b/packages/engine-beta/src/contract-scripts.ts new file mode 100644 index 00000000..7fbd2dac --- /dev/null +++ b/packages/engine-beta/src/contract-scripts.ts @@ -0,0 +1,350 @@ +// The scripts mn runs in a dApp's own folder to deploy, call and read a +// contract with midnight-js, and the packages they import, for this engine's +// SDK set. What every set's script shares (the prelude that reports a +// failure, the client of mn serve's RPC, the argument and secret helpers, +// where the witnesses may be) comes from the runner as ScriptParts. + +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; +import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; + +/** + * Every package a generated script imports, and the compact runtime the + * user's compiled contract imports. Each is found by name from this engine's + * location and linked into the dApp by name, so this works wherever the + * packages sit (our checkout, our install, or someone else's hoisted tree). + * A test keeps this list in step with the scripts' imports. + */ +export const SCRIPT_PACKAGES = [ + '@midnight-ntwrk/compact-js', + '@midnight-ntwrk/compact-runtime', + '@midnight-ntwrk/midnight-js-contracts', + '@midnight-ntwrk/midnight-js-http-client-proof-provider', + '@midnight-ntwrk/midnight-js-indexer-public-data-provider', + '@midnight-ntwrk/midnight-js-level-private-state-provider', + '@midnight-ntwrk/midnight-js-network-id', + '@midnight-ntwrk/midnight-js-node-zk-config-provider', + '@midnight-ntwrk/midnight-js-types', + '@midnight-ntwrk/midnight-js-utils', + 'ws', +] as const; + +/** The folder of the installed package `name`, as mn resolves it; null when it isn't installed. */ +export function packageFolder(name: string): string | null { + // node:module's createRequire works in every host (Node, the test runner, + // the bundle); a package exported to `import` only is found through + // import.meta.resolve where the host has it. + let entry: string; + try { + entry = createRequire(import.meta.url).resolve(name); + } catch { + try { + entry = fileURLToPath(import.meta.resolve(name)); + } catch { + return null; + } + } + for (let dir = dirname(entry); ; dir = dirname(dir)) { + const manifest = join(dir, 'package.json'); + if (existsSync(manifest)) { + try { + if ((JSON.parse(readFileSync(manifest, 'utf8')) as { name?: string }).name === name) return dir; + } catch { /* not this one: keep looking up */ } + } + if (dirname(dir) === dir) return null; + } +} + +/** + * SDK imports used by walletProviderCode and providerSetupCode. Kept out of + * those fragments so a test can evaluate a fragment with the same bindings. + */ +export const PROVIDER_IMPORTS = ` +import { Transaction } from '@midnight-ntwrk/midnight-js-types'; +import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils'; +import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; +import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; +import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; +import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; +`; + +/** + * walletProvider + midnightProvider backed by mn serve RPC. midnight-js + * 5.0.0-beta.6 takes plain provider objects and hands them live ledger-v9 + * txs: it has no version tags, no `supportedEras` and no + * createWalletProvider/createMidnightProvider. + */ +export function walletProviderCode(): string { + return ` +const walletState = await rpcCall('getShieldedAddresses', {}); + +const walletProvider = { + getCoinPublicKey: () => walletState.shieldedCoinPublicKey, + getEncryptionPublicKey: () => walletState.shieldedEncryptionPublicKey, + // ttl is ignored: mn serve applies its own TTL when balancing. + async balanceTx(tx) { + const result = await rpcCall('balanceUnsealedTransaction', { tx: toHex(tx.serialize()) }); + return Transaction.deserialize('signature', 'proof', 'binding', fromHex(result.tx)); + }, +}; + +const midnightProvider = { + async submitTx(tx) { + await rpcCall('submitTransaction', { tx: toHex(tx.serialize()) }); + return tx.identifiers()[0]; + }, +}; +`; +} + +function contractSetupCode(contractName: string, managedDir: string, parts: ScriptParts): string { + return ` +import { pathToFileURL } from 'node:url'; +import { resolve } from 'node:path'; +import { CompiledContract } from '@midnight-ntwrk/compact-js'; + +const MANAGED_DIR = ${JSON.stringify(managedDir)}; + +// Load compiled contract class +const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract', 'index.js')).href); + +// Try to load witnesses and private state factory. +// Both relative-to-cwd locations and contract/<...> locations are checked +// so mn dev (which chdirs into the contract sub-package) and mn contract +// deploy run from a workspace root both work. +const WITNESS_CANDIDATES = ${JSON.stringify(parts.witnessCandidates)}; +let witnesses; +let createPrivateState; +for (const p of WITNESS_CANDIDATES) { + try { + const wMod = await import(pathToFileURL(resolve(p)).href); + if (wMod.witnesses) { witnesses = wMod.witnesses; } + // Look for createInitialPrivateState or create*PrivateState + for (const key of Object.keys(wMod)) { + if (typeof wMod[key] === 'function' && key.startsWith('create') && key.toLowerCase().includes('privatestate')) { + createPrivateState = wMod[key]; + } + } + if (witnesses) break; + } catch {} +} + +// Note: callers (commands/contract.ts, commands/dev.ts) preflight when the +// contract's compiler-info declares witnesses, so a missing module here means +// the contract truly has no witnesses (vacant is correct). The runtime +// warning still names every path we tried — useful when the SDK later +// complains about a specific witness name despite preflight passing. +if (!witnesses) { + process.stderr.write('Warning: No witnesses module found — using vacant witnesses. Searched:\\n'); + for (const p of WITNESS_CANDIDATES) process.stderr.write(' - ' + p + '\\n'); +} + +// Generate initial private state. +// Uses a deterministic seed derived from the wallet so post/takeDown use the same key. +// The private state provider (leveldb) persists between calls, but initialPrivateState +// is the fallback when no stored state exists yet. +${parts.privateStateSecretFn} +function makeInitialPrivateState() { + if (createPrivateState) { + // Secret precedence (see resolvePrivateStateSecretKey, injected above via + // .toString()): an explicit mn --secret-key (from env MN_PRIVATE_STATE_SECRET, + // never on disk) wins, else a deterministic key from the wallet's coin public + // key so post/takeDown reuse it, else random. + const secretKey = resolvePrivateStateSecretKey( + process.env.MN_PRIVATE_STATE_SECRET, + walletState?.shieldedCoinPublicKey, + ); + try { return createPrivateState(secretKey); } catch {} + try { return createPrivateState(); } catch {} + } + return {}; +} + +const compiled = witnesses + ? CompiledContract.make(${JSON.stringify(contractName)}, contractMod.Contract).pipe( + (c) => CompiledContract.withWitnesses(c, witnesses), + (c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR), + ) + : CompiledContract.make(${JSON.stringify(contractName)}, contractMod.Contract).pipe( + CompiledContract.withVacantWitnesses, + (c) => CompiledContract.withCompiledFileAssets(c, MANAGED_DIR), + ); +`; +} + +/** The `providers` object deploy/call pass to midnight-js-contracts. */ +export function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string, parts: ScriptParts): string { + return ` +const zkConfigProvider = new NodeZkConfigProvider(MANAGED_DIR); + +const providers = { + privateStateProvider: levelPrivateStateProvider({ + privateStateStoreName: ${JSON.stringify(privateStateKey)}, + privateStoragePasswordProvider: () => Promise.resolve('mn-contract-default-pwd-16ch'), + accountId: 'mn-contract-runner', + }), + publicDataProvider: indexerPublicDataProvider({ + queryURL: process.env.${parts.indexerUrlEnv}, + subscriptionURL: process.env.${parts.indexerWsUrlEnv}, + }), + zkConfigProvider, + proofProvider: httpClientProofProvider({ url: ${JSON.stringify(networkConfig.proofServer)}, zkConfigProvider }), + walletProvider, + midnightProvider, +}; +`; +} + +// ── Script generation ── + +export function generateDeployScript(opts: DeployScript, parts: ScriptParts): string { + const privateStateKey = opts.privateStateKey ?? `${opts.contractName}PrivateState`; + // Constructor args are pre-serialized to JSON here (still in our process) + // so the generated script just spreads them. The coerceArg helper inside + // the bridge then upgrades number → BigInt and number[] → Uint8Array, the + // two coercions Compact circuits invariably need. + const argsLiteral = JSON.stringify(opts.args ?? []); + + return `${parts.prelude} +import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; +setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); + +${parts.rpcClientCode(opts.servePort)} +${contractSetupCode(opts.contractName, opts.managedDir, parts)} + +process.stderr.write('Connecting to mn serve...\\n'); +await rpcConnect(); +process.stderr.write('Connected\\n'); + +${PROVIDER_IMPORTS} +${walletProviderCode()} +${providerSetupCode(opts.networkConfig, privateStateKey, parts)} + +import { deployContract } from '@midnight-ntwrk/midnight-js-contracts'; + +${parts.coerceArgFn} +const constructorArgs = (${argsLiteral}).map(coerceArg); +process.stderr.write('Deploying contract' + (constructorArgs.length ? ' with ' + constructorArgs.length + ' constructor arg(s)...' : '...') + '\\n'); +const deployed = await deployContract(providers, { + compiledContract: compiled, + privateStateId: ${JSON.stringify(privateStateKey)}, + initialPrivateState: makeInitialPrivateState(), + args: constructorArgs, +}); + +const address = deployed.deployTxData?.public?.contractAddress ?? 'unknown'; +process.stderr.write('Deploy complete: ' + address + '\\n'); + +console.log(JSON.stringify({ contractAddress: address })); +rpcClose(); +process.exit(0); +`; +} + +export function generateCallScript(opts: CallScript, parts: ScriptParts): string { + const privateStateKey = opts.privateStateKey ?? `${opts.contractName}PrivateState`; + + return `${parts.prelude} +import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; +setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); + +${parts.rpcClientCode(opts.servePort)} +${contractSetupCode(opts.contractName, opts.managedDir, parts)} + +process.stderr.write('Connecting to mn serve...\\n'); +await rpcConnect(); +process.stderr.write('Connected\\n'); + +${PROVIDER_IMPORTS} +${walletProviderCode()} +${providerSetupCode(opts.networkConfig, privateStateKey, parts)} + +import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts'; + +process.stderr.write('Finding deployed contract...\\n'); +const deployed = await findDeployedContract(providers, { + compiledContract: compiled, + contractAddress: ${JSON.stringify(opts.contractAddress)}, + privateStateId: ${JSON.stringify(privateStateKey)}, + initialPrivateState: makeInitialPrivateState(), +}); + +process.stderr.write('Calling ${opts.circuit}...\\n'); +${parts.coerceArgFn} +const args = (${JSON.stringify(opts.args ?? [])}).map(coerceArg); +await deployed.callTx.${opts.circuit}(...args); + +console.log(JSON.stringify({ status: 'success', circuit: ${JSON.stringify(opts.circuit)} })); +rpcClose(); +process.exit(0); +`; +} + +export function generateStateScript(opts: StateScript, parts: ScriptParts): string { + return `${parts.prelude} +import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id'; +setNetworkId(${JSON.stringify(opts.networkConfig.networkId.toLowerCase())}); + +import { pathToFileURL } from 'node:url'; +import { resolve } from 'node:path'; +import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; + +const MANAGED_DIR = ${JSON.stringify(opts.managedDir)}; + +// Load the contract module which exports the ledger() function +const contractMod = await import(pathToFileURL(resolve(MANAGED_DIR, 'contract', 'index.js')).href); + +if (typeof contractMod.ledger !== 'function') { + fail(new Error('Contract module does not export a ledger() function')); +} + +process.stderr.write('Querying contract state...\\n'); +const provider = indexerPublicDataProvider({ + queryURL: process.env.${parts.indexerUrlEnv}, + subscriptionURL: process.env.${parts.indexerWsUrlEnv}, +}); + +const contractState = await provider.queryContractState(${JSON.stringify(opts.contractAddress)}); +if (!contractState) { + fail(new Error('No contract found at address ${opts.contractAddress}')); +} + +process.stderr.write('Parsing ledger state...\\n'); +// ledger() expects contractState.data (ChargedState), not the full ContractState +const state = contractMod.ledger(contractState.data ?? contractState); + +// Extract scalar fields and map fields +const fields = {}; +const maps = {}; + +for (const key of Object.keys(state)) { + const val = state[key]; + + // Check if it's a map-like (has size() and Symbol.iterator) + if (val && typeof val === 'object' && typeof val.size === 'function') { + try { + maps[key] = { size: val.size().toString() }; + } catch { + maps[key] = { size: '?' }; + } + } else if (typeof val === 'bigint') { + fields[key] = val.toString(); + } else if (typeof val === 'string') { + fields[key] = val; + } else if (typeof val === 'boolean') { + fields[key] = String(val); + } else if (val instanceof Uint8Array) { + fields[key] = Array.from(val).map(b => b.toString(16).padStart(2, '0')).join(''); + } else if (val !== undefined && val !== null) { + try { fields[key] = JSON.stringify(val); } catch { fields[key] = '?'; } + } +} + +console.log(JSON.stringify({ fields, maps })); +process.exit(0); +`; +} + diff --git a/packages/engine-beta/src/dapp-connector.ts b/packages/engine-beta/src/dapp-connector.ts new file mode 100644 index 00000000..70f9702d --- /dev/null +++ b/packages/engine-beta/src/dapp-connector.ts @@ -0,0 +1,1019 @@ +// DApp Connector — implements all 18 ConnectedAPI methods as RPC handlers +// Factory function returns a handler map for ws-rpc.ts to dispatch + +import * as rx from 'rxjs'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk-address-format'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import type { UnboundTransaction } from '@midnightntwrk/wallet-sdk-capabilities/proving'; +import type { FacadeState, WalletEntry } from '@midnightntwrk/wallet-sdk-facade'; + +import { type FacadeBundle, hasDustAvailable } from './facade.ts'; +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { createApiError, type RpcHandler, type RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { createPhaseTracker, type PhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; +import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; +import { inspectTxHex } from './tx-inspect.ts'; +import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; +import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; +import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; +import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; +import { fetchPartialSuccessSegments, type SegmentResult } from '@kuiralabs/midnight-chain/lib/tx-segments'; +import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; + +// ── Types ── + + +export interface DAppConnectorOptions { + bundle: FacadeBundle; + networkConfig: NetworkConfig; + approvalOptions: ApprovalOptions; + /** Under --approve-fees: the most a transaction may cost, and how many may wait unsubmitted. */ + feeLimits?: FeeLimits; + callbacks?: DAppConnectorCallbacks; + /** + * The state the caller's own sync ended on. Reads answer from it at once; + * without it they are refused ("Wallet not synced yet") until the wallet's + * next state that counts as current, which on a hosted indexer can be the + * better part of a minute after the server says it is ready. + */ + initialState?: FacadeState; + /** + * Which wallet states count as current and replace the one reads answer + * from. Default: the SDK's own `isSynced`, which also waits for wallets the + * caller chose not to sync and for a flag the SDK's Dust wallet doesn't set + * on a quiet stream. A caller that synced by another rule passes that rule. + */ + isCurrent?: (state: FacadeState) => boolean; + /** + * The longest a request waits for the wallet's Dust to grow to a fee it + * doesn't cover yet. A fee that takes longer is refused at once, with the + * time it takes. Default: DUST_SHORT_WAIT_MS. + */ + dustWaitMs?: number; +} + +/** A dApp's transaction as the facade takes it, by stage. */ +type DAppTransaction = { Unbound: UnboundTransaction; Finalized: ledger.FinalizedTransaction }; + +/** Which token kinds the facade balances a dApp's transaction in. */ +export type TokenKindsToBalance = 'all' | Array<'dust' | 'shielded' | 'unshielded'>; + + +// ── Factory ── + +/** Where a FiberFailure keeps the Cause its Effect failed with. The wallet + * SDK runs its Effects with Effect.runPromise, which rejects with one: the + * error the Effect failed with, and what that wraps, are under this symbol, + * not `cause`. */ +const FIBER_FAILURE_CAUSE = Symbol.for('effect/Runtime/FiberFailure/Cause'); + +/** The error a FiberFailure's Effect failed or died with; undefined for anything else. */ +function fiberFailureOf(err: object): unknown { + const cause = (err as Record)[FIBER_FAILURE_CAUSE]; + if (cause?._tag === 'Fail') return cause.error; + if (cause?._tag === 'Die') return cause.defect; + return undefined; +} + +/** Extract a human-readable detail string from an SDK/chain error. + * Walks nested cause chains including Effect Data.TaggedError objects, and + * into the error a FiberFailure holds. */ +function extractErrorDetail(err: unknown): string { + const parts: string[] = []; + let current: unknown = err; + const seen = new Set(); + while (current && !seen.has(current)) { + seen.add(current); + // A FiberFailure says only its failure's message: read the failure itself. + const failure = typeof current === 'object' ? fiberFailureOf(current) : undefined; + if (failure !== undefined) { + current = failure; + continue; + } + const anyErr = current as any; + // Effect Data.TaggedError or standard Error + if (current instanceof Error || (typeof current === 'object' && anyErr._tag)) { + const tag = anyErr._tag; + const msg = anyErr.message ?? ''; + if (tag && msg) { + parts.push(`[${tag}] ${msg}`); + } else if (msg) { + parts.push(msg); + } else if (tag) { + parts.push(`[${tag}]`); + } + // Effect errors may have structured data + if (anyErr.data && typeof anyErr.data === 'object') { + try { parts.push(`data=${JSON.stringify(anyErr.data)}`); } catch { /* skip */ } + } + // Walk the cause chain (works for both Error.cause and Effect's cause field) + current = anyErr.cause; + } else if (typeof current === 'string') { + parts.push(current); + break; + } else { + try { + const str = JSON.stringify(current); + if (str && str !== '{}') parts.push(str); + else parts.push(String(current)); + } catch { parts.push(String(current)); } + break; + } + } + // Deduplicate identical consecutive messages (SDK wraps same message at multiple levels) + const deduped: string[] = []; + for (const p of parts) { + if (deduped.length === 0 || deduped[deduped.length - 1] !== p) { + deduped.push(p); + } + } + return deduped.join(' → ') || 'Unknown error'; +} + +export { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; + +/** The connector API's history entry for one wallet history entry. */ +export type HistoryEntry = { + txHash: string; + txStatus: + | { status: 'finalized'; executionStatus: Record } + | { status: 'pending' } + | { status: 'discarded' }; +}; + +/** + * Map a wallet history entry onto the connector API's shape. The wallet keeps + * one outcome per transaction; segment 0 is the guaranteed section, which + * every transaction has. + * - SUCCESS: every segment succeeded, so segment 0 did. + * - FAILURE: the ledger reports any fallible failure as a partial success, + * so a failure is the guaranteed section's. + * - PARTIAL_SUCCESS: the per-segment results, which only the indexer has, are + * required as `segments`. + * An entry with no recorded outcome reports none. + */ +export function toHistoryEntry(entry: WalletEntry, segments?: readonly SegmentResult[]): HistoryEntry { + switch (entry.lifecycle.status) { + case 'finalized': + return { txHash: entry.hash, txStatus: { status: 'finalized', executionStatus: executionStatusOf(entry, segments) } }; + case 'rejected': + return { txHash: entry.hash, txStatus: { status: 'discarded' } }; + case 'pending': + return { txHash: entry.hash, txStatus: { status: 'pending' } }; + } +} + +function executionStatusOf(entry: WalletEntry, segments?: readonly SegmentResult[]): Record { + switch (entry.status) { + case 'SUCCESS': + return { 0: 'Success' }; + case 'FAILURE': + return { 0: 'Failure' }; + case 'PARTIAL_SUCCESS': + if (!segments || segments.length === 0) { + throw new Error(`Transaction ${entry.hash} partly succeeded, but its segment results are missing`); + } + return Object.fromEntries(segments.map((s) => [s.id, s.success ? 'Success' : 'Failure'])); + case undefined: + return {}; + } +} + +/** + * The connector API's name for a signature scheme. mn's unshielded key is a + * BIP-340 Schnorr key; it never signs ECDSA, so any other tag is a bug. + */ +export function signatureScheme(tag: string): 'schnorr_bip340' { + if (tag !== 'schnorr') { + throw new Error(`Unexpected signature scheme "${tag}": mn signs with BIP-340 Schnorr only`); + } + return 'schnorr_bip340'; +} + +export function createDAppConnector(options: DAppConnectorOptions): DAppConnector { + const { bundle, networkConfig, approvalOptions, callbacks } = options; + const feeLimits = options.feeLimits ?? DEFAULT_FEE_LIMITS; + const { facade, keystore, secretKeys } = bundle; + const networkId = getNetworkId(networkConfig.networkId); + + // ── State subscription — cache latest synced state ── + + const isCurrent = options.isCurrent ?? ((state: FacadeState) => state.isSynced); + const dustWaitMs = options.dustWaitMs ?? DUST_SHORT_WAIT_MS; + let latestState: FacadeState | undefined = options.initialState; + // Whether any state has come, synced or not: until one has, the wallet + // takes no transaction work (as the rc engine refuses it). + let started = options.initialState !== undefined; + const subscription = facade.state().subscribe((state) => { + started = true; + if (isCurrent(state)) latestState = state; + }); + + function getState(): FacadeState { + if (!latestState) { + throw createApiError('Disconnected', 'Wallet not synced yet'); + } + return latestState; + } + + /** + * Refuse transaction work until the wallet's first state. The beta SDK has + * one ledger, so there is no fork to wait for, only the first state. + */ + function assertWalletStarted(): void { + if (!started) { + throw createApiError('Disconnected', 'Wallet not synced yet'); + } + } + + // ── Shared helpers ── + + // Track pending transactions per connection that haven't been submitted yet. + // Keyed by serialized tx hex so untracking works after deserialization. + // On rejection/disconnect/abandon we revert the FINALIZED transaction: that + // releases the coins it spent in all three wallets and clears the pending + // entry `finalizeRecipe` registered for it. Reverting the recipe would leave + // that entry pending until its TTL. `feeOnly` marks a transaction this + // connection had balanced Dust-only under --approve-fees: only its submit + // counts as fee-only. + const pendingTxsByConnection = new Map; feeOnly: boolean }>>(); + + function trackPendingTx(connectionId: string, txHex: string, finalized: ledger.FinalizedTransaction, feeOnly = false): void { + let txMap = pendingTxsByConnection.get(connectionId); + if (!txMap) { + txMap = new Map(); + pendingTxsByConnection.set(connectionId, txMap); + } + // Start abandon timer — auto-revert if DApp never submits. + const timer = setTimeout(async () => { + txMap!.delete(txHex); + if (txMap!.size === 0) pendingTxsByConnection.delete(connectionId); + try { await facade.revert(finalized); } catch { /* best-effort */ } + notice(dim(` abandoned tx reverted (${connectionId})`)); + }, ABANDONED_TX_TIMEOUT_MS); + txMap.set(txHex, { finalized, timer, feeOnly }); + } + + function untrackPendingTx(connectionId: string, txHex: string): void { + const txMap = pendingTxsByConnection.get(connectionId); + if (!txMap) return; + const entry = txMap.get(txHex); + if (entry) { + clearTimeout(entry.timer); + txMap.delete(txHex); + } + if (txMap.size === 0) pendingTxsByConnection.delete(connectionId); + } + + /** Revert and clean up all pending transactions for a connection (disconnect). */ + async function revertPendingTxs(connectionId: string): Promise { + const txMap = pendingTxsByConnection.get(connectionId); + if (!txMap || txMap.size === 0) return; + pendingTxsByConnection.delete(connectionId); + for (const [, entry] of txMap) { + clearTimeout(entry.timer); + try { await facade.revert(entry.finalized); } catch { /* best-effort */ } + } + notice(dim(` reverted ${txMap.size} pending tx(s) on disconnect`)); + } + + function createTtl(): Date { + return new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000); + } + + /** Sign, prove (with timeout), and serialize a transaction recipe. + * Returns both the serialized hex and the finalized tx object (for tracking/revert). */ + async function processRecipe(recipe: any, tracker?: PhaseTracker): Promise<{ hex: string; finalized: ledger.FinalizedTransaction }> { + tracker?.start('signing'); + let signed: any; + try { + signed = await signRecipe(facade, recipe, keystore.signDataAsync); + } catch (err) { + // Release what balancing booked; nothing will be tracked for this recipe. + try { await facade.revert(recipe); } catch { /* best-effort */ } + // The transaction's own shape, not the wallet, is what can't be signed. + if (err instanceof PartlySignedTransactionError) throw createApiError('InvalidRequest', err.message); + throw err; + } + tracker?.start('proving'); + let timer: ReturnType | undefined; + let finalized: ledger.FinalizedTransaction; + const finalizing = facade.finalizeRecipe(signed); + try { + finalized = await Promise.race([ + finalizing, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('ZK proof generation timed out')), PROOF_TIMEOUT_MS); + }), + ]); + } catch (err) { + // No finalized transaction to track: release what balancing booked now, + // rather than leaving the coins held until the TTL. + try { await facade.revert(recipe); } catch { /* best-effort */ } + // A timed-out proof keeps running, and the SDK registers its finalized tx + // as pending when it lands; nobody will submit it, so revert that too. + finalizing.then((late) => facade.revert(late)).catch(() => { /* best-effort */ }); + throw err; + } finally { + clearTimeout(timer); + } + tracker?.complete(); + return { hex: toHex(finalized.serialize()), finalized }; + } + + /** + * Read a dApp's hex transaction at the given stage, as ledger 9 (the beta + * SDK's only ledger; it has no `adoptTransaction`). Bytes from another + * ledger version, or another stage, are the caller's mistake, so they come + * back as InvalidRequest. + */ + function adopt(txHex: string, stage: TStage): DAppTransaction[TStage] { + try { + const bytes = fromHex(txHex); + return (stage === 'Unbound' + ? ledger.Transaction.deserialize('signature', 'proof', 'pre-binding', bytes) + : ledger.Transaction.deserialize('signature', 'proof', 'binding', bytes)) as DAppTransaction[TStage]; + } catch (err) { + throw createApiError( + 'InvalidRequest', + `The transaction could not be read at stage ${stage} as this wallet's ledger version: ${extractErrorDetail(err)}`, + ); + } + } + + /** Prompt terminal approval for a write method. Throws Rejected on denial. */ + async function requireApproval( + method: string, + details: Array<{ label: string; value: string }> = [], + context?: RpcHandlerContext, + feeOnly = false, + ): Promise { + context?.notify('approval:pending', { method }); + const result = await promptApproval( + { method, network: networkConfig.networkId, details, dappName: context?.connectionId, feeOnly }, + approvalOptions, + ); + const outcome = result === 'reject' ? 'rejected' : 'approved'; + context?.notify('approval:resolved', { method, result: outcome }); + if (result === 'reject') { + throw createApiError('Rejected', approvalOptions.approveFees + ? `${OPERATOR_REJECTED_MESSAGE}: this fee wallet (--approve-fees) approves without the operator only paying the ` + + 'Dust fee for an agent\'s own transaction and submitting a transaction it balanced that way on the same connection' + : OPERATOR_REJECTED_MESSAGE); + } + } + + /** + * Fee-wallet mode (--approve-fees): refuse a dApp transaction unless paying + * its Dust fee is all this wallet would do to it. Signing an unbound recipe + * signs the dApp's own transaction, so Dust-only balancing alone does not + * keep the wallet to the fee (see fee-only-check.ts). + */ + function assertFeeOnly(txHex: string, stage: DAppTxStage, payFees: unknown): void { + if (payFees === false) { + throw createApiError('InvalidRequest', + 'This wallet is a fee wallet (--approve-fees): it only pays the Dust fee, so payFees: false leaves it nothing to do'); + } + let tx: FeeCheckTransaction; + try { + tx = readDAppTransaction(fromHex(txHex), stage); + } catch (err) { + throw createApiError('InvalidRequest', + `The transaction could not be read as a proven ledger-9 ${stage} transaction: ${extractErrorDetail(err)}`); + } + const reasons = feeOnlyRefusals(tx, keystore.getPublicKey()); + if (reasons.length > 0) { + throw createApiError('Rejected', + `This wallet is a fee wallet (--approve-fees) and pays only the Dust fee; it refuses this transaction because ${reasons.join('; ')}`); + } + } + + /** Refuse a dApp transaction the chain would refuse for its TTL, before anything is reserved for it. */ + function assertNotExpired(txHex: string, stage: DAppTxStage): void { + let expired: Array<{ segment: number; ttl: Date }>; + try { + expired = expiredIntents(readDAppTransaction(fromHex(txHex), stage), new Date()); + } catch (err) { + throw createApiError('InvalidRequest', extractErrorDetail(err)); + } + if (expired.length > 0) { + const which = expired.map(({ segment, ttl }) => `intent ${segment}'s TTL (${ttl.toISOString()})`).join(', '); + throw createApiError('InvalidRequest', `The transaction has expired: ${which} has passed. Build it again with a later TTL.`); + } + } + + /** Refuse an unsealed dApp transaction the wallet can't sign without breaking it. */ + function assertDAppTxSignable(txHex: string, balancesUnshielded: boolean): void { + try { + assertSignable(readDAppTransaction(fromHex(txHex), 'unsealed'), balancesUnshielded); + } catch (err) { + throw createApiError('InvalidRequest', extractErrorDetail(err)); + } + } + + /** + * Fee-wallet limits, checked before anything is booked: no more than + * `maxPending` balanced transactions may wait unsubmitted, and the total fee + * (the dApp's tx plus the wallet's balancing tx) may not exceed `maxFee`. + */ + function pendingCount(): number { + let pending = 0; + for (const [, txMap] of pendingTxsByConnection) pending += txMap.size; + return pending; + } + + function feeLimitError(reason: string) { + return createApiError('Rejected', `This wallet is a fee wallet (--approve-fees) and refuses this transaction: ${reason}`); + } + + // Fee-only balances between their limit check and being tracked as pending. + // Counted with the pending ones, so simultaneous requests can't all pass + // --max-pending while none of them is tracked yet. + let feeOnlyInFlight = 0; + + /** Take one of the --max-pending slots, synchronously. Returns the release; throws when none is left. */ + function reserveFeeOnlySlot(): () => void { + const reason = pendingLimitRefusal(pendingCount() + feeOnlyInFlight, feeLimits); + if (reason) throw feeLimitError(reason); + feeOnlyInFlight++; + let released = false; + return () => { + if (!released) { released = true; feeOnlyInFlight--; } + }; + } + + async function assertFeeWithinLimit(dappTx: DAppTransaction['Unbound'] | DAppTransaction['Finalized'], ttl: Date): Promise { + const fee = await withDustRetry(() => facade.estimateTransactionFee(dappTx, secretKeys.dustSecretKey, { ttl })); + notice(dim(` fee-only: estimated fee ${toDust(fee)} DUST (limit ${toDust(feeLimits.maxFeeSpecks)})`)); + const reason = feeLimitRefusal(fee, feeLimits); + if (reason) throw feeLimitError(reason); + } + + /** + * Balance a dApp's transaction. Under --approve-fees: Dust only, and only once + * `assertFeeOnly` passes, never falling back to a wider balance. Otherwise + * every token kind, or all but Dust when the dApp says `payFees: false`. + */ + async function balanceDAppTransaction( + method: 'balanceUnsealedTransaction' | 'balanceSealedTransaction', + stage: DAppTxStage, + params: Record, + context: RpcHandlerContext, + ): Promise<{ tx: string }> { + const txHex = String(params.tx ?? ''); + if (!txHex) { + throw createApiError('InvalidRequest', 'tx is required'); + } + assertWalletStarted(); + const payFees = (params.options as { payFees?: unknown } | undefined)?.payFees; + const feeOnly = approvalOptions.approveFees === true; + if (feeOnly) assertFeeOnly(txHex, stage, payFees); + const tokenKindsToBalance: TokenKindsToBalance = feeOnly + ? ['dust'] + : payFees === false ? ['shielded', 'unshielded'] : 'all'; + + const ttl = createTtl(); + const dappTx = stage === 'unsealed' ? adopt(txHex, 'Unbound') : adopt(txHex, 'Finalized'); + assertNotExpired(txHex, stage); + // Signing an unsealed transaction signs the dApp's part too; refuse one that can't be signed before booking anything. + if (stage === 'unsealed') { + assertDAppTxSignable(txHex, tokenKindsToBalance === 'all' || tokenKindsToBalance.includes('unshielded')); + } + const releaseSlot = feeOnly ? reserveFeeOnlySlot() : undefined; + try { + if (feeOnly) await assertFeeWithinLimit(dappTx, ttl); + + const tracker = makeTracker(method, context); + + tracker.start('approve'); + await requireApproval(method, inspectTxHex(txHex, stage), context, feeOnly); + + tracker.start('building'); + const balanceOptions = { ttl, tokenKindsToBalance }; + let recipe: any; + if (stage === 'unsealed') { + const unsealedTx = dappTx as DAppTransaction['Unbound']; + recipe = await withDustRetry(() => facade.balanceUnboundTransaction(unsealedTx, secretKeys, balanceOptions)); + } else { + const sealedTx = dappTx as DAppTransaction['Finalized']; + recipe = await withDustRetry(() => facade.balanceFinalizedTransaction(sealedTx, secretKeys, balanceOptions)); + } + const { hex, finalized } = await processRecipe(recipe, tracker); + trackPendingTx(context.connectionId, hex, finalized, feeOnly); + context.metadata.phases = tracker.getTimings(); + return { tx: hex }; + } finally { + releaseSlot?.(); + } + } + + /** Encode an SDK address object to bech32m string. */ + function encodeAddress(address: any): string { + return MidnightBech32m.encode(networkId, address).asString(); + } + + /** A token amount the dApp gives: a whole number of the smallest unit, above 0. */ + function parsePositiveAmount(value: unknown, field: string): bigint { + let amount: bigint; + try { + if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'bigint') throw new TypeError(); + amount = BigInt(value); + } catch { + throw createApiError('InvalidRequest', `Invalid ${field}: "${String(value)}" — must be a whole number of the token's smallest unit`); + } + if (amount <= 0n) throw createApiError('InvalidRequest', `Invalid ${field}: ${amount} — must be greater than 0`); + return amount; + } + + function parseKind(kind: unknown, of: 'input' | 'output'): 'shielded' | 'unshielded' { + if (kind !== 'shielded' && kind !== 'unshielded') { + throw createApiError('InvalidRequest', `Invalid ${of} kind: "${kind}" — must be "shielded" or "unshielded"`); + } + return kind; + } + + function parseTokenType(type: unknown): string { + if (typeof type !== 'string' || !/^[0-9a-fA-F]{64}$/.test(type)) { + throw createApiError('InvalidRequest', `Invalid token type: "${type}" — must be 64 hex characters`); + } + return type; + } + + /** DesiredInput[] → CombinedSwapInputs { shielded?: Record, unshielded?: Record }. */ + function parseDesiredInputs(inputs: any[]): Record> { + if (!Array.isArray(inputs)) throw createApiError('InvalidRequest', 'desiredInputs must be an array'); + const swapInputs: Record> = {}; + for (const input of inputs) { + const kind = parseKind(input?.kind, 'input'); + swapInputs[kind] ??= {}; + swapInputs[kind][parseTokenType(input.type)] = parsePositiveAmount(input.value, 'value'); + } + return swapInputs; + } + + /** + * Convert DApp Connector DesiredOutput[] to SDK CombinedTokenTransfer[]. + * + * Field mapping: + * DesiredOutput.kind ('shielded'|'unshielded') → CombinedTokenTransfer.type + * DesiredOutput.type (hex TokenType) → TokenTransfer.type (RawTokenType) + * DesiredOutput.value (bigint or string) → TokenTransfer.amount (bigint) + * DesiredOutput.recipient (bech32m string) → TokenTransfer.receiverAddress (Address object) + */ + function parseDesiredOutputs(outputs: any[]): any[] { + if (!Array.isArray(outputs)) throw createApiError('InvalidRequest', 'desiredOutputs must be an array'); + const grouped: Record = {}; + + for (const output of outputs) { + const kind = parseKind(output?.kind, 'output'); + grouped[kind] ??= []; + const type = parseTokenType(output.type); + const amount = parsePositiveAmount(output.value, 'value'); + + let receiverAddress: any; + try { + receiverAddress = MidnightBech32m.parse(String(output.recipient)) + .decode(kind === 'unshielded' ? UnshieldedAddress : ShieldedAddress, networkId); + } catch (err) { + throw createApiError('InvalidRequest', + `Invalid recipient: "${output.recipient}" is not ${kind === 'unshielded' ? 'an' : 'a'} ${kind} address on ${networkConfig.networkId} (${extractErrorDetail(err)})`); + } + + grouped[kind].push({ + type, + receiverAddress, + amount, + }); + } + + return Object.entries(grouped).map(([kind, transfers]) => ({ + type: kind, + outputs: transfers, + })); + } + + /** Create a phase tracker wired to callbacks and context notifications. */ + function makeTracker(method: string, context?: RpcHandlerContext): PhaseTracker { + return createPhaseTracker({ + onStart: (phase) => { + const connId = context?.connectionId ?? 'unknown'; + callbacks?.onPhaseStart?.(connId, method, phase); + context?.notify('progress', { method, phase, status: 'started' }); + }, + onComplete: (phase, durationMs) => { + const connId = context?.connectionId ?? 'unknown'; + callbacks?.onPhaseComplete?.(connId, method, phase, durationMs); + context?.notify('progress', { method, phase, status: 'completed', durationMs }); + }, + }); + } + + /** Check if dust coins are currently available via the cached state. */ + function isDustAvailable(): boolean { + return latestState !== undefined && hasDustAvailable(latestState); + } + + /** + * Waits for a Dust coin to show in the wallet state: `already` there, + * `appeared` during the wait, or `timeout`. + */ + async function waitForDust(timeoutMs: number): Promise<'already' | 'appeared' | 'timeout'> { + return new Promise((resolve) => { + if (isDustAvailable()) { resolve('already'); return; } + const sub = facade.state().pipe( + rx.filter(() => isDustAvailable()), + rx.take(1), + rx.timeout(timeoutMs), + ).subscribe({ + next: () => { sub.unsubscribe(); resolve('appeared'); }, + error: () => { sub.unsubscribe(); resolve('timeout'); }, + }); + }); + } + + /** A Dust shortage that waiting didn't fix, with what is holding the Dust (if anything is) and what to do. */ + function dustExhaustedError(err: unknown) { + const pending = pendingCount(); + if (pending === 0) { + // Nothing is reserved, so nothing will come free: the wallet's Dust is simply less than the fee. + return createApiError('InternalError', + `The wallet has no Dust available that covers this transaction's fee (${extractErrorDetail(err)}), and no balanced ` + + 'transaction is holding any back on this server. Dust builds up with time from the NIGHT registered for it: ' + + 'retry later, or register more NIGHT for Dust generation.'); + } + return createApiError('InternalError', + `No Dust is free to pay the fee (${extractErrorDetail(err)}). Each balanced transaction reserves a whole Dust coin ` + + `until it is submitted and on chain, or released when its connection closes or it expires; ${pending} ` + + 'balanced transaction(s) are waiting to be submitted on this server. Retry once they settle. To pay for more ' + + 'transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.'); + } + + /** The fee takes more Dust than the wallet's NIGHT generates in the time a request waits (`waitMs` null: within a day). */ + function dustTooFarError(have: bigint, needed: bigint, waitMs: number | null) { + const when = waitMs === null + ? "Its registered NIGHT won't generate that within a day: register more NIGHT for Dust generation." + : `Its registered NIGHT generates the rest in ${formatWait(waitMs)}: retry then, or register more NIGHT to get there sooner.`; + return createApiError('InternalError', + `Not enough Dust available for this transaction's fee: the wallet has ${roughDust(have)} DUST and the fee takes ${roughDust(needed, true)}. ${when}`); + } + + /** + * The wait for a fee the wallet's Dust doesn't cover yet, when that is all + * there is to wait for: the shortage says what the wallet is short by, and + * nothing balanced here is holding Dust back. Undefined otherwise. + */ + function dustGrowthWait(err: unknown): DustWaitPlan | undefined { + if (latestState === undefined || pendingCount() > 0) return undefined; + return planDustWait(err, latestState.dust, new Date()); + } + + /** + * Retries a facade call that fails for lack of Dust. When the shortage says + * what the fee takes and the wallet simply has less, the wait is the time + * its NIGHT takes to generate the rest: waited out when it fits in + * `dustWaitMs`, refused at once with that time when it doesn't. Otherwise a + * coin may come free or grow, and a few short waits find out. + */ + async function withDustRetry(fn: () => Promise): Promise { + let waitedForGrowthMs = 0; + let attempt = 1; + for (;;) { + try { + return await fn(); + } catch (err: any) { + const msg = String(err?.message ?? err ?? ''); + if (!isDustShortage(err)) throw err; + const growth = dustGrowthWait(err); + if (growth) { + const { have, needed, waitMs } = growth; + if (waitMs === null || waitedForGrowthMs + waitMs > dustWaitMs) throw dustTooFarError(have, needed, waitMs); + notice(dim(` Dust: ${roughDust(have)} of the ${roughDust(needed, true)} DUST this fee takes; waiting ${formatWait(waitMs)} for the rest...`)); + await sleep(waitMs); + waitedForGrowthMs += waitMs; + continue; + } + if (attempt >= DUST_RETRY_ATTEMPTS) throw dustExhaustedError(err); + notice(dim(` dust unavailable, waiting for recovery (${attempt}/${DUST_RETRY_ATTEMPTS})... [${msg.slice(0, 60)}]`)); + // A coin that comes free during the wait (its transaction landed) is + // tried at once. A coin that was there all along was too small for + // the fee, and a wait that ran out found none: either way it needs + // time, so the delay passes before the next attempt. + if (await waitForDust(DUST_RETRY_DELAY_MS) !== 'appeared') await sleep(DUST_RETRY_DELAY_MS); + attempt++; + } + } + } + + // ── Handler map — all 18 ConnectedAPI methods ── + + const handlers: Record = { + + // ── Handshake (1) ── + + connect: async (params) => { + const requestedNetwork = String(params.networkId ?? ''); + if (requestedNetwork.toLowerCase() !== networkConfig.networkId.toLowerCase()) { + throw createApiError('InvalidRequest', + `Network mismatch: wallet is on ${networkConfig.networkId}, requested ${requestedNetwork}`); + } + return { networkId: networkConfig.networkId }; + }, + + // ── Read-Only Methods (9) — auto-approved ── + + getUnshieldedBalances: async () => { + return getState().unshielded.balances; + }, + + getShieldedBalances: async () => { + return getState().shielded.balances; + }, + + getDustBalance: async () => { + const state = getState(); + const balance = state.dust.balance(new Date()); + // API expects { cap, balance }. Exact cap requires estimating from + // registered NIGHT UTXO dust generation potential. For v1, use balance + // as approximation — both represent current dust availability. + return { cap: balance, balance }; + }, + + getUnshieldedAddress: async () => { + const state = getState(); + return { unshieldedAddress: encodeAddress(state.unshielded.address) }; + }, + + getShieldedAddresses: async () => { + const state = getState(); + const addr = state.shielded.address; + return { + shieldedAddress: encodeAddress(addr), + shieldedCoinPublicKey: addr.coinPublicKeyString(), + shieldedEncryptionPublicKey: addr.encryptionPublicKeyString(), + }; + }, + + getDustAddress: async () => { + const state = getState(); + return { dustAddress: encodeAddress(state.dust.address) }; + }, + + getTxHistory: async (params) => { + getState(); + const pageNumber = (params.pageNumber ?? 0) as number; + const pageSize = (params.pageSize ?? 20) as number; + if (!Number.isSafeInteger(pageNumber) || pageNumber < 0) { + throw createApiError('InvalidRequest', `Invalid pageNumber: ${JSON.stringify(pageNumber)} — must be a whole number, 0 or more`); + } + if (!Number.isSafeInteger(pageSize) || pageSize < 1) { + throw createApiError('InvalidRequest', `Invalid pageSize: ${JSON.stringify(pageSize)} — must be a whole number, 1 or more`); + } + const start = pageNumber * pageSize; + const entries = await facade.getAllFromTxHistory(); + const page: HistoryEntry[] = []; + // One at a time: a page can be large, and each partial success is an indexer query. + for (const entry of entries.slice(start, start + pageSize)) { + if (entry.lifecycle.status !== 'finalized' || entry.status !== 'PARTIAL_SUCCESS') { + page.push(toHistoryEntry(entry)); + continue; + } + try { + page.push(toHistoryEntry(entry, await fetchPartialSuccessSegments(networkConfig.indexer, entry.hash))); + } catch (err) { + throw createApiError('InternalError', extractErrorDetail(err)); + } + } + return page; + }, + + getConfiguration: async () => { + return { + indexerUri: networkConfig.indexer, + indexerWsUri: networkConfig.indexerWS, + proverServerUri: networkConfig.proofServer, + substrateNodeUri: networkConfig.node, + networkId: networkConfig.networkId, + }; + }, + + getConnectionStatus: async () => { + // Return the lowercase abstractions form (e.g. 'undeployed'), matching + // what addresses are encoded with. dApps that round-trip this back into + // setNetworkId() and then decode an address would otherwise hit a + // case-sensitivity mismatch — bech32m HRPs are lowercase, so encoder + // and getConnectionStatus must agree on the lowercase form. + return { status: 'connected', networkId }; + }, + + // ── Write Methods (7) — require terminal approval ── + + makeTransfer: async (params, context) => { + const outputs = params.desiredOutputs as any[]; + if (!Array.isArray(outputs) || outputs.length === 0) { + throw createApiError('InvalidRequest', 'desiredOutputs must be a non-empty array'); + } + assertWalletStarted(); + const combinedTransfers = parseDesiredOutputs(outputs); + + const tracker = makeTracker('makeTransfer', context); + + const details = outputs.map((o, i) => ({ + label: `Output ${i + 1}`, + value: `${o.value} → ${String(o.recipient).slice(0, 20)}... (${o.kind})`, + })); + tracker.start('approve'); + await requireApproval('makeTransfer', details, context); + + tracker.start('building'); + const payFees = (params.options as any)?.payFees ?? true; + const recipe = await withDustRetry(() => facade.transferTransaction(combinedTransfers, secretKeys, { + ttl: createTtl(), + payFees, + })); + const { hex, finalized } = await processRecipe(recipe, tracker); + trackPendingTx(context.connectionId, hex, finalized); + context.metadata.phases = tracker.getTimings(); + return { tx: hex }; + }, + + submitTransaction: async (params, context) => { + const txHex = String(params.tx ?? ''); + if (!txHex) { + throw createApiError('InvalidRequest', 'tx is required'); + } + assertWalletStarted(); + + const tracker = makeTracker('submitTransaction', context); + + // Submit is the irreversible action: prompt, unless under --approve-fees + // it is a transaction this connection had balanced fee-only. + const feeOnly = approvalOptions.approveFees === true + && pendingTxsByConnection.get(context.connectionId)?.get(txHex)?.feeOnly === true; + tracker.start('approve'); + try { + await requireApproval('submitTransaction', inspectTxHex(txHex, 'sealed'), context, feeOnly); + } catch (err) { + // Rejection — revert to release dust coins from pending. + const txMap = pendingTxsByConnection.get(context.connectionId); + const entry = txMap?.get(txHex); + if (entry) { + try { await facade.revert(entry.finalized); } catch { /* best-effort */ } + } + untrackPendingTx(context.connectionId, txHex); + throw err; + } + + // Adopt for submission (the chain doesn't need object identity) + const sealedTx = adopt(txHex, 'Finalized'); + tracker.start('submitting'); + try { + const txHash = await facade.submitTransaction(sealedTx); + tracker.complete(); + // Tx submitted successfully — untrack (coins are now spent, not pending) + untrackPendingTx(context.connectionId, txHex); + context.metadata.phases = tracker.getTimings(); + // Return txHash for server logging (onResponse can read it from result) + return { txHash }; + } catch (submitErr: unknown) { + tracker.complete(); + // Revert pending tx to release locked dust coins + const txMap = pendingTxsByConnection.get(context.connectionId); + const entry = txMap?.get(txHex); + if (entry) { + try { await facade.revert(entry.finalized); } catch { /* best-effort */ } + } + untrackPendingTx(context.connectionId, txHex); + // Re-throw with full detail so the RPC layer can forward it + const detail = extractErrorDetail(submitErr); + const enriched = new Error(`Transaction submission failed: ${detail}`); + enriched.cause = submitErr; + throw enriched; + } + }, + + balanceUnsealedTransaction: (params, context) => + balanceDAppTransaction('balanceUnsealedTransaction', 'unsealed', params, context), + + balanceSealedTransaction: (params, context) => + balanceDAppTransaction('balanceSealedTransaction', 'sealed', params, context), + + makeIntent: async (params, context) => { + const desiredInputs = params.desiredInputs as any[]; + const desiredOutputs = params.desiredOutputs as any[]; + const intentOptions = params.options as any; + + if (!intentOptions) { + throw createApiError('InvalidRequest', 'options is required for makeIntent'); + } + assertWalletStarted(); + const swapInputs = parseDesiredInputs(desiredInputs ?? []); + const combinedOutputs = parseDesiredOutputs(desiredOutputs ?? []); + + const tracker = makeTracker('makeIntent', context); + + tracker.start('approve'); + await requireApproval('makeIntent', [], context); + + tracker.start('building'); + + const recipe = await withDustRetry(() => facade.initSwap(swapInputs, combinedOutputs, secretKeys, { + ttl: createTtl(), + payFees: intentOptions.payFees ?? true, + })); + const { hex, finalized } = await processRecipe(recipe, tracker); + trackPendingTx(context.connectionId, hex, finalized); + context.metadata.phases = tracker.getTimings(); + return { tx: hex }; + }, + + signData: async (params, context) => { + const data = String(params.data ?? ''); + const signOptions = params.options as any; + + if (!data || !signOptions?.encoding) { + throw createApiError('InvalidRequest', 'data and options.encoding are required'); + } + if (signOptions.keyType && signOptions.keyType !== 'unshielded') { + throw createApiError('InvalidRequest', `Unsupported keyType: "${signOptions.keyType}" — only "unshielded" is supported`); + } + + // Decode before asking the operator: a payload that can't be read is the dApp's mistake. + let payload: Uint8Array; + try { + payload = decodeSignPayload(data, signOptions.encoding); + } catch (err) { + throw createApiError('InvalidRequest', (err as Error).message); + } + + await requireApproval('signData', [ + { label: 'Encoding', value: signOptions.encoding }, + { label: 'Data', value: data.length > 64 ? data.slice(0, 64) + '...' : data }, + ], context); + + // Both come back as { tag, value }: the hex is in `value`, and the + // tag names the scheme the connector API reports. + const signature = await keystore.signDataAsync(signedMessageBytes(payload)); + const verifyingKey = keystore.getPublicKey(); + + return { + data, + signature: signature.value, + verifyingKey: verifyingKey.value, + scheme: signatureScheme(signature.tag), + }; + }, + + // ── Proving Provider (1) ── + + getProvingProvider: async () => { + // For v1, we use the proof server from network config. + // The DApp's keyMaterialProvider is not used over JSON-RPC — the proof + // server handles proving directly. WASM proving with DApp-provided key + // material would require bidirectional RPC (future enhancement). + return { provingProvider: 'ready', proverServerUri: networkConfig.proofServer }; + }, + + // ── Permission (1) ── + + hintUsage: async (params) => { + const methods = params.methodNames ?? []; + // Names only: they are printed to the operator's terminal as they come. + if (!Array.isArray(methods) || !methods.every((m) => typeof m === 'string' && /^[A-Za-z]\w*$/.test(m))) { + throw createApiError('InvalidRequest', 'methodNames must be an array of connector method names'); + } + notice(dim(` DApp hints usage: ${methods.join(', ')}`)); + }, + }; + + function dispose(): void { + subscription.unsubscribe(); + // Clear all abandon timers + for (const [, txMap] of pendingTxsByConnection) { + for (const [, entry] of txMap) { + clearTimeout(entry.timer); + } + } + pendingTxsByConnection.clear(); + } + + function hasPendingTxs(): boolean { + for (const [, txMap] of pendingTxsByConnection) { + if (txMap.size > 0) return true; + } + return false; + } + + return { handlers, revertPendingTxs, hasPendingTxs, dispose }; +} diff --git a/packages/engine-beta/src/derivation.ts b/packages/engine-beta/src/derivation.ts new file mode 100644 index 00000000..00ba196e --- /dev/null +++ b/packages/engine-beta/src/derivation.ts @@ -0,0 +1,41 @@ +import { HDWallet, Roles } from '@midnightntwrk/wallet-sdk-hd'; + +/** + * Derive a key from the HD wallet for a given role. + * All derivations use account=0, index=0. + * Path: m/44'/2400'/0'//0 + */ +function deriveKey(seedBuffer: Buffer, role: typeof Roles[keyof typeof Roles]): Uint8Array { + const hdResult = HDWallet.fromSeed(seedBuffer); + if (hdResult.type !== 'seedOk') { + throw new Error('Invalid seed for HD wallet'); + } + + const derivation = hdResult.hdWallet.selectAccount(0).selectRole(role).deriveKeyAt(0); + if (derivation.type === 'keyOutOfBounds') { + throw new Error('Key derivation out of bounds'); + } + + return derivation.key; +} + +/** + * Derive shielded (Zswap) seed for ZK proofs. + */ +export function deriveShieldedSeed(seedBuffer: Buffer): Uint8Array { + return deriveKey(seedBuffer, Roles.Zswap); +} + +/** + * Derive unshielded (NightExternal) seed for NIGHT transfers. + */ +export function deriveUnshieldedSeed(seedBuffer: Buffer): Uint8Array { + return deriveKey(seedBuffer, Roles.NightExternal); +} + +/** + * Derive dust seed for fee token generation. + */ +export function deriveDustSeed(seedBuffer: Buffer): Uint8Array { + return deriveKey(seedBuffer, Roles.Dust); +} diff --git a/packages/engine-beta/src/derive-address.ts b/packages/engine-beta/src/derive-address.ts new file mode 100644 index 00000000..08fead2a --- /dev/null +++ b/packages/engine-beta/src/derive-address.ts @@ -0,0 +1,101 @@ +// Address derivation helper — wraps HD derivation + keystore + PublicKey +// into a single call returning the bech32m address string. + +import { HDWallet, Roles } from '@midnightntwrk/wallet-sdk-hd'; +import { createKeystore, PublicKey } from '@midnightntwrk/wallet-sdk-unshielded-wallet'; +import { + MidnightBech32m, + ShieldedAddress, + ShieldedCoinPublicKey, + ShieldedEncryptionPublicKey, +} from '@midnightntwrk/wallet-sdk-address-format'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { type NetworkName, getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; +import { deriveShieldedSeed } from './derivation.ts'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; + +/** + * Derive an unshielded address from a seed buffer, network, and optional key index. + * Path: m/44'/2400'/0'/NightExternal/ + * + * Returns the bech32m address string (e.g., mn_addr_preprod1...). + */ +export function deriveUnshieldedAddress( + seedBuffer: Buffer, + networkName: NetworkName, + keyIndex: number = 0, +): string { + const networkId = networkIdForName(networkName); + + const hdResult = HDWallet.fromSeed(seedBuffer); + if (hdResult.type !== 'seedOk') { + throw new Error('Invalid seed for HD wallet'); + } + + const derivation = hdResult.hdWallet + .selectAccount(0) + .selectRole(Roles.NightExternal) + .deriveKeyAt(keyIndex); + + if (derivation.type === 'keyOutOfBounds') { + throw new Error(`Key index ${keyIndex} out of bounds`); + } + + const keystore = createKeystore({ kind: 'schnorr', secret: derivation.key }, networkId); + const publicKey = PublicKey.fromKeyStore(keystore); + return publicKey.address; +} + +/** + * Derive unshielded addresses for all supported networks from a single seed. + * Returns a map of network name → bech32m address string. + */ +export function deriveAllAddresses( + seedBuffer: Buffer, + keyIndex: number = 0, +): Record { + const addresses = {} as Record; + for (const name of getValidNetworkNames()) { + addresses[name as NetworkName] = deriveUnshieldedAddress(seedBuffer, name as NetworkName, keyIndex); + } + return addresses; +} + +/** + * Derive shielded (Zswap) addresses for all supported networks from a single seed. + * The underlying keys are network-independent — only the bech32m prefix changes + * per network (e.g. mn_shield-addr_preprod1..., mn_shield-addr_preview1...). + * + * Returns a map of network name → bech32m shielded address string. + */ +export function deriveAllShieldedAddresses( + seedBuffer: Buffer, +): Record { + const address = deriveShieldedAddress(seedBuffer); + const out = {} as Record; + for (const name of getValidNetworkNames()) { + const networkId = networkIdForName(name as NetworkName); + out[name as NetworkName] = MidnightBech32m.encode(networkId, address).asString(); + } + return out; +} + +/** The shielded address on one network, as its bech32m string. */ +export function deriveShieldedAddressString(seedBuffer: Buffer, networkName: NetworkName): string { + return MidnightBech32m.encode(networkIdForName(networkName), deriveShieldedAddress(seedBuffer)).asString(); +} + +/** + * Derive the raw `ShieldedAddress` (SDK type) from a seed. Cheap — pure + * key derivation, no facade or network needed. Use when you need an + * address as an SDK call argument (e.g. `transferTransaction`'s + * `receiverAddress` field). + */ +export function deriveShieldedAddress(seedBuffer: Buffer): ShieldedAddress { + const shieldedSeed = deriveShieldedSeed(seedBuffer); + const keys = ledger.ZswapSecretKeys.fromSeed(shieldedSeed); + return new ShieldedAddress( + new ShieldedCoinPublicKey(Buffer.from(keys.coinPublicKey, 'hex')), + new ShieldedEncryptionPublicKey(Buffer.from(keys.encryptionPublicKey, 'hex')), + ); +} diff --git a/packages/engine-beta/src/dust-collapse.ts b/packages/engine-beta/src/dust-collapse.ts new file mode 100644 index 00000000..bb7aa3ae --- /dev/null +++ b/packages/engine-beta/src/dust-collapse.ts @@ -0,0 +1,107 @@ +// Collapse the foreign portion of the dust generation Merkle tree, keeping the +// wallet's own generation leaves. This shrinks the persisted dust state and its +// restore time without changing balances or spendability — the client-side form +// of the optimization in `midnight-wallet` issue #639. +// +// Pure logic only: no I/O, no console. Callers decide when to collapse and how +// to source the owned index set (owner-match during event replay). + +import * as ledger from '@midnightntwrk/ledger-v9'; + +export interface CollapseOutcome { + /** The collapsed state, or the original state if collapse was skipped/rejected. */ + state: ledger.DustLocalState; + /** True iff a verified collapse was applied. */ + collapsed: boolean; + /** Number of foreign ranges collapsed. */ + rangesCollapsed: number; + /** Why collapse was skipped or rolled back (diagnostics; undefined on success). */ + reason?: string; +} + +/** + * Compute the contiguous foreign index ranges of the generation tree: every gap + * in `[0, frontier)` not occupied by an owned generation index. Indices outside + * `[0, frontier)` and duplicates are ignored. Pure. + */ +export function computeForeignRanges( + ownedIndices: Iterable, + frontier: bigint, +): Array<[bigint, bigint]> { + if (frontier <= 0n) return []; + const owned = [...new Set(ownedIndices)] + .filter((i) => i >= 0n && i < frontier) + .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + + const ranges: Array<[bigint, bigint]> = []; + let prev = -1n; // highest index already accounted for + for (const idx of owned) { + if (idx > prev + 1n) ranges.push([prev + 1n, idx - 1n]); + prev = idx; + } + if (frontier - 1n > prev) ranges.push([prev + 1n, frontier - 1n]); + return ranges; +} + +/** + * Collapse the foreign ranges of the dust generation tree while keeping the + * wallet's own generation leaves (`ownedIndices`) intact. + * + * Safety guard: after collapsing, the state must still report the same + * `walletBalance` and generation-tree root as the input. If it doesn't — e.g. an + * owned index was misclassified and collapsed — the original, uncollapsed state + * is returned instead. A logic error can therefore only cost the size + * optimization, never balance correctness or spendability. + */ +export function collapseForeignGenerations( + state: ledger.DustLocalState, + ownedIndices: Iterable, + frontier: bigint, +): CollapseOutcome { + const ranges = computeForeignRanges(ownedIndices, frontier); + if (ranges.length === 0) { + return { state, collapsed: false, rangesCollapsed: 0, reason: 'nothing-foreign' }; + } + + // Reference values the collapsed state must still reproduce. Use the state's + // own sync time so the balance comparison is time-invariant. + const when = state.syncTime instanceof Date ? state.syncTime : new Date(String(state.syncTime)); + let refBalance: bigint; + let refRoot: bigint | undefined; + try { + refBalance = state.walletBalance(when); + refRoot = state.generatingTreeRoot(); + } catch (err) { + return { state, collapsed: false, rangesCollapsed: 0, reason: `no-reference: ${(err as Error).message}` }; + } + + let collapsed = state; + try { + for (const [start, end] of ranges) { + collapsed = collapsed.collapseGenerationTree(start, end); + } + } catch (err) { + return { state, collapsed: false, rangesCollapsed: 0, reason: `collapse-threw: ${(err as Error).message}` }; + } + + // Safety guard — a mis-collapse of an owned leaf must roll back. `walletBalance` + // is the primary check; the tree root is a cheap sanity check (a collapse + // preserves the root by construction, so this only catches a deeper bug, not a + // mis-collapse). The load-bearing extra check is that every owned UTXO still + // resolves its generation info: a pruned owned leaf breaks this even when the + // balance happens to be unaffected (e.g. a leaf contributing 0 dust at syncTime). + try { + if (collapsed.walletBalance(when) !== refBalance || collapsed.generatingTreeRoot() !== refRoot) { + return { state, collapsed: false, rangesCollapsed: 0, reason: 'guard-mismatch' }; + } + for (const utxo of collapsed.utxos) { + if (collapsed.generationInfo(utxo) === undefined) { + return { state, collapsed: false, rangesCollapsed: 0, reason: 'guard-utxo-generation-missing' }; + } + } + } catch (err) { + return { state, collapsed: false, rangesCollapsed: 0, reason: `guard-threw: ${(err as Error).message}` }; + } + + return { state: collapsed, collapsed: true, rangesCollapsed: ranges.length }; +} diff --git a/packages/engine-beta/src/dust-direct-cache.ts b/packages/engine-beta/src/dust-direct-cache.ts new file mode 100644 index 00000000..09f30bbc --- /dev/null +++ b/packages/engine-beta/src/dust-direct-cache.ts @@ -0,0 +1,183 @@ +// Cache for the indexer-direct dust reader. +// +// Persists a serialized `DustLocalState` + the last event id we applied to +// disk, keyed by (network, dust public key). On next run we restore the state +// and resume the subscription from `lastAppliedEventId + 1` — delta-sync +// instead of re-reading the full event history. +// +// Security: the cached state contains owned UTXOs but NOT the dust secret +// key. Same sensitivity as the wallet file (mode 0o600). + +import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { randomBytes } from 'node:crypto'; + +import * as ledger from '@midnightntwrk/ledger-v9'; + +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { deriveDustSeed } from './derivation.ts'; +import { type DustRetention } from './dust-direct.ts'; +import { dustCacheDir, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; + +// v2 added the retention fields (owned generation indices + frontier) that the +// generation-tree collapse needs. v1 caches lack them and are invalidated, so +// they re-sync once and come back collapsed. +// v3: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis +// hash, so the chain-id guard can't keep a ledger-8 cache off a ledger-9 chain. +const DUST_CACHE_VERSION = 3; + +interface DustCacheFile { + version: number; + network: string; + dustPublicKeyHex: string; + lastAppliedEventId: number; + /** Genesis block hash — see wallet-cache.ts for the rationale. Optional for back-compat. */ + chainId?: string; + timestamp: string; + dustState: string; // hex-encoded DustLocalState.serialize() + /** Generation-tree indices owned by this wallet (never collapsed). */ + ownedGenerationIndices: number[]; + /** Next-free generation index the state has reached. */ + generationFrontier: number; +} + +export interface DustCacheEntry { + state: ledger.DustLocalState; + lastAppliedEventId: number; + retention: DustRetention; +} + +const EMPTY_RETENTION: DustRetention = { ownedGenerationIndices: [], generationFrontier: 0 }; + +/** Normalize a DustPublicKey (bigint) to a fixed-width 64-char hex string. */ +export function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string { + return publicKey.toString(16).padStart(64, '0'); +} + +/** + * Derive the dust public key (as hex) from a wallet seed. Convenience for + * callers that want to look up dust-direct cache entries by wallet rather + * than by raw public key. + */ +export function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string { + const dustSeed = deriveDustSeed(seedBuffer); + const sk = ledger.DustSecretKey.fromSeed(dustSeed); + return dustPublicKeyHex(sk.publicKey); +} + + +/** + * Load a cached DustLocalState for the given (network, dust pubkey). + * Returns null if missing, corrupt, version-mismatched, or network/pubkey-mismatched. + */ +export function loadDustCache( + network: string, + pubkeyHex: string, + cacheDir?: string, +): DustCacheEntry | null { + const path = getDustCachePath(network, pubkeyHex, cacheDir); + if (!existsSync(path)) return null; + + try { + const parsed: DustCacheFile = JSON.parse(readFileSync(path, 'utf-8')); + if (parsed.version !== DUST_CACHE_VERSION) return null; + if (parsed.network !== network) return null; + if (parsed.dustPublicKeyHex !== pubkeyHex) return null; + if (typeof parsed.lastAppliedEventId !== 'number') return null; + if (typeof parsed.dustState !== 'string') return null; + if (!Array.isArray(parsed.ownedGenerationIndices)) return null; + if (typeof parsed.generationFrontier !== 'number') return null; + + const bytes = Buffer.from(parsed.dustState, 'hex'); + const state = ledger.DustLocalState.deserialize(bytes); + return { + state, + lastAppliedEventId: parsed.lastAppliedEventId, + retention: { + ownedGenerationIndices: parsed.ownedGenerationIndices, + generationFrontier: parsed.generationFrontier, + }, + }; + } catch { + return null; + } +} + +/** + * Serialize a DustLocalState + lastAppliedEventId to disk atomically. + */ +export function saveDustCache( + network: string, + pubkeyHex: string, + state: ledger.DustLocalState, + lastAppliedEventId: number, + cacheDir?: string, + chainId?: string, + retention: DustRetention = EMPTY_RETENTION, +): void { + const data: DustCacheFile = { + version: DUST_CACHE_VERSION, + network, + dustPublicKeyHex: pubkeyHex, + lastAppliedEventId, + timestamp: new Date().toISOString(), + dustState: Buffer.from(state.serialize()).toString('hex'), + ownedGenerationIndices: retention.ownedGenerationIndices, + generationFrontier: retention.generationFrontier, + ...(chainId ? { chainId } : {}), + }; + + const path = getDustCachePath(network, pubkeyHex, cacheDir); + const dir = dirname(path); + + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + } + + const tmpPath = path + `.tmp.${randomBytes(4).toString('hex')}`; + try { + writeFileSync(tmpPath, JSON.stringify(data), { mode: FILE_MODE }); + renameSync(tmpPath, path); + } catch (err) { + try { unlinkSync(tmpPath); } catch { /* best-effort */ } + throw err; + } +} + +/** + * Wipe every dust-direct cache file for a network whose stored chainId + * doesn't match the chain's current genesis hash. Paired with + * `validateWalletCacheChainId` — both get called at command startup. + * Returns wiped paths. + */ +export function validateDustCacheChainId( + network: string, + currentChainId: string | null, + cacheDir?: string, +): string[] { + // Caller fetches the chain's current genesis hash once and passes it in. + // A null hash (node unreachable) skips validation — proceed best-effort. + if (!currentChainId) return []; + + const dir = dustCacheDir(network, cacheDir); + if (!existsSync(dir)) return []; + + const wiped: string[] = []; + let entries: string[]; + try { entries = readdirSync(dir); } catch { return []; } + + for (const file of entries) { + if (!file.startsWith('dust-') || !file.endsWith('.json')) continue; + const path = join(dir, file); + try { + const parsed: DustCacheFile = JSON.parse(readFileSync(path, 'utf-8')); + if (!parsed.chainId) continue; // legacy — back-compat + if (parsed.chainId !== currentChainId) { + unlinkSync(path); + wiped.push(path); + } + } catch { /* skip */ } + } + return wiped; +} + diff --git a/packages/engine-beta/src/dust-direct.ts b/packages/engine-beta/src/dust-direct.ts new file mode 100644 index 00000000..d462fdc1 --- /dev/null +++ b/packages/engine-beta/src/dust-direct.ts @@ -0,0 +1,255 @@ +// Direct-from-indexer dust balance reader. +// +// Bypasses the dust-wallet SDK's sync machinery (which hangs on preprod due to +// an `isConnected` predicate that never flips for idle wallets). Subscribes to +// `dustLedgerEvents(id: 0)` ourselves, deserializes each raw hex event via +// `ledger.Event.deserialize`, replays them into a fresh `DustLocalState`, then +// reads `walletBalance(now)`. +// +// The SDK's dust wallet does the same thing internally — we just don't wait on +// the cosmetic `isConnected` flag. + +import WebSocket from 'ws'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { collapseForeignGenerations } from './dust-collapse.ts'; +import { + INITIAL_NIGHT_DUST_RATIO, + INITIAL_GENERATION_DECAY_RATE, + INITIAL_DUST_GRACE_PERIOD_SECONDS, +} from '@kuiralabs/midnight-cli-core/lib/constants'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; + +// MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): settings().isDustCollapseOff. + +/** + * Data the collapse needs to keep working correctly across restarts: which + * generation-tree leaves are ours (must never be collapsed) and how far the + * tree has grown. Persisted alongside the dust state and fed back on resume. + */ +export interface DustRetention { + /** Generation-tree indices owned by this wallet. */ + ownedGenerationIndices: number[]; + /** Next-free generation index reached (exclusive upper bound). */ + generationFrontier: number; +} + +// Initial dust parameters live in constants.ts (single source of truth). +// `ParamChange` events in the replay stream update these to the chain's current +// values before any UTXO events are applied, so the starting values only affect +// state-construction, not results. + +const SUBSCRIPTION_QUERY = ` + subscription DustLedgerEvents($id: Int) { + dustLedgerEvents(id: $id) { + type: __typename + id + raw + maxId + } + } +`; + +interface RawDustEvent { + type: string; + id: number; + raw: string; + maxId: number; +} + +export interface DustDirectResult { + balance: bigint; + availableCoins: number; + eventCount: number; + ownedUtxoCount: number; + syncTime: Date; + /** Final DustLocalState — callers can serialize this for caching. */ + state: ledger.DustLocalState; + /** Retention data to persist with the state (for correct resume + collapse). */ + retention: DustRetention; + /** Id of the last event applied in this run. -1 if none arrived. */ + lastAppliedEventId: number; + /** + * True iff the sync stopped before catching up to the indexer's tip + * (timeout or abort). The returned state + lastAppliedEventId are still + * valid — the caller should persist them and re-call to resume from the + * checkpoint. False means we caught up to the chain head (or there were + * no events to apply). + */ + partial: boolean; +} + +export interface DustDirectOptions { + /** Called with (eventsApplied, maxIdSeen) whenever a new event arrives. */ + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + /** + * Called after every chunk of events is applied to the local state, with + * the current state + last applied event id. Lets the caller persist a + * checkpoint so a Ctrl+C / timeout doesn't lose 100k events of work. + * Note: invoked synchronously after `replayEvents`; keep the callback + * cheap (file write is fine, network is not). + */ + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + /** + * Soft ceiling for the whole subscription. On expiry the call resolves + * with `partial: true` and whatever state has been applied so far — + * never throws away progress. Default: 600s. Set very high to disable. + */ + timeoutMs?: number; + /** If no event arrives for this long (and we've received some), treat as caught up. Default: 5s. */ + idleMs?: number; + /** + * If no event is received AT ALL within this window after connecting, treat + * the stream as empty (nothing to catch up on) and return. This lets a + * cached-resume with zero new events finish quickly instead of waiting on + * `timeoutMs`. Default: 3s. + */ + initialSilenceMs?: number; + /** Abort the subscription mid-flight. */ + signal?: AbortSignal; + /** Resume from this cached state instead of building fresh. */ + initialState?: ledger.DustLocalState; + /** Subscribe starting at this event id (inclusive). Default: 0. */ + startFromId?: number; + /** Retention data from a cached checkpoint, so resume keeps collapsing correctly. */ + initialRetention?: DustRetention; + /** Collapse foreign generation ranges before checkpoint/return. Default: true. */ + collapse?: boolean; +} + +function createInitialDustState(): ledger.DustLocalState { + const params = new ledger.DustParameters( + INITIAL_NIGHT_DUST_RATIO, + INITIAL_GENERATION_DECAY_RATE, + INITIAL_DUST_GRACE_PERIOD_SECONDS, + ); + return new ledger.DustLocalState(params); +} + +/** + * Subscribe to all dust ledger events from the beginning of chain, deserialize, + * replay into a fresh local state using the given dust secret key, and return + * the resulting balance plus diagnostics. + * + * "Caught up" is detected when the latest `id` received equals `maxId`. + */ +export function readDustBalanceDirect( + dustSecretKey: ledger.DustSecretKey, + indexerWS: string, + options: DustDirectOptions = {}, +): Promise { + const { + onProgress, + onCheckpoint, + timeoutMs = 600_000, + idleMs = 5_000, + initialSilenceMs = 3_000, + signal, + initialState, + startFromId = 0, + initialRetention, + collapse, + } = options; + + const collapseEnabled = collapse !== false && !settings().isDustCollapseOff; + + // Apply events in chunks as they arrive so the final step is cheap and + // progress updates stay responsive. Replaying 100k events in a single + // synchronous WASM call blocks the event loop for tens of seconds. + const CHUNK_SIZE = 500; + + let state = initialState ?? createInitialDustState(); + const pending: ledger.Event[] = []; + + // Retention tracking (owner-match): a generation leaf is ours iff its owner is + // our dust public key. Accumulate the owned index set + frontier as events + // arrive so we collapse only foreign ranges. Seeded from the cached checkpoint. + const myPubkey = dustSecretKey.publicKey; + const ownedGenIndices = new Set((initialRetention?.ownedGenerationIndices ?? []).map(BigInt)); + let frontier = BigInt(initialRetention?.generationFrontier ?? 0); + const trackRetention = (event: ledger.Event) => { + const content = event.content as { tag?: string; generationIndex?: bigint; generation?: { owner?: bigint } }; + if (content?.tag !== 'dustInitialUtxo' || content.generationIndex === undefined) return; + const idx = content.generationIndex; + if (idx + 1n > frontier) frontier = idx + 1n; + if (content.generation?.owner === myPubkey) ownedGenIndices.add(idx); + }; + const currentRetention = (): DustRetention => ({ + ownedGenerationIndices: [...ownedGenIndices].map(Number), + generationFrontier: Number(frontier), + }); + + let eventsAppliedCount = 0; + let lastEventId = startFromId - 1; + let maxIdSeen = -1; + + // Replay accumulated events in chunks so the final step is cheap and the event + // loop can breathe between WASM calls; collapse foreign ranges and checkpoint + // after each chunk so a timeout/abort doesn't lose the work. lastEventId is + // updated before the flush so the checkpoint cursor matches the events applied. + const flushPending = () => { + if (pending.length === 0) return; + state = state.replayEvents(dustSecretKey, pending); + eventsAppliedCount += pending.length; + pending.length = 0; + if (collapseEnabled) { + state = collapseForeignGenerations(state, ownedGenIndices, frontier).state; + } + if (onCheckpoint && lastEventId >= 0) { + try { onCheckpoint(state, lastEventId, currentRetention()); } catch { /* best-effort */ } + } + }; + + return subscribeGraphqlWs(indexerWS, { + query: SUBSCRIPTION_QUERY, + variables: { id: startFromId }, + idleMs, + timeoutMs, + // Fast-return only when resuming from cached state; a fresh cold sync must + // wait for its (possibly slow) first event. + initialSilenceMs: initialState ? initialSilenceMs : 0, + signal, + onNext: (data) => { + const evt = (data as { dustLedgerEvents?: RawDustEvent } | undefined)?.dustLedgerEvents; + if (!evt) return false; + let event: ledger.Event; + try { + event = ledger.Event.deserialize(Buffer.from(evt.raw, 'hex')); + } catch (err) { + throw new Error(`Failed to deserialize dust event ${evt.id}: ${(err as Error).message}`); + } + trackRetention(event); // read owner/index before replayEvents consumes it + pending.push(event); + lastEventId = evt.id; + if (evt.maxId > maxIdSeen) maxIdSeen = evt.maxId; + if (pending.length >= CHUNK_SIZE) { + try { flushPending(); } catch (err) { + throw new Error(`Failed applying dust events: ${(err as Error).message}`); + } + } + onProgress?.(eventsAppliedCount + pending.length, maxIdSeen); + // Caught up when we've received the final event in the current stream. + return lastEventId >= maxIdSeen; + }, + buildResult: (partial) => { + try { + flushPending(); + const now = new Date(); + state = state.processTtls(now); + return { + balance: state.walletBalance(now), + availableCoins: state.utxos.length, + eventCount: eventsAppliedCount, + ownedUtxoCount: state.utxos.length, + syncTime: state.syncTime, + state, + retention: currentRetention(), + lastAppliedEventId: lastEventId, + partial, + }; + } catch (err) { + throw new Error(`Failed to build dust state: ${(err as Error).message}`); + } + }, + }); +} diff --git a/packages/engine-beta/src/dust-export.ts b/packages/engine-beta/src/dust-export.ts new file mode 100644 index 00000000..dca16597 --- /dev/null +++ b/packages/engine-beta/src/dust-export.ts @@ -0,0 +1,108 @@ +// Export a facade-restorable dust snapshot for a seed. +// +// Combines a full dust sync with a base facade dust snapshot (built from keys, +// never connected) to produce a JSON blob that ANY wallet on the same seed can +// hand to `DustWallet.restore(...)` (e.g. via a wallet-SDK facade's +// `dustSerializedState`) to skip the slow cold dust scan. This is the seam a +// dApp operator uses to warm up in seconds instead of re-scanning the whole +// dust event history on every restart. +// +// The sync runs through `WalletDataRepository.dust()` rather than calling the +// indexer-direct reader itself. That is deliberate: the repository owns the +// native-sidecar acceleration (~5x on a cold preprod sync) and the +// partial-resume loop that carries a from-scratch sync past the underlying +// fetcher's soft timeout. Calling the reader directly — as this module used to — +// got neither, so a fresh wallet on preprod silently exported a snapshot cut off +// at the 600s mark. +// +// Pure logic: returns values, never writes to stdout/stderr or exits. + +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; + + +export interface DustExportOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + signal?: AbortSignal; + /** Injectable for tests; defaults to the process-wide repository. */ + repository?: WalletDataRepository; + /** + * Produce the base (empty) dust snapshot to overlay onto. Injectable for tests; + * defaults to building a fresh facade from keys and reading its dust snapshot. + * The default touches the node relay (building a facade opens its API-WS), so + * tests stub this to stay offline. + */ + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + /** The call's verbose lines. */ + log?: VerboseLog; +} + +/** Build a fresh facade from keys and read its base (empty) dust snapshot. */ +async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, log?: VerboseLog): Promise { + const bundle = await buildFacade(seedBuffer, networkConfig, null, log); + try { + return await (bundle.facade as unknown as { + dust: { serializeState(): Promise }; + }).dust.serializeState(); + } finally { + await stopFacade(bundle); + } +} + +/** + * Produce a restorable dust snapshot for `seedBuffer` on `network`. + * + * 1. Full dust sync via the repository (native sidecar when available, WASM + * otherwise; resumes from the on-disk checkpoint and retries past partials). + * 2. Build a fresh facade (from keys only — no `start()`, so no network I/O) + * to get a correctly-shaped base dust snapshot (publicKey/protocolVersion/ + * networkId + schema). + * 3. Overlay the synced `DustLocalState` onto that base — the same operation + * `maybeBridgeDustCache` does for the CLI's own write commands. + */ +export async function exportDustSnapshot( + seedBuffer: Buffer, + network: string, + networkConfig: NetworkConfig, + options: DustExportOptions = {}, +): Promise { + const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); + const repo = options.repository ?? defaultRepository(); + + const view = await repo.dust(seedBuffer, networkConfig, { + signal: options.signal, + onProgress: options.onProgress, + log: options.log, + }); + + const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.log); + + // Overlay whenever at least one event has been folded in. For a wallet with no + // dust events yet (lastAppliedEventId -1) the fresh base snapshot is already the + // correct empty state and carries a valid offset 0, so leave it untouched. + // The state + offset come from the view rather than re-reading the cache file: + // the repository may be pointed at a different cache dir, and its in-memory view + // is authoritative for the sync that just ran. + const snapshot = view.lastAppliedEventId >= 0 + ? overlayDustDirectSnapshot(baseDust, { + state: view.state, + lastAppliedEventId: view.lastAppliedEventId, + }) + : baseDust; + + return { + network, + dustPublicKey: pubkeyHex, + offset: view.lastAppliedEventId, + balance: view.balance, + eventCount: view.eventsApplied, + fromCache: view.fromCache, + partial: view.partial, + snapshot, + }; +} diff --git a/packages/engine-beta/src/dust-register.ts b/packages/engine-beta/src/dust-register.ts new file mode 100644 index 00000000..5b149356 --- /dev/null +++ b/packages/engine-beta/src/dust-register.ts @@ -0,0 +1,53 @@ +// Registering a wallet's NIGHT for Dust generation and waiting until it has +// Dust to spend. `mn dust register` and `mn dev` both register through here. + +import { waitForLiteSyncedState } from './facade.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { ensureDust } from './transfer.ts'; +import { defaultRepository } from './wallet-data-repository.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; + + + +export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { + const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log } = options; + const stopListening = sdkWarnings.listen(onSyncWarning); + try { + const { result, dustBalance } = await defaultRepository().withFacade( + seed, + networkConfig, + async ({ bundle, state }) => { + throwIfCancelled(signal); + onStatus?.('Checking dust status...'); + + // ensureDust handles: early return if dust exists, registration + // of unregistered UTXOs, waiting for dust coins. + const result = await ensureDust(bundle, (status: string) => onStatus?.(status), state); + + throwIfCancelled(signal); + + // Wait for dust data to be fully populated before reading balance. + const finalState = await waitForLiteSyncedState(bundle); + return { result, dustBalance: finalState.dust.balance(new Date()) }; + }, + { + syncMode: 'lite', + requireStrictSync: true, + signal, + onStatus, + onSyncProgress, + onSyncDetail, + log, + }, + ); + const registration: DustRegistration = { alreadyAvailable: result.alreadyAvailable, dustBalance }; + if (result.txHash) registration.txHash = result.txHash; + return registration; + } finally { + stopListening(); + } +} diff --git a/packages/engine-beta/src/dust-sync-native.ts b/packages/engine-beta/src/dust-sync-native.ts new file mode 100644 index 00000000..d648988d --- /dev/null +++ b/packages/engine-beta/src/dust-sync-native.ts @@ -0,0 +1,256 @@ +// Native dust-sync bridge: run the Rust `dust-sync` sidecar and adapt its output +// to a `DustDirectResult`, so it drops into the repository's `fetchDust` seam. +// Several times faster on a cold dust sync. If the binary is missing or the run +// fails, callers fall back to the WASM path — the sidecar is an optional +// accelerator, never a hard dependency. + +import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; + +import * as ledger from '@midnightntwrk/ledger-v9'; + +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { deriveDustSeed } from './derivation.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; +import { collapseForeignGenerations } from './dust-collapse.ts'; +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { cacheRootDir, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; + +/** Sidecar checkpoint JSON shape (snake_case — matches the Rust `Checkpoint`). */ +export interface SidecarCheckpoint { + dust_state: string; + last_applied_event_id: number; + owned_generation_indices: number[]; + generation_frontier: number; + balance: string; + available_coins: number; + events_applied: number; + partial: boolean; +} + +interface NativeFetchOptions { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + /** The wallet's cache folder (the state root's when absent): the checkpoint lives beside the other Dust caches. */ + cacheDir?: string; +} + +/** + * Locate the sidecar binary. Order: explicit env override → the (Phase 3) + * optional platform package → the dev build under sidecar/dust-sync. Returns + * null when none resolve (→ WASM fallback). + */ +export function resolveSidecarBinary(): string | null { + const fromEnv = settings().dustSyncBin; + if (fromEnv && existsSync(fromEnv)) return fromEnv; + + const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; + // Dev build (repo checkout): sidecar/dust-sync/target/release/dust-sync, + // three levels up from the engine package's src/ (tsx) and from its dist/. + const here = dirname(fileURLToPath(import.meta.url)); + for (const up of [['..', '..', '..']]) { + const devBuild = join(here, ...up, 'sidecar', 'dust-sync', 'target', 'release', exe); + if (existsSync(devBuild)) return devBuild; + } + + // Phase 3 platform package: @nel349/dust-sync--. + return platformPackageBinary(import.meta.url); +} + +/** + * The sidecar binary in the platform package (@nel349/dust-sync--) + * resolvable from `fromUrl`, or null when it isn't installed. Resolved with + * node:module's createRequire, which works from source and from the bundle. + */ +export function platformPackageBinary(fromUrl: string): string | null { + const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; + try { + const pkg = `@nel349/dust-sync-${process.platform}-${process.arch}`; + const binPath = join(dirname(createRequire(fromUrl).resolve(`${pkg}/package.json`)), exe); + return existsSync(binPath) ? binPath : null; + } catch { + return null; // package not installed + } +} + + +/** True when the native sidecar should be used (binary resolves + not disabled). */ +/** + * The ledger the sidecar binary is built against. It replays dust events with + * its own copy of the ledger, so it can only serve a chain on the same ledger. + * No ledger-9 `midnight-ledger` crate is published yet. + */ +const SIDECAR_LEDGER: number = 8; +/** The ledger this build of mn targets. */ +const MN_LEDGER: number = 9; + +export function nativeDustSyncAvailable(): boolean { + if (SIDECAR_LEDGER !== MN_LEDGER) return false; + if (settings().isNativeDustOff) return false; + return resolveSidecarBinary() !== null; +} + +/** + * Choose how to resume the sidecar, kill-safely: + * - `existing`: an on-disk checkpoint already reaches the requested cursor + * (e.g. a prior run was killed mid-sync) — resume from it, don't rewind. + * - `seed`: no usable checkpoint but the repo has cached state — seed from it. + * - `fresh`: nothing to resume from — sync from the start. + * `existingCursor` is a last-applied-event-id (-2 if no checkpoint). + */ +export function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): 'existing' | 'seed' | 'fresh' { + if (existingCursor + 1 >= startFromId) return 'existing'; + if (hasInitialState) return 'seed'; + return 'fresh'; +} + +/** Last-applied event id in a sidecar checkpoint file, or -2 if absent/unreadable. */ +function readCheckpointCursor(path: string): number { + if (!existsSync(path)) return -2; + try { + const cp: SidecarCheckpoint = JSON.parse(readFileSync(path, 'utf-8')); + return typeof cp.last_applied_event_id === 'number' ? cp.last_applied_event_id : -2; + } catch { return -2; } +} + +/** The sidecar's checkpoint file for a Dust key, beside the other Dust caches. */ + +function nativeCheckpointPath(networkName: string, pubkeyHex: string, cacheDir?: string): string { + const dir = join(cacheRootDir(cacheDir), networkCacheFolder(networkName)); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + return join(dir, nativeCheckpointName(pubkeyHex)); +} + + +/** + * Run the native sidecar for a dust sync and adapt to `DustDirectResult`. + * Rejects (so the caller can fall back) if the binary is missing or the run + * fails. Aborting via `signal` sends SIGINT — the sidecar checkpoints and exits, + * yielding a `partial` result the repo persists and resumes from. + */ +export function runDustSyncNative( + seed: Buffer, + network: NetworkConfig, + opts: NativeFetchOptions, +): Promise { + return new Promise((resolve, reject) => { + const bin = resolveSidecarBinary(); + if (!bin) { reject(new Error('dust-sync sidecar not found')); return; } + assertEndpointUsable(network.indexerWS); + + const networkName = network.networkId.toLowerCase(); + const pubkeyHex = dustPublicKeyHexFromSeed(seed); + const out = nativeCheckpointPath(networkName, pubkeyHex, opts.cacheDir); + + // Resume selection (out == resume file; the sidecar reads it once at start, + // then overwrites it with its own checkpoints — kill-safe at this path): + // - if an existing sidecar checkpoint is already AT/PAST the repo's cursor + // (e.g. a prior run was killed mid-sync), keep it — don't rewind it. + // - else seed it from the repo's cached state so we resume from there. + // - else (no cache) let the sidecar start fresh. + const args = ['--indexer-ws', network.indexerWS, '--out', out]; + const decision = resumeDecision(readCheckpointCursor(out), opts.startFromId, !!opts.initialState); + if (decision === 'seed') { + const seedCp: SidecarCheckpoint = { + dust_state: Buffer.from(opts.initialState!.serialize()).toString('hex'), + last_applied_event_id: opts.startFromId - 1, + owned_generation_indices: opts.initialRetention?.ownedGenerationIndices ?? [], + generation_frontier: opts.initialRetention?.generationFrontier ?? 0, + balance: '0', available_coins: 0, events_applied: 0, partial: true, + }; + writeFileSync(out, JSON.stringify(seedCp), { mode: FILE_MODE }); + } + if (decision !== 'fresh') args.push('--resume', out); + + const child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] }); + + const onAbort = () => { try { child.kill('SIGINT'); } catch { /* already gone */ } }; + opts.signal?.addEventListener('abort', onAbort, { once: true }); + + // Feed the derived dust seed on stdin (sidecar zeroizes it), then close. + // If the sidecar exits before reading stdin, the write races an EPIPE that + // would otherwise surface as an unhandled stream 'error' and crash us. Swallow + // it here — the real outcome is reported via child.on('close'/'error'). + child.stdin.on('error', () => { /* EPIPE: child gone; handled by close/error */ }); + const dustSeedHex = Buffer.from(deriveDustSeed(seed)).toString('hex'); + child.stdin.write(dustSeedHex + '\n'); + child.stdin.end(); + + let stdout = ''; + let stderrTail = ''; + child.stdout.on('data', (d) => { stdout += d.toString(); }); + child.stderr.on('data', (d) => { + const s = d.toString(); + stderrTail = (stderrTail + s).slice(-2000); + // Parse "dust-sync: applied / " progress lines. + for (const m of s.matchAll(/applied (\d+) \/ (\d+)/g)) { + opts.onProgress?.(Number(m[1]), Number(m[2])); + } + }); + + child.on('error', (err) => { opts.signal?.removeEventListener('abort', onAbort); reject(err); }); + child.on('close', (code) => { + opts.signal?.removeEventListener('abort', onAbort); + // The sidecar answers SIGINT itself (checkpoint, then exit 0), so any + // other exit is a failure, whatever is left at `out`. That file may be our + // own seed checkpoint or one the dead run never finished. + if (code !== 0) { + reject(new Error(`dust-sync exited ${code}: ${stderrTail.trim().slice(-300)}`)); + return; + } + try { + // Prefer the final stdout line; fall back to the checkpoint file. + const lastLine = stdout.trim().split('\n').filter(Boolean).pop(); + const cp: SidecarCheckpoint = lastLine + ? JSON.parse(lastLine) + : JSON.parse(readFileSync(out, 'utf-8')); + resolve(adaptResult(cp)); + } catch (err) { + reject(new Error(`dust-sync output parse failed: ${(err as Error).message}`)); + } + }); + }); +} + +/** Map the sidecar's checkpoint JSON to a `DustDirectResult`. Exported for tests. */ +export function adaptResult(cp: SidecarCheckpoint): DustDirectResult { + const now = new Date(); + let state = ledger.DustLocalState.deserialize(new Uint8Array(Buffer.from(cp.dust_state, 'hex'))); + // The Rust sidecar doesn't collapse the generation tree, so a native sync would + // otherwise persist/export an unbounded state (~1.46 MB on a cold preprod wallet + // vs ~23 KB collapsed). Apply the same TS collapse the WASM reader uses, reusing + // the owned-indices + frontier the checkpoint already carries. Idempotent, and it + // fails safe to the uncollapsed state via the balance+root guard. + if (!settings().isDustCollapseOff) { + const owned = new Set(cp.owned_generation_indices.map((i) => BigInt(i))); + state = collapseForeignGenerations(state, owned, BigInt(cp.generation_frontier)).state; + } + // processTtls is immutable (returns a new state) — parity with the WASM reader, + // which drops expired coins before reading the balance. + state = state.processTtls(now); + const utxoCount = state.utxos.length; + return { + balance: state.walletBalance(now), + availableCoins: utxoCount, + eventCount: cp.events_applied, + ownedUtxoCount: utxoCount, + syncTime: state.syncTime instanceof Date ? state.syncTime : new Date(String(state.syncTime)), + state, + retention: { + ownedGenerationIndices: cp.owned_generation_indices, + generationFrontier: cp.generation_frontier, + }, + lastAppliedEventId: cp.last_applied_event_id, + partial: cp.partial, + }; +} diff --git a/packages/engine-beta/src/dust-wallet.ts b/packages/engine-beta/src/dust-wallet.ts new file mode 100644 index 00000000..601495f1 --- /dev/null +++ b/packages/engine-beta/src/dust-wallet.ts @@ -0,0 +1,123 @@ +// mn's Dust wallet: the wallet SDK's, built the way the SDK builds it, with +// one part its builder lets a caller bring: how the coins that pay a fee are +// chosen. The SDK's own choice can loop without end (see dust-balancing-plan.ts), +// freezing the process until the ledger's WASM runs out of memory. Everything +// else is the SDK's. +// +// When the SDK's computeBalancingRecipe ends on its own, this file goes and +// facade.ts imports DustWallet from the SDK again. + +import * as ledger from '@midnightntwrk/ledger-v9'; +import { Imbalances, InsufficientFundsError as NoCoinsCoverIt, getBalanceRecipe } from '@midnightntwrk/wallet-sdk-capabilities'; +import { CustomDustWallet, DustWallet as SdkDustWallet } from '@midnightntwrk/wallet-sdk-dust-wallet'; +import { Transacting, V1Builder, WalletError } from '@midnightntwrk/wallet-sdk-dust-wallet/v1'; +import { LedgerOps } from '@midnightntwrk/wallet-sdk-utilities'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '@kuiralabs/midnight-cli-core/lib/dust-balancing-plan'; +import { type DustShortfall, withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; + +type SdkTransacting = Transacting.TransactingCapabilityImplementation; +type RecipeArguments = Parameters; +type Recipe = ReturnType; +type DustCoin = ReturnType['getAvailableCoinsWithGeneratedDust']>[number]; + +/** The SDK's transacting, with its fee-coin choice replaced by one that ends. */ +export class ConvergingDustTransacting extends Transacting.TransactingCapabilityImplementation { + override computeBalancingRecipe(...args: RecipeArguments): Recipe { + const [secretKey, state, transactions, ttl, currentTime, ledgerParams] = args; + let plan; + try { + // What the transactions owe in Dust before any spend is added: the + // SDK's starting imbalance, as an amount owed. + const owed = -transactions.reduce( + (total, tx) => total + Transacting.TransactingCapabilityImplementation.feeImbalance(tx, this.calculateFee(tx, ledgerParams)), + 0n, + ); + const coins = this.getCoins().getAvailableCoinsWithGeneratedDust(state, currentTime); + plan = planDustInputs({ + owed, + coinCount: coins.length, + choose: (amount) => chooseDustCoins(coins, amount, (several) => this.#combine(coins, several)), + feeWith: (inputs) => this.dryRunFee(inputs, transactions, secretKey, state, ttl, currentTime, ledgerParams), + }); + } catch (error) { + return LedgerOps.ledgerTry(() => { throw error; }); + } + + if (plan.kind === 'covered') { + const { fee, inputs } = plan; + return LedgerOps.ledgerTry(() => ({ fee, recipeInputs: spreadFeeAcrossInputs(inputs, fee) })); + } + const shortfall = this.#shortfall(args); + // Too little Dust even before a spend is added: the SDK's first choice + // refuses it and stops, so its own error stands, with the shortfall added. + if (plan.atFirstChoice) { + const refused = super.computeBalancingRecipe(...args); + if (shortfall && refused._tag === 'Left') withDustShortfall(refused.left, shortfall); + return refused; + } + // Enough for the transactions' own fee, not for the fee with the spends + // added: where the SDK's loop never ends. Refused as the same shortage. + return LedgerOps.ledgerTry(() => { + const shortage = new WalletError.InsufficientFundsError({ message: new NoCoinsCoverIt('dust').message, tokenType: 'dust' }); + throw shortfall ? withDustShortfall(shortage, shortfall) : shortage; + }); + } + + /** + * What the wallet is short by, so a caller can tell how long its NIGHT + * takes to generate it: the fee with a spend of every coin the wallet has, + * and what those coins hold at the time the spends are made for (the + * wallet's clock for the chain, which a local chain can run behind). + * Undefined with no coin to spend, or when the fee can't be worked out. + */ + #shortfall([secretKey, state, transactions, ttl, currentTime, ledgerParams]: RecipeArguments): DustShortfall | undefined { + try { + const coins = this.getCoins().getAvailableCoinsWithGeneratedDust(state, currentTime); + if (coins.length === 0) return undefined; + const inputs = coins.map(({ token, value }) => ({ token, value })); + return { + needed: this.dryRunFee(inputs, transactions, secretKey, state, ttl, currentTime, ledgerParams), + available: inputs.reduce((sum, input) => sum + input.value, 0n), + }; + } catch { + return undefined; + } + } + + /** The SDK balancer's choice of several coins covering `owed`, in the order it takes them. */ + #combine(coins: readonly DustCoin[], owed: bigint): DustInput[] | undefined { + try { + const recipe = getBalanceRecipe({ + coins: coins.map((coin) => ({ type: 'dust' as const, value: coin.value, token: coin.token })), + initialImbalances: Imbalances.fromEntry('dust', -owed), + feeTokenType: 'dust', + coinSelection: this.getCoinSelection(), + transactionCostModel: { inputFeeOverhead: 0n, outputFeeOverhead: 0n }, + createOutput: (coin) => coin, + isCoinEqual: (a, b) => a.token.nonce === b.token.nonce, + }); + return recipe.inputs.map(({ token, value }) => ({ token, value })); + } catch (error) { + if (error instanceof NoCoinsCoverIt) return undefined; + throw error; + } + } +} + +const makeConvergingTransacting: typeof Transacting.makeDefaultTransactingCapability = (config, getContext) => + new ConvergingDustTransacting( + config.networkId, + config.costParameters, + () => getContext().coinSelection, + () => getContext().coinsAndBalancesCapability, + () => getContext().keysCapability, + ); + +/** + * The SDK's `DustWallet(configuration)`, composed as it composes it (one + * ledger-9 variant on the beta SDK, which has no fork schedule), with that + * variant's transacting replaced. + */ +export function DustWallet(configuration: Parameters[0]): ReturnType { + return CustomDustWallet(configuration, new V1Builder().withDefaults().withTransacting(makeConvergingTransacting)); +} diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts new file mode 100644 index 00000000..4e13b031 --- /dev/null +++ b/packages/engine-beta/src/facade.ts @@ -0,0 +1,662 @@ +import { ShieldedWallet } from '@midnightntwrk/wallet-sdk-shielded'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { + UnshieldedWallet, + createKeystore, + PublicKey, + type UnshieldedKeystore, +} from '@midnightntwrk/wallet-sdk-unshielded-wallet'; +import { DustWallet } from './dust-wallet.ts'; +import { + WalletFacade, + WalletEntrySchema, + mergeWalletEntries, + type FacadeState, +} from '@midnightntwrk/wallet-sdk-facade'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk-abstractions'; +import * as rx from 'rxjs'; + +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; +import { type WalletCacheData } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; +import { + DUST_COST_OVERHEAD, + DUST_FEE_BLOCKS_MARGIN, + SYNC_TIMEOUT_MS, + PRE_SEND_SYNC_TIMEOUT_MS, +} from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; +import { isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; +import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; + +export type SyncMode = 'full' | 'lite' | 'no-dust'; +// full = shielded + unshielded + dust +// lite = unshielded + dust (skip shielded — used by dust register/status) +// no-dust = shielded + unshielded (skip dust — used by balance; dust isn't needed +// to read NIGHT balances and avoids the dust `isConnected` SDK hang) + +/** + * The secret keys the wallets start with and the facade balances with. The + * beta SDK starts wallets from keys, not seeds, and asks for them again on + * every call that spends shielded coins or Dust. + */ +export interface WalletSecretKeys { + shieldedSecretKeys: ledger.ZswapSecretKeys; + dustSecretKey: ledger.DustSecretKey; +} + +export interface FacadeBundle { + facade: WalletFacade; + keystore: UnshieldedKeystore; + /** The shielded and dust secret keys, derived once from the seed. */ + secretKeys: WalletSecretKeys; + /** Active subscription that keeps shareReplay buffers alive. Cleaned up by stopFacade. */ + keepAlive?: rx.Subscription; + /** Whether the facade was restored from cached state (vs built from scratch). */ + restoredFromCache?: boolean; + /** The network's indexer (HTTP), for reads the facade doesn't offer, like the chain's clock. */ + indexerHttpUrl?: string; + /** The network's indexer (WebSocket), asked which event streams are empty when a sync starts. */ + indexerWsUrl?: string; + /** The streams the chain has no events in, as read when the sync started. */ + emptyStreams?: EmptyStreams; +} + +/** + * Build a complete WalletFacade from a seed and network config. + * Returns the facade plus all keys needed for signing and proving. + * + * When `cache` is provided, wallets are restored from serialized state + * instead of starting fresh — the SDK then only syncs new transactions + * since the last checkpoint. + * + * Its diagnostics go to `log`, the call's verbose lines. + */ +export async function buildFacade( + seedBuffer: Buffer, + networkConfig: NetworkConfig, + cache?: WalletCacheData | null, + log?: VerboseLog, +): Promise { + const networkId = getNetworkId(networkConfig.networkId); + + await assertNetworkAnswers(networkConfig); + + log?.('facade', `Building facade for network ${networkConfig.networkId}`); + log?.('facade', `Node: ${networkConfig.node}`); + log?.('facade', `Indexer: ${networkConfig.indexerWS}`); + log?.('facade', `Proof server: ${networkConfig.proofServer}`); + + const secretKeys: WalletSecretKeys = { + shieldedSecretKeys: ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(seedBuffer)), + dustSecretKey: ledger.DustSecretKey.fromSeed(deriveDustSeed(seedBuffer)), + }; + const keystore = createKeystore({ kind: 'schnorr', secret: deriveUnshieldedSeed(seedBuffer) }, networkId); + + // Merged configuration for WalletFacade.init() — all wallet types + // and services draw from this single config object. + const configuration = { + networkId, + indexerClientConnection: { + indexerHttpUrl: networkConfig.indexer, + indexerWsUrl: networkConfig.indexerWS, + }, + costParameters: { + additionalFeeOverhead: DUST_COST_OVERHEAD, + feeBlocksMargin: DUST_FEE_BLOCKS_MARGIN, + }, + txHistoryStorage: new InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries), + provingServerUrl: new URL(networkConfig.proofServer), + relayURL: new URL(networkConfig.node), + }; + + // Fresh build from the secret keys. It doesn't start syncing; startFacade + // does that. + const initFresh = () => WalletFacade.init({ + configuration, + shielded: (cfg) => ShieldedWallet(cfg).startWithSecretKeys(secretKeys.shieldedSecretKeys), + unshielded: (cfg) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(keystore)), + dust: (cfg) => DustWallet(cfg).startWithSecretKey(secretKeys.dustSecretKey, ledger.LedgerParameters.initialParameters().dust), + }); + + // Bridge: if the dust-direct cache has a more recent DustLocalState than the + // facade cache, overlay it into the facade cache's dust snapshot before + // restore. This lets commands that use the facade (transfer, airdrop, dust + // register) benefit from the indexer-direct reader's checkpoint without + // re-implementing the whole transaction flow. + const dustPublicKey = secretKeys.dustSecretKey.publicKey; + const effectiveCache = cache ? maybeBridgeDustCache(cache, networkConfig, dustPublicKey, log) : null; + + // Attempt cache restore — fall back to fresh build on any deserialization error. + let restoredFromCache = false; + let facade: WalletFacade; + + if (effectiveCache) { + log?.('facade', 'Restoring from cache...'); + try { + facade = await WalletFacade.init({ + configuration, + shielded: (cfg) => ShieldedWallet(cfg).restore(effectiveCache.shielded), + unshielded: (cfg) => UnshieldedWallet(cfg).restore(effectiveCache.unshielded), + dust: (cfg) => DustWallet(cfg).restore(effectiveCache.dust), + }); + restoredFromCache = true; + log?.('facade', 'Cache restore successful'); + } catch (err) { + log?.('facade', `Cache restore failed: ${(err as Error).message}`); + notice(` Cache restore failed, building from scratch: ${(err as Error).message}`); + facade = await initFresh(); + } + } else { + log?.('facade', 'No cache, building fresh'); + facade = await initFresh(); + } + + return { facade, keystore, secretKeys, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; +} + +/** + * Start the facade's wallets and background sync, exactly once. + * + * Fresh or restored, the beta SDK takes the same path: a snapshot carries no + * keys, and `facade.start` hands the shielded and dust wallets theirs. There + * is one ledger variant, so no wallet can be restored onto one the keys + * don't drive. + */ +async function startFacade(bundle: FacadeBundle): Promise { + const { facade, secretKeys } = bundle; + await facade.start(secretKeys.shieldedSecretKeys, secretKeys.dustSecretKey); +} + +/** + * If our indexer-direct cache has a NEWER DustLocalState than the facade + * cache, overlay it into the facade cache's dust snapshot. Keeps publicKey, + * protocolVersion, networkId from the existing snapshot; only state + offset + * change. Returns the cache unchanged if: + * - no dust-direct entry exists + * - facade cache's own offset is already >= dust-direct's offset (prior + * transfer already advanced it past our indexer-direct snapshot) + * - parsing fails + */ +// Shape of the facade's serialized dust-wallet snapshot. See +// dust-wallet/src/v1/Serialization.ts `SnapshotSchema` — JSON on disk with +// BigInts rendered as decimal strings. The `state` field is a hex-encoded +// `DustLocalState.serialize()` (ledger-v9) — the same blob the dust-direct +// cache stores, which is why the two are interchangeable via the overlay below. +export interface FacadeDustSnapshot { + publicKey: { publicKey: string }; + state: string; + protocolVersion: string; + networkId: string; + offset?: string; +} + +/** + * Overlay a dust-direct checkpoint onto a facade dust snapshot: swap in the + * `DustLocalState` from the indexer-direct reader and set the offset to its last + * applied event id. Keeps publicKey/protocolVersion/networkId from the base + * snapshot untouched. This is an UNCONDITIONAL overlay — whether the dust-direct + * state is the one you want is the caller's policy (see `maybeBridgeDustCache`'s + * freshness guard, and `dust export`'s "any events applied?" check). Overlaying + * must not itself decide to skip: a base facade snapshot always carries + * `offset:"0"`, which would otherwise collide with a genuine checkpoint at id 0. + * + * This is the seam that lets a facade restore from the fast dust-direct sync: + * `maybeBridgeDustCache` uses it to speed up write commands, and `dust export` + * uses it to hand a restorable snapshot to other wallets (e.g. a dApp operator). + */ +export function overlayDustDirectSnapshot( + dustSnapshotJson: string, + direct: Pick, +): string { + const snapshot: FacadeDustSnapshot = JSON.parse(dustSnapshotJson); + // The beta SDK's Dust wallet has one variant, ledger 9, and restores every + // snapshot onto it whatever protocolVersion the snapshot carries, so there + // is no ledger-8 variant a ledger-9 state could be misread by. + snapshot.state = Buffer.from(direct.state.serialize()).toString('hex'); + snapshot.offset = direct.lastAppliedEventId.toString(); + return JSON.stringify(snapshot); +} + +function maybeBridgeDustCache( + cache: WalletCacheData, + networkConfig: NetworkConfig, + dustPublicKey: ledger.DustPublicKey, + log?: VerboseLog, +): WalletCacheData { + try { + const networkName = networkConfig.networkId.toLowerCase(); + const pubkeyHex = dustPublicKeyHex(dustPublicKey); + const direct = loadDustCache(networkName, pubkeyHex); + if (!direct) return cache; + + // Only overlay when dust-direct is AHEAD of the facade cache's own offset — a prior + // write may have advanced the facade past our indexer-direct checkpoint, and we must + // not roll it back. + const snapshot: FacadeDustSnapshot = JSON.parse(cache.dust); + const facadeOffset = snapshot.offset !== undefined ? Number(snapshot.offset) : -1; + if (facadeOffset >= direct.lastAppliedEventId) { + log?.('facade', `Facade dust offset=${facadeOffset} >= dust-direct offset=${direct.lastAppliedEventId}; skipping bridge`); + return cache; + } + log?.('facade', `Bridged dust-direct cache (facade offset ${facadeOffset} → dust-direct offset ${direct.lastAppliedEventId})`); + return { ...cache, dust: overlayDustDirectSnapshot(cache.dust, direct) }; + } catch (err) { + log?.('facade', `Dust-direct bridge skipped: ${(err as Error).message}`); + return cache; + } +} + +/** + * SDK bug workaround: the dust wallet's `isStrictlyComplete()` requires + * `isConnected === true`, but `isConnected` only becomes true when a non-empty + * batch of DustLedgerEvents arrives from the indexer. On an idle chain (no new + * dust transactions), empty batches don't set `isConnected`, so + * `isStrictlyComplete()` stays false forever and `isSynced` never becomes true. + * + * This predicate bypasses the `isConnected` check for dust by verifying the + * actual sync index values directly: if `appliedIndex >= highestRelevantWalletIndex`, + * the dust wallet is caught up regardless of `isConnected`. + * + * Shielded and unshielded wallets don't have this issue because the indexer + * sends progress messages (unshielded) or zswap events (shielded) on every block. + */ +/** The index fields of a shielded or dust wallet's sync progress (bigints in the SDK). */ +interface IndexProgress { + isStrictlyComplete(): boolean; + readonly appliedIndex: bigint; + readonly highestRelevantWalletIndex: bigint; +} + +/** + * The event streams the chain has nothing in. A wallet reading one never hears + * from the indexer, so its progress stays at 0/0 for good: there, and only + * there, "nothing applied" is the wallet's final state. On a chain that has + * events, 0/0 only means the wallet hasn't heard yet, and the unshielded + * wallet often finishes first: a shielded balance read then is 0 whatever the + * wallet holds. + */ +export interface EmptyStreams { + readonly zswap: boolean; + readonly dust: boolean; +} + +/** Nothing known to be empty: every wallet has to hear from the indexer before it counts as synced. */ +export const NO_EMPTY_STREAMS: EmptyStreams = { zswap: false, dust: false }; + +/** + * Dust is caught up when it's strictly complete, or when its indices show it + * is despite the `isConnected` bug above. Nothing applied (0/0) counts only on + * a chain with no dust events, once unshielded is synced. + */ +function isDustCaughtUp(dust: IndexProgress, unshieldedOk: boolean, streamEmpty: boolean): boolean { + if (dust.isStrictlyComplete()) return true; + if (dust.highestRelevantWalletIndex > 0n && dust.appliedIndex >= dust.highestRelevantWalletIndex) return true; + return streamEmpty && isUntouched(dust) && unshieldedOk; +} + +/** No events have reached this wallet yet: nothing applied, nothing relevant. */ +function isUntouched(progress: IndexProgress): boolean { + return progress.highestRelevantWalletIndex === 0n && progress.appliedIndex === 0n; +} + +export function isFacadeSynced( + state: FacadeState, + syncMode: SyncMode = 'full', + empty: EmptyStreams = NO_EMPTY_STREAMS, +): boolean { + const unshieldedOk = state.unshielded.progress.isStrictlyComplete(); + const dustOk = syncMode === 'no-dust' || isDustCaughtUp(state.dust.progress, unshieldedOk, empty.dust); + + if (syncMode === 'lite') { + return unshieldedOk && dustOk; + } + + const shielded = state.shielded.progress; + const shieldedOk = shielded.isStrictlyComplete() || (empty.zswap && unshieldedOk && isUntouched(shielded)); + + return shieldedOk && unshieldedOk && dustOk; +} + +/** Check if dust wallet sync is pending (for diagnostics). */ +function isDustSyncPending(state: FacadeState, empty: EmptyStreams): boolean { + return !isDustCaughtUp(state.dust.progress, state.unshielded.progress.isStrictlyComplete(), empty.dust); +} + +/** Ask the indexer which of the streams this sync mode reads have no events. With no indexer to ask, none. */ +async function readEmptyStreams(indexerWsUrl: string | undefined, syncMode: SyncMode): Promise { + if (!indexerWsUrl) return NO_EMPTY_STREAMS; + const [zswap, dust] = await Promise.all([ + syncMode === 'lite' ? false : isStreamEmpty(indexerWsUrl, 'zswap'), + syncMode === 'no-dust' ? false : isStreamEmpty(indexerWsUrl, 'dust'), + ]); + return { zswap, dust }; +} + +/** + * Start the facade and wait for initial sync. + * Calls onProgress with sync progress updates. + * + * Uses a single persistent subscription to facade.state() that serves three purposes: + * 1. Reports unshielded progress (and which wallets are still syncing) + * 2. Detects sync completion to resolve the sync promise + * 3. Keeps shareReplay({ refCount: true }) buffers alive for the command lifetime + */ +export interface SyncOptions { + onProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + timeoutMs?: number; + syncMode?: SyncMode; + /** + * Require strict sync before resolving (disables the cached-restore grace + * period). Write operations (transfer, airdrop, dust register, contract + * calls) MUST pass this because they construct ZK proofs against the + * commitment tree — if the tree is stale, the proof fails validation on + * chain (MalformedError::InvalidDustSpendProof, error code 170). Read-only + * operations (balance, dust status) can leave this off for the speedup. + */ + requireStrictSync?: boolean; + /** The call's verbose lines. */ + log?: VerboseLog; + /** Cancels the wait: the sync fails with CancelledError. The caller stops the facade. */ + signal?: AbortSignal; +} + +export async function startAndSyncFacade( + bundle: FacadeBundle, + options: SyncOptions = {}, +): Promise { + const { onProgress, onSyncDetail, timeoutMs, syncMode = 'full', requireStrictSync = false, log, signal } = options; + const { facade } = bundle; + + throwIfCancelled(signal); + + log?.('sync', 'Starting facade (connecting to node and indexer)...'); + const [, emptyStreams] = await Promise.all([startFacade(bundle), readEmptyStreams(bundle.indexerWsUrl, syncMode)]); + bundle.emptyStreams = emptyStreams; + if (emptyStreams.zswap || emptyStreams.dust) { + log?.('sync', `The chain has no events in: ${[emptyStreams.zswap && 'zswap', emptyStreams.dust && 'dust'].filter(Boolean).join(', ')}`); + } + log?.('sync', 'Facade started, subscribing to state...'); + throwIfCancelled(signal); + + const effectiveTimeout = timeoutMs ?? SYNC_TIMEOUT_MS; + log?.('sync', `Sync timeout: ${effectiveTimeout / 1000}s, mode: ${syncMode}`); + + // Cached-restore grace: if the facade was restored from cache and we're a + // READ operation, accept dust as "good enough" once non-dust wallets are + // strictly complete AND `CACHED_RESTORE_DUST_GRACE_MS` has elapsed — without + // waiting for the dust-wallet SDK's `isConnected` flag (known bug — never + // flips on idle preprod streams). Writes set `requireStrictSync` to opt out, + // because ZK proofs built against a stale commitment tree are rejected by + // the chain as MalformedError::InvalidDustSpendProof (error code 170). + const graceEligible = !requireStrictSync && bundle.restoredFromCache; + const startedAt = Date.now(); + + return new Promise((resolveSync, rejectSync) => { + let resolved = false; + let emissionCount = 0; + const onAbort = (): void => { + if (resolved) return; + resolved = true; + clearTimeout(timeout); + log?.('sync', `Sync cancelled after ${emissionCount} emissions`); + rejectSync(new CancelledError()); + }; + const resolve = (state: FacadeState): void => { signal?.removeEventListener('abort', onAbort); resolveSync(state); }; + const reject = (err: unknown): void => { signal?.removeEventListener('abort', onAbort); rejectSync(err); }; + let lastPendingKey = ''; + + let lastState: FacadeState | null = null; + + const timeout = setTimeout(() => { + if (!resolved) { + log?.('sync', `Sync timed out after ${effectiveTimeout / 1000}s (${emissionCount} emissions)`); + if (lastState) { + try { + const up = lastState.unshielded.progress; + log?.('sync', ` unshielded: applied=${up.appliedId} highest=${up.highestTransactionId} complete=${up.isStrictlyComplete()}`); + const dp = lastState.dust.progress; + log?.('sync', ` dust: applied=${dp.appliedIndex} highest=${dp.highestRelevantWalletIndex} complete=${dp.isStrictlyComplete()} connected=${dp.isConnected}`); + if (syncMode === 'full') { + const sp = lastState.shielded.progress; + log?.('sync', ` shielded: complete=${sp.isStrictlyComplete()}`); + } + } catch { /* best-effort */ } + } + reject(new Error('Wallet sync timed out')); + } + }, effectiveTimeout); + + bundle.keepAlive = facade.state().subscribe({ + next: (state) => { + if (resolved) return; + emissionCount++; + lastState = state; + + // Stale-cache detection: if we restored from cache and our cached + // appliedIndex exceeds the chain's currently-reported highest, the + // cache is from a different chain (common on localnet restarts). + // Runs on every emission so the error fires before `isFacadeSynced` + // might accept a stale state (sync can "complete" against cached + // data before any chain-tip data arrives on emission 1-2). + if (bundle.restoredFromCache) { + const staleReason = detectStaleCache(state); + if (staleReason) { + resolved = true; + clearTimeout(timeout); + log?.('sync', `Stale cache detected: ${staleReason}`); + reject(new StaleCacheError(staleReason)); + return; + } + } + + if (onProgress) { + const progress = state.unshielded.progress; + if (progress) { + const applied = Number(progress.appliedId); + const highest = Number(progress.highestTransactionId); + onProgress(Math.min(applied, highest), highest); + } + } + + // Report which wallets are still syncing (only the ones this mode needs). + const pending: string[] = []; + try { + if ((syncMode === 'full' || syncMode === 'no-dust') && !state.shielded.progress.isStrictlyComplete()) pending.push('shielded'); + if (syncMode !== 'no-dust' && isDustSyncPending(state, emptyStreams)) pending.push('dust'); + if (!state.unshielded.progress.isStrictlyComplete()) pending.push('unshielded'); + } catch { /* best-effort */ } + + if (pending.length > 0) { + onSyncDetail?.(pending.join(', ')); + const pendingKey = pending.join(','); + if (emissionCount === 1 || pendingKey !== lastPendingKey || emissionCount % 100 === 0) { + log?.('sync', `Waiting on: ${pending.join(', ')} (emission #${emissionCount})`); + lastPendingKey = pendingKey; + } + } + + // Primary: strict sync per mode (uses the isFacadeSynced workaround for + // the dust isConnected bug — see that function above). + if (isFacadeSynced(state, syncMode, emptyStreams)) { + resolved = true; + clearTimeout(timeout); + log?.('sync', `Sync complete after ${emissionCount} emissions`); + resolve(state); + return; + } + + // Grace fallback: treat "everything except dust synced, and grace + // elapsed" as done. Reuses the existing no-dust predicate so the two + // completion paths can't drift. + if (graceEligible) { + const elapsed = Date.now() - startedAt; + if (elapsed >= CACHED_RESTORE_DUST_GRACE_MS && isFacadeSynced(state, 'no-dust', emptyStreams)) { + resolved = true; + clearTimeout(timeout); + log?.('sync', `Sync resolved via cached-restore grace (${elapsed}ms, ${emissionCount} emissions)`); + resolve(state); + } + } + }, + error: (err) => { + if (!resolved) { + log?.('sync', `Sync error: ${(err as Error).message}`); + clearTimeout(timeout); + reject(err); + } + }, + }); + if (!resolved) signal?.addEventListener('abort', onAbort, { once: true }); + }); +} + +// Cached-restore grace period: after this long, if the facade was built from +// a cache, accept dust as "good enough" without waiting for the SDK's +// isConnected flag (which has a known bug and may never flip). +const CACHED_RESTORE_DUST_GRACE_MS = 10_000; + +/** + * Raised when a restored facade's cached state references event ids that + * don't exist on the current chain — typically because the local chain was + * reset (e.g. `mn localnet clean`) while the cache on disk kept the old + * wallet state. Commands should catch this and clear the cache before retrying. + */ +export class StaleCacheError extends Error { + readonly code = 'STALE_CACHE'; + constructor(detail: string) { + super( + `Cached wallet state is stale (from a previous chain). ${detail}\n` + + `Run: midnight cache clear --wallet --network \n` + + `Or: midnight cache clear (wipe all caches)`, + ); + this.name = 'StaleCacheError'; + } +} + +/** + * Detect a cache whose `appliedIndex` exceeds the chain's currently-reported + * `highestRelevantWalletIndex` — a signature of a cache restored against a + * different chain (new localnet, networkId reuse, etc). + * + * Returns a human-readable reason string if stale, otherwise undefined. + * Only checks unshielded (the indexer sends progress on every block so its + * `highestTransactionId` is populated reliably — dust's `highest` can be 0 + * genuinely on a quiet stream even when cache is valid, so checking it would + * produce false positives). + */ +export function detectStaleCache(state: FacadeState): string | undefined { + const { appliedId: applied, highestTransactionId: highest } = state.unshielded.progress; + // We require highest > 0 to ensure the indexer has reported at least once; + // otherwise we can't make a reliable comparison. applied > highest means + // our local state has applied events the chain doesn't have. + if (highest > 0n && applied > highest) { + return `unshielded cache applied=${applied} but chain highest=${highest}.`; + } + return undefined; +} + +/** + * Wait for a fully-populated lite-synced state (unshielded + dust data ready). + * + * The index fallback in `isFacadeSynced` resolves sync before the dust wallet + * has processed its events into `balance()` and `availableCoins`. This helper + * waits for dust's `isStrictlyComplete()` (which requires `isConnected` — set + * when actual DustLedgerEvents arrive and populate state data). + * + * On active chains (preprod): resolves quickly — a few seconds after lite sync. + * On idle chains (no dust events): times out after 15s, returns best-effort state. + * + * Use this for data-reading calls (dust status, balances) where accurate state + * matters. Use `isFacadeSynced` with lite mode for sync gating where the index + * fallback is acceptable. + */ +export async function waitForLiteSyncedState(bundle: FacadeBundle): Promise { + const isDataReady = (s: FacadeState): boolean => { + const unshieldedOk = s.unshielded.progress.isStrictlyComplete(); + const dustOk = s.dust.progress.isStrictlyComplete(); + return unshieldedOk && dustOk; + }; + + try { + return await rx.firstValueFrom( + bundle.facade.state().pipe( + rx.filter(isDataReady), + rx.timeout(15_000), + ) + ); + } catch { + // Timeout — idle chain where dust never connects (no DustLedgerEvents). + // Fall back to the latest available state (dust balance will be 0, which + // is correct for a chain with no dust activity). + return await rx.firstValueFrom(bundle.facade.state()); + } +} + +/** + * Wait for dust coins to actually be available (not just synced). + * + * `waitForLiteSyncedState` checks sync progress (`isStrictlyComplete`), but that + * resolves before `availableCoins` is populated. This helper waits until the dust + * wallet has at least one available coin, which is required for any write operation + * (balancing, transfers, swaps). + * + * On preprod: may take 10-30s after sync for dust coins to appear. + * Timeout falls back gracefully — the server still starts, but writes will fail + * until dust becomes available (the retry wrapper in dapp-connector handles that). + */ +/** Whether the wallet holds dust it can spend on fees right now. */ +export function hasDustAvailable(state: FacadeState): boolean { + return state.dust.availableCoins.length > 0 || state.dust.balance(new Date()) > 0n; +} + +export async function waitForDustAvailable(bundle: FacadeBundle, timeoutMs = 60_000, signal?: AbortSignal): Promise { + throwIfCancelled(signal); + const cancelled = signal === undefined ? rx.NEVER : rx.fromEvent(signal, 'abort'); + try { + return await rx.firstValueFrom( + bundle.facade.state().pipe( + rx.filter(hasDustAvailable), + rx.timeout(timeoutMs), + rx.takeUntil(cancelled), + ) + ); + } catch { + throwIfCancelled(signal); + // Timeout — dust may not be available yet (fresh wallet, slow chain). + // Return latest state; caller should handle gracefully. + return await rx.firstValueFrom(bundle.facade.state()); + } +} + +/** + * Quick sync for pre-send validation. + * Shorter timeout — just catches stale UTXOs before building a transaction. + */ +export async function quickSync(bundle: FacadeBundle, syncMode: SyncMode = 'full'): Promise { + return rx.firstValueFrom( + bundle.facade.state().pipe( + rx.filter((state) => isFacadeSynced(state, syncMode, bundle.emptyStreams)), + rx.timeout(PRE_SEND_SYNC_TIMEOUT_MS), + ) + ); +} + +/** + * Clean shutdown of the wallet facade. + */ +export async function stopFacade(bundle: FacadeBundle): Promise { + bundle.keepAlive?.unsubscribe(); + // Timeout facade.stop() — wallets may hang if in a bad state (e.g. dust wallet stuck). + // Don't block the caller forever; let the old facade be GC'd. + await Promise.race([ + bundle.facade.stop(), + new Promise(resolve => setTimeout(resolve, 5_000)), + ]); +} + diff --git a/packages/engine-beta/src/fee-only-check.ts b/packages/engine-beta/src/fee-only-check.ts new file mode 100644 index 00000000..efcb6c51 --- /dev/null +++ b/packages/engine-beta/src/fee-only-check.ts @@ -0,0 +1,124 @@ +// Fee-wallet scope check for `mn serve --approve-fees`. +// +// Balancing Dust-only limits what the wallet ADDS to a dApp's transaction, not +// what it AUTHORIZES: signing an unbound recipe signs the dApp's own +// transaction, and the unshielded signer fills every empty signature slot of +// every unshielded input, whoever owns it. So before a balance may count as +// fee-only, the dApp's transaction itself has to leave the wallet nothing to +// sign and nothing to fund but the fee. + +import { + Transaction, + addressFromKey, + type Binding, + type Bindingish, + type PreBinding, + type Proof, + type Proofish, + type SignatureEnabled, + type SignatureVerifyingKey, + type UnshieldedOffer, +} from '@midnightntwrk/ledger-v9'; + +/** How far along the dApp's transaction is: `balanceUnsealedTransaction` or `balanceSealedTransaction`. */ +export type DAppTxStage = 'unsealed' | 'sealed'; + +export type FeeCheckTransaction = Transaction; + +/** The guaranteed section is segment 0; each intent's fallible section is its own segment. */ +const GUARANTEED_SEGMENT = 0; + +/** + * Read a dApp's transaction as ledger 9 at its stage. Throws when the bytes are + * not a proven, signature-enabled transaction of that stage. + */ +export function readDAppTransaction(bytes: Uint8Array, stage: DAppTxStage): FeeCheckTransaction { + return stage === 'unsealed' + ? Transaction.deserialize('signature', 'proof', 'pre-binding', bytes) + : Transaction.deserialize('signature', 'proof', 'binding', bytes); +} + +/** Every segment a transaction has: the guaranteed one (0) and each intent's and fallible offer's. */ +export function segmentsOf(tx: FeeCheckTransaction): Set { + return new Set([ + GUARANTEED_SEGMENT, + ...(tx.intents?.keys() ?? []), + ...(tx.fallibleOffer?.keys() ?? []), + ]); +} + +/** The intents whose TTL is at or before `now`: the chain refuses a transaction carrying one. */ +export function expiredIntents(tx: FeeCheckTransaction, now: Date): Array<{ segment: number; ttl: Date }> { + return [...(tx.intents ?? new Map())] + .filter(([, intent]) => intent.ttl.getTime() <= now.getTime()) + .map(([segment, intent]) => ({ segment, ttl: intent.ttl })); +} + +export interface UnshieldedInputRef { + /** Where the input sits, e.g. "intent 1 guaranteed unshielded input 0". */ + where: string; + owner: SignatureVerifyingKey; + /** Whether the offer carries a signature for this input. */ + signed: boolean; +} + +/** Every unshielded input of every intent, guaranteed section before fallible. */ +export function unshieldedInputs(tx: FeeCheckTransaction): UnshieldedInputRef[] { + const refs: UnshieldedInputRef[] = []; + for (const [segment, intent] of tx.intents ?? new Map()) { + const offers: Array<[string, UnshieldedOffer | undefined]> = [ + ['guaranteed', intent.guaranteedUnshieldedOffer], + ['fallible', intent.fallibleUnshieldedOffer], + ]; + for (const [section, offer] of offers) { + offer?.inputs.forEach((input, i) => refs.push({ + where: `intent ${segment} ${section} unshielded input ${i}`, + owner: input.owner, + signed: offer.signatures[i] !== undefined, + })); + } + } + return refs; +} + +/** + * Why paying only the Dust fee for `tx` would not keep the wallet to the fee. + * Empty when it would. Refuses when: + * - an unshielded input is owned by `walletKey` (the dApp would spend the wallet's Night); + * - an unshielded input has no signature (the wallet's signer would sign it); + * - a segment is short of any non-Dust token (Dust-only balancing can't fund it); + * - the transaction is a rewards claim, not a standard transaction. + */ +export function feeOnlyRefusals(tx: FeeCheckTransaction, walletKey: SignatureVerifyingKey): string[] { + if (tx.rewards !== undefined) { + return ['it is a rewards claim, not a standard transaction']; + } + + const reasons: string[] = []; + const walletAddress = addressFromKey(walletKey); + + for (const { where, owner, signed } of unshieldedInputs(tx)) { + if (addressFromKey(owner) === walletAddress) { + reasons.push(`${where} spends this wallet's own funds`); + } + if (!signed) { + reasons.push(`${where} is unsigned, so this wallet would sign it`); + } + } + + for (const segment of segmentsOf(tx)) { + let imbalances: Map<{ tag: string; raw?: string }, bigint>; + try { + imbalances = tx.imbalances(segment); + } catch (err) { + reasons.push(`segment ${segment}'s balance could not be computed: ${(err as Error).message ?? err}`); + continue; + } + for (const [token, value] of imbalances) { + if (token.tag === 'dust' || value >= 0n) continue; + reasons.push(`segment ${segment} is short ${-value} of ${token.tag} token ${token.raw}, which a Dust-only balance can't fund`); + } + } + + return reasons; +} diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts new file mode 100644 index 00000000..106df18e --- /dev/null +++ b/packages/engine-beta/src/index.ts @@ -0,0 +1,68 @@ +// The engine for the SDK's beta set, which stagenet runs: the wallet SDK's +// 5.0 beta split packages, ledger 9 rc.3 and midnight-js 5 beta, as mn pins +// them. + +import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; +import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; +import { blockLimitsOf } from './ledger-parameters.ts'; +import { rawContractState } from './contract-providers.ts'; +import { assertAddress } from './addresses.ts'; +import { inspectTxHex } from './tx-inspect.ts'; +import { betaWallet } from './wallet.ts'; +import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; + +export const betaEngine: Engine = { + set: 'beta', + keys: { + unshieldedAddress: deriveUnshieldedAddress, + unshieldedAddresses: deriveAllAddresses, + shieldedAddress: deriveShieldedAddressString, + shieldedAddresses: deriveAllShieldedAddresses, + dustPublicKeyHex: dustPublicKeyHexFromSeed, + shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, + assertAddress, + }, + ledger: { + blockLimits: blockLimitsOf, + nightTokenId: () => ledger.unshieldedToken().raw, + readTransaction: inspectTxHex, + }, + contracts: { + rawState: rawContractState, + acceptsPrivateStatePassword(password) { + try { + validatePassword(password); + return true; + } catch { + return false; + } + }, + scripts: { + packages: SCRIPT_PACKAGES, + packageFolder, + compactRuntimeVersion, + // The compiler release whose contracts compact-runtime 0.18 runs (compactc 0.33, built with --feature-zkir-v3). + compiler: 'compactc 0.33', + acceptsRuntime(runtimeVersion) { + try { + checkRuntimeVersion(runtimeVersion); + return true; + } catch { + return false; + } + }, + deploy: generateDeployScript, + call: generateCallScript, + state: generateStateScript, + }, + }, + readers: { + shieldedBalance: readShieldedBalanceCached, + }, + wallet: betaWallet, +}; diff --git a/packages/engine-beta/src/ledger-parameters.ts b/packages/engine-beta/src/ledger-parameters.ts new file mode 100644 index 00000000..decf682d --- /dev/null +++ b/packages/engine-beta/src/ledger-parameters.ts @@ -0,0 +1,29 @@ +// A chain's block limits, from its ledger parameters' bytes. The ledger +// doesn't expose the limits themselves, so each is probed through +// normalizeFullness: normalized = value / limit, so limit = value / normalized. + +import * as ledger from '@midnightntwrk/ledger-v9'; +import type { BlockLimits } from '@kuiralabs/midnight-cli-core/lib/engine'; + +type Dimension = keyof BlockLimits; + +function probeDimension(params: ledger.LedgerParameters, dimension: Dimension, probeValue: bigint): number { + const cost: Record = { readTime: 0n, computeTime: 0n, blockUsage: 0n, bytesWritten: 0n, bytesChurned: 0n }; + cost[dimension] = probeValue; + // Cast required: the shape matches the ledger's SyntheticCost, which TS can't verify for the opaque SDK type. + const normalized = params.normalizeFullness(cost as unknown as ledger.SyntheticCost); + const normalizedValue = (normalized as Record)[dimension]!; + return Math.round(Number(probeValue) / normalizedValue); +} + +/** The block limits in serialized ledger parameters (hex). Throws when the bytes aren't this ledger's parameters. */ +export function blockLimitsOf(parametersHex: string): BlockLimits { + const params = ledger.LedgerParameters.deserialize(Buffer.from(parametersHex, 'hex')); + return { + readTime: probeDimension(params, 'readTime', 1_000_000_000n), + computeTime: probeDimension(params, 'computeTime', 1_000_000_000n), + blockUsage: probeDimension(params, 'blockUsage', 10_000n), + bytesWritten: probeDimension(params, 'bytesWritten', 10_000n), + bytesChurned: probeDimension(params, 'bytesChurned', 1_000_000n), + }; +} diff --git a/packages/engine-beta/src/raw-state.ts b/packages/engine-beta/src/raw-state.ts new file mode 100644 index 00000000..93b18a95 --- /dev/null +++ b/packages/engine-beta/src/raw-state.ts @@ -0,0 +1,34 @@ +// A deployed contract's ledger state, read without its compiled contract: the +// untyped tree the chain stores, as plain JSON. Without the contract's ledger +// layout the fields have no names, so cells show their field-aligned bytes in +// hex and maps show their size, as the parsed state does. + +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; + +const toHex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); + +/** The parts of the runtime's `StateValue` read here (the runtime version the indexer decodes with varies). */ +interface StateValueLike { + type(): 'null' | 'cell' | 'map' | 'array' | 'boundedMerkleTree'; + asCell(): { value: Uint8Array[] }; + asMap(): { keys(): unknown[] } | undefined; + asArray(): StateValueLike[] | undefined; + asBoundedMerkleTree(): { height: number; root(): { value: Uint8Array[] } | undefined } | undefined; +} + +export function describeRawState(state: StateValueLike): RawStateValue { + switch (state.type()) { + case 'null': + return { type: 'null' }; + case 'cell': + return { type: 'cell', value: state.asCell().value.map(toHex) }; + case 'array': + return { type: 'array', items: (state.asArray() ?? []).map(describeRawState) }; + case 'map': + return { type: 'map', size: state.asMap()?.keys().length ?? 0 }; + case 'boundedMerkleTree': { + const tree = state.asBoundedMerkleTree(); + return { type: 'boundedMerkleTree', height: tree?.height ?? 0, root: tree?.root()?.value.map(toHex) ?? null }; + } + } +} diff --git a/packages/engine-beta/src/shielded-direct-cache.ts b/packages/engine-beta/src/shielded-direct-cache.ts new file mode 100644 index 00000000..2bccba78 --- /dev/null +++ b/packages/engine-beta/src/shielded-direct-cache.ts @@ -0,0 +1,186 @@ +// Cache for the indexer-direct shielded (zswap) reader. +// +// Persists a serialized `ZswapLocalState` + the last event id we applied to +// disk, keyed by (network, shielded coin public key). On next run we restore the +// state and resume the subscription from `lastAppliedEventId + 1` — delta-sync +// instead of re-reading the full zswap event history (which is ~50-70s cold on +// hosted networks; incremental is ~instant). +// +// Security: the cached state contains owned coins but NOT the secret keys. Same +// sensitivity as the wallet file (mode 0o600). + +import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { randomBytes } from 'node:crypto'; + +import * as ledger from '@midnightntwrk/ledger-v9'; + +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { deriveShieldedSeed } from './derivation.ts'; +import { readShieldedBalanceDirect, type ShieldedDirectOptions } from './shielded-direct.ts'; +import { fetchEventTip, isCursorBeyondTip } from '@kuiralabs/midnight-chain/lib/event-tip'; +import { clearShieldedDirectCache, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; + +// v2: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis +// hash, so the chain-id guard can't keep a ledger-8 cache off a ledger-9 chain. +const SHIELDED_CACHE_VERSION = 2; + +interface ShieldedCacheFile { + version: number; + network: string; + coinPublicKeyHex: string; + lastAppliedEventId: number; + /** Genesis block hash — invalidates the cache on chain reset. Optional for back-compat. */ + chainId?: string; + timestamp: string; + zswapState: string; // hex-encoded ZswapLocalState.serialize() +} + +export interface ShieldedCacheEntry { + state: ledger.ZswapLocalState; + lastAppliedEventId: number; +} + +/** + * Derive the shielded coin public key (as hex) from a wallet seed. Used to key + * shielded-direct cache entries by wallet. + */ +export function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string { + const keys = ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(seedBuffer)); + return keys.coinPublicKey; +} + + +/** + * Load a cached ZswapLocalState for the given (network, coin pubkey). + * Returns null if missing, corrupt, version-mismatched, network/pubkey-mismatched, + * or — when `expectedChainId` is given and the cache recorded one — if the chain + * genesis hash no longer matches (chain reset). A stale-chain cache is discarded + * so a localnet reset can't surface a wrong balance from an old chain's coins. + */ +export function loadShieldedCache( + network: string, + pubkeyHex: string, + cacheDir?: string, + expectedChainId?: string, +): ShieldedCacheEntry | null { + const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + if (!existsSync(path)) return null; + + try { + const parsed: ShieldedCacheFile = JSON.parse(readFileSync(path, 'utf-8')); + if (parsed.version !== SHIELDED_CACHE_VERSION) return null; + if (parsed.network !== network) return null; + if (parsed.coinPublicKeyHex !== pubkeyHex) return null; + if (typeof parsed.lastAppliedEventId !== 'number') return null; + if (typeof parsed.zswapState !== 'string') return null; + if (expectedChainId && parsed.chainId && parsed.chainId !== expectedChainId) return null; + + const state = ledger.ZswapLocalState.deserialize(new Uint8Array(Buffer.from(parsed.zswapState, 'hex'))); + return { state, lastAppliedEventId: parsed.lastAppliedEventId }; + } catch { + return null; + } +} + +/** + * Serialize a ZswapLocalState + lastAppliedEventId to disk atomically. + */ +export function saveShieldedCache( + network: string, + pubkeyHex: string, + state: ledger.ZswapLocalState, + lastAppliedEventId: number, + cacheDir?: string, + chainId?: string, +): void { + const data: ShieldedCacheFile = { + version: SHIELDED_CACHE_VERSION, + network, + coinPublicKeyHex: pubkeyHex, + lastAppliedEventId, + timestamp: new Date().toISOString(), + zswapState: Buffer.from(state.serialize()).toString('hex'), + ...(chainId ? { chainId } : {}), + }; + + const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + const dir = dirname(path); + + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + } + + const tmpPath = path + `.tmp.${randomBytes(4).toString('hex')}`; + try { + writeFileSync(tmpPath, JSON.stringify(data), { mode: FILE_MODE }); + renameSync(tmpPath, path); + } catch (err) { + try { unlinkSync(tmpPath); } catch { /* best-effort */ } + throw err; + } +} + + +export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; + +/** + * Read the shielded NIGHT balance for a wallet seed, using (and refreshing) the + * indexer-direct cache. Loads any cached ZswapLocalState, resumes the + * `zswapLedgerEvents` subscription from the last applied event, and persists the + * extended state. First sync walks the full history (~50-70s on hosted nets); + * subsequent calls are delta-syncs. + */ +export async function readShieldedBalanceCached( + seedBuffer: Buffer, + network: string, + indexerWS: string, + options: ShieldedCachedOptions = {}, +): Promise { + const secretKeys = ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(seedBuffer)); + const pubkeyHex = secretKeys.coinPublicKey; + + // State resumed from another indexer's event ids would replay the wrong events. + bindCachesToIndexer(network, indexerWS); + let cached = options.forceFresh ? null : loadShieldedCache(network, pubkeyHex, undefined, options.chainId); + // A cursor past the chain's latest event: the chain was reset under the cache. + if (cached && isCursorBeyondTip(cached.lastAppliedEventId, await fetchEventTip(indexerWS, 'zswap'))) { + clearShieldedDirectCache(network, pubkeyHex); + cached = null; + } + const startFromId = cached ? cached.lastAppliedEventId + 1 : 0; + + const result = await readShieldedBalanceDirect(secretKeys, indexerWS, { + initialState: cached?.state, + startFromId, + onProgress: options.onProgress, + signal: options.signal, + timeoutMs: options.timeoutMs, + // Persist after each chunk so a Ctrl+C / kill during a cold ~70s sync + // doesn't lose progress — the next call resumes from the last checkpoint. + onCheckpoint: (state, lastAppliedEventId) => { + try { saveShieldedCache(network, pubkeyHex, state, lastAppliedEventId, undefined, options.chainId); } catch { /* best-effort */ } + }, + }); + + // Only write if we advanced or this is a first sync. If we had a cache and zero + // new events arrived, leave the on-disk file untouched. + if (result.lastAppliedEventId >= 0) { + saveShieldedCache(network, pubkeyHex, result.state, result.lastAppliedEventId, undefined, options.chainId); + } else if (!cached) { + saveShieldedCache(network, pubkeyHex, result.state, -1, undefined, options.chainId); + } + + return { + balance: result.balance, + availableCoins: result.availableCoins, + eventCount: result.eventCount, + lastAppliedEventId: result.lastAppliedEventId >= 0 + ? result.lastAppliedEventId + : (cached?.lastAppliedEventId ?? -1), + fromCache: cached !== null, + partial: result.partial, + }; +} diff --git a/packages/engine-beta/src/shielded-direct.ts b/packages/engine-beta/src/shielded-direct.ts new file mode 100644 index 00000000..c4e49a19 --- /dev/null +++ b/packages/engine-beta/src/shielded-direct.ts @@ -0,0 +1,197 @@ +// Direct-from-indexer shielded (zswap) balance reader. +// +// Bypasses the shielded-wallet SDK facade (minutes-to-hours + 16GB OOM on cold +// hosted syncs). Subscribes to `zswapLedgerEvents(id)` ourselves, deserializes +// each raw hex event via `ledger.Event.deserialize`, and replays them into a +// `ZswapLocalState` with `replayEventsWithChanges(secretKeys, events)` — which +// reconciles BOTH received and spent coins locally using the full secret keys +// (the collapsed `connect`/`shieldedTransactions` session is encryption-only and +// cannot see spends, so it is not used). Reads the NIGHT balance off the coin +// set. Mirrors the dust-direct reader's checkpoint/resume shape. +// +// The batched replay keeps the working set bounded (~155MB even on preview), +// unlike the SDK's cold sync. + +import * as ledger from '@midnightntwrk/ledger-v9'; + +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; + +const SUBSCRIPTION_QUERY = ` + subscription ZswapLedgerEvents($id: Int) { + zswapLedgerEvents(id: $id) { + id + raw + maxId + } + } +`; + +interface RawZswapEvent { + id: number; + raw: string; + maxId: number; +} + +export interface ShieldedDirectResult { + /** Native (NIGHT) shielded balance in atomic units. */ + balance: bigint; + /** Number of spendable NIGHT coins tracked. */ + availableCoins: number; + /** Events applied in this run. */ + eventCount: number; + /** Final ZswapLocalState — callers serialize this for caching. */ + state: ledger.ZswapLocalState; + /** Id of the last event applied in this run. -1 if none arrived. */ + lastAppliedEventId: number; + /** + * True iff the sync stopped before catching up to the indexer's tip (timeout + * or abort). The returned state + lastAppliedEventId are still valid — persist + * them and re-call to resume from the checkpoint. False means we caught up to + * the chain head (or there were no events to apply). + */ + partial: boolean; +} + +export interface ShieldedDirectOptions { + /** Called with (eventsApplied, maxIdSeen) whenever a new event arrives. */ + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + /** + * Called after every chunk of events is applied, with the current state + last + * applied event id. Lets the caller persist a checkpoint so a Ctrl+C / timeout + * doesn't lose 50k events of work. Keep the callback cheap (a file write is + * fine, network is not). + */ + onCheckpoint?: (state: ledger.ZswapLocalState, lastAppliedEventId: number) => void; + /** + * Soft ceiling for the whole subscription. On expiry the call resolves with + * `partial: true` and whatever state has been applied — never throws away + * progress. Default: 600s. + */ + timeoutMs?: number; + /** If no event arrives for this long (and we've received some), treat as caught up. Default: 5s. */ + idleMs?: number; + /** + * If no event is received AT ALL within this window after connecting, treat the + * stream as empty (nothing to catch up on) and return — but only when resuming + * from a cached state. Default: 3s. + */ + initialSilenceMs?: number; + /** Abort the subscription mid-flight. */ + signal?: AbortSignal; + /** Resume from this cached state instead of building fresh. */ + initialState?: ledger.ZswapLocalState; + /** Subscribe starting at this event id (inclusive). Default: 0. */ + startFromId?: number; +} + +/** Sum spendable native-token (NIGHT) coins in a state. */ +function nativeBalance(state: ledger.ZswapLocalState): { balance: bigint; count: number } { + // Shielded NIGHT coins carry the unshielded raw token type (matches balance.ts / facade). + const night = ledger.unshieldedToken().raw; + let balance = 0n; + let count = 0; + for (const coin of state.coins) { + if (coin.type === night) { + balance += coin.value; + count++; + } + } + return { balance, count }; +} + +/** + * Subscribe to zswap ledger events from `startFromId`, deserialize, replay into a + * `ZswapLocalState` with the full secret keys (reconciling receives AND spends), + * and return the NIGHT balance plus the state + resume cursor. + * + * "Caught up" is detected when the latest `id` received equals `maxId`. + */ +export function readShieldedBalanceDirect( + secretKeys: ledger.ZswapSecretKeys, + indexerWS: string, + options: ShieldedDirectOptions = {}, +): Promise { + const { + onProgress, + onCheckpoint, + timeoutMs = 600_000, + idleMs = 5_000, + initialSilenceMs = 3_000, + signal, + initialState, + startFromId = 0, + } = options; + + // Apply events in chunks so the final step is cheap, the event loop can breathe + // between WASM calls, and the working set stays bounded on large chains. + const CHUNK_SIZE = 500; + + let state = initialState ?? new ledger.ZswapLocalState(); + const pending: ledger.Event[] = []; + let eventsAppliedCount = 0; + let lastEventId = startFromId - 1; + let maxIdSeen = -1; + + // Apply events in chunks so the final step is cheap, the event loop can breathe + // between WASM calls, and the working set stays bounded on large chains. + // Checkpoint after each chunk so a timeout/abort/crash doesn't lose the work. + const flushPending = () => { + if (pending.length === 0) return; + state = state.replayEventsWithChanges(secretKeys, pending).state; + eventsAppliedCount += pending.length; + pending.length = 0; + if (onCheckpoint && lastEventId >= 0) { + try { onCheckpoint(state, lastEventId); } catch { /* best-effort */ } + } + }; + + return subscribeGraphqlWs(indexerWS, { + query: SUBSCRIPTION_QUERY, + variables: { id: startFromId }, + idleMs, + timeoutMs, + // Fast-return only when resuming from cached state; a fresh cold sync must + // wait for its (possibly slow) first event. + initialSilenceMs: initialState ? initialSilenceMs : 0, + signal, + onNext: (data) => { + const evt = (data as { zswapLedgerEvents?: RawZswapEvent } | undefined)?.zswapLedgerEvents; + if (!evt) return false; + let event: ledger.Event; + try { + event = ledger.Event.deserialize(new Uint8Array(Buffer.from(evt.raw, 'hex'))); + } catch (err) { + throw new Error(`Failed to deserialize zswap event ${evt.id}: ${(err as Error).message}`); + } + pending.push(event); + // Update lastEventId BEFORE flushing so the checkpoint cursor matches the + // events actually applied (resuming at cursor+1 must not re-apply). + lastEventId = evt.id; + if (evt.maxId > maxIdSeen) maxIdSeen = evt.maxId; + if (pending.length >= CHUNK_SIZE) { + try { flushPending(); } catch (err) { + throw new Error(`Failed applying zswap events: ${(err as Error).message}`); + } + } + onProgress?.(eventsAppliedCount + pending.length, maxIdSeen); + // Caught up when we've received the final event in the current stream. + return lastEventId >= maxIdSeen; + }, + buildResult: (partial) => { + try { + flushPending(); + const { balance, count } = nativeBalance(state); + return { + balance, + availableCoins: count, + eventCount: eventsAppliedCount, + state, + lastAppliedEventId: lastEventId, + partial, + }; + } catch (err) { + throw new Error(`Failed to build shielded state: ${(err as Error).message}`); + } + }, + }); +} diff --git a/packages/engine-beta/src/sign-recipe.ts b/packages/engine-beta/src/sign-recipe.ts new file mode 100644 index 00000000..b46e30d8 --- /dev/null +++ b/packages/engine-beta/src/sign-recipe.ts @@ -0,0 +1,108 @@ +// Signing a balancing recipe with the wallet's keystore, around a wallet-sdk +// 2.0.0-rc.0 defect. +// +// For an unbound recipe the facade signs the dApp's own transaction too. Its +// unshielded signer builds a full per-input signature list (signatures already +// there kept, empty slots filled with the wallet's) and hands it to ledger-v9's +// UnshieldedOffer.addSignatures, which appends. So every signature the dApp +// already attached comes back twice, and the ledger refuses the transaction +// ("mismatch between number of inputs (1) and signatures (2)"). +// +// A dApp transaction whose unshielded inputs are all signed leaves the wallet +// nothing to sign in it, so mn signs only its own balancing transaction. One +// with no signed inputs signs correctly through the facade. One that mixes +// signed and unsigned inputs can't be signed correctly, so it is refused. +// +// Balancing unshielded value in an unbound transaction merges the wallet's +// inputs and outputs into the dApp's own intent, which changes the data the +// dApp signed. So a transaction whose unshielded inputs are signed can only be +// balanced for Dust; one that also needs unshielded value is refused. + +import type { Signature } from '@midnightntwrk/ledger-v9'; +import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk-facade'; +import { readDAppTransaction, segmentsOf, unshieldedInputs, type FeeCheckTransaction } from './fee-only-check.ts'; + +export type SignSegment = (data: Uint8Array) => Promise; + +/** Whether a transaction's unshielded inputs carry signatures: none of them, all of them, or some. */ +export type UnshieldedSignatures = 'none' | 'all' | 'some'; + +export function unshieldedSignatures(tx: FeeCheckTransaction): UnshieldedSignatures { + const inputs = unshieldedInputs(tx); + const signed = inputs.filter((input) => input.signed).length; + if (signed === 0) return 'none'; + return signed === inputs.length ? 'all' : 'some'; +} + +/** A dApp transaction with both signed and unsigned unshielded inputs, which the wallet can't sign correctly. */ +export class PartlySignedTransactionError extends Error { + constructor() { + super( + 'The transaction has both signed and unsigned unshielded inputs. This wallet can\'t add its signatures to it ' + + 'without duplicating the existing ones (a wallet SDK limitation): send it with every unshielded input signed, ' + + 'or with none signed.', + ); + this.name = 'PartlySignedTransactionError'; + Object.setPrototypeOf(this, PartlySignedTransactionError.prototype); + } +} + +/** A dApp transaction with signed unshielded inputs that also needs unshielded value from the wallet. */ +export class SignedTransactionNeedsUnshieldedError extends Error { + constructor(segments: number[]) { + super( + `The transaction's unshielded inputs are already signed, but segment ${segments.join(', ')} is not balanced in ` + + 'unshielded value. This wallet balances it by adding inputs and outputs to the same intent, which invalidates ' + + 'those signatures. Leave the unshielded inputs unsigned so they are signed after balancing, or balance the ' + + 'sealed transaction with balanceSealedTransaction, which adds a separate intent.', + ); + this.name = 'SignedTransactionNeedsUnshieldedError'; + Object.setPrototypeOf(this, SignedTransactionNeedsUnshieldedError.prototype); + } +} + +/** The segments whose unshielded value doesn't balance: what the wallet would add inputs or outputs for. */ +export function unshieldedImbalanceSegments(tx: FeeCheckTransaction): number[] { + return [...segmentsOf(tx)].filter((segment) => + [...tx.imbalances(segment)].some(([token, value]) => token.tag === 'unshielded' && value !== 0n)); +} + +/** + * The dApp's unsealed transaction can be balanced and signed without breaking + * it. Throws when it can't: some unshielded inputs signed and some not, or all + * signed while `balancesUnshielded` would add unshielded value to it. + */ +export function assertSignable(tx: FeeCheckTransaction, balancesUnshielded: boolean): void { + const state = unshieldedSignatures(tx); + if (state === 'some') throw new PartlySignedTransactionError(); + if (state === 'all' && balancesUnshielded) { + const segments = unshieldedImbalanceSegments(tx); + if (segments.length > 0) throw new SignedTransactionNeedsUnshieldedError(segments); + } +} + +/** Sign a balancing recipe as the facade does, without re-signing a dApp transaction that is already signed. */ +export async function signRecipe( + facade: WalletFacade, + recipe: BalancingRecipe, + signSegment: SignSegment, +): Promise { + if (recipe.type !== 'UNBOUND_TRANSACTION') return facade.signRecipe(recipe, signSegment); + + // Read before anything signs: signing mutates the transaction behind the handle. + const base = readDAppTransaction(recipe.baseTransaction.serialize(), 'unsealed'); + const state = unshieldedSignatures(base); + if (state === 'none') return facade.signRecipe(recipe, signSegment); + if (state === 'some') throw new PartlySignedTransactionError(); + + if (!recipe.balancingTransaction) return recipe; + // The facade's own path for an unproven transaction: unshielded signatures, then a Dust registration's, if any. + const signed = await facade.signRecipe( + { type: 'UNPROVEN_TRANSACTION', transaction: recipe.balancingTransaction }, + signSegment, + ); + if (signed.type !== 'UNPROVEN_TRANSACTION') { + throw new Error(`The wallet SDK signed an unproven transaction into a ${signed.type} recipe`); + } + return { ...recipe, balancingTransaction: signed.transaction }; +} diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts new file mode 100644 index 00000000..20e93074 --- /dev/null +++ b/packages/engine-beta/src/transfer.ts @@ -0,0 +1,520 @@ +// Shared transfer execution — used by both airdrop and transfer commands +// Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries + +import * as ledger from '@midnightntwrk/ledger-v9'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk-address-format'; +import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk-facade'; +import * as rx from 'rxjs'; + +import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; +import { defaultRepository } from './wallet-data-repository.ts'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { + NATIVE_TOKEN_TYPE, + TOKEN_MULTIPLIER, + TX_TTL_MINUTES, + PROOF_TIMEOUT_MS, + DUST_TIMEOUT_MS, + MAX_RETRY_ATTEMPTS, + STALE_UTXO_ERROR_CODE, + DUST_REGISTRATION_TIMEOUT_MS, + DUST_REGISTRATION_RETRY_DELAY_MS, + SYNC_ATTEMPT_TIMEOUT_MS, + DUST_COST_OVERHEAD, + MIN_DUST_FOR_TRANSFER, +} from '@kuiralabs/midnight-cli-core/lib/constants'; + + + + +/** + * Validate recipient address format (bech32m, matching network). + * Returns the decoded UnshieldedAddress for use with the facade. + */ +export function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress { + const networkId = getNetworkId(networkConfig.networkId); + + try { + return MidnightBech32m.parse(address).decode(UnshieldedAddress, networkId); + } catch (err: any) { + throw new Error( + `Invalid recipient address: ${err.message}\n` + + `Expected a bech32m address for network "${networkConfig.networkId}"` + ); + } +} + +// ── Error detection ────────────────────────────────────────────────── + +// SDK error classifiers moved to ./sdk-errors.ts so wallet-data-repository +// can import them without a circular dependency. Re-exported for callers +// that still import from this module. +export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { isColdStartRace, isDustRelatedError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; +import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; +import { assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; +import { awaitDustForFee, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; + +/** How long the transfer retry waits for Dust to grow when the fee is above the pre-flight threshold. */ +const DUST_GROW_WAIT_MS = 10_000; +import { toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; + + +/** Format milliseconds as "Xs" or "Xm Ys" for human-friendly elapsed display. */ +function formatElapsed(ms: number): string { + const totalSeconds = Math.round(ms / 1000); + if (totalSeconds < 60) return `${totalSeconds}s`; + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + return `${minutes}m ${seconds}s`; +} + +// ── Dust registration ──────────────────────────────────────────────── + +/** + * Build, prove and submit a dust registration transaction. Separated so the + * retry wrapper can call it on each attempt with a fresh timestamp. + */ +async function submitDustRegistration( + bundle: FacadeBundle, + nightUtxos: readonly UtxoWithMeta[], + dustReceiverAddress: DustAddress, + waitTimeoutMs: number, +): Promise { + // Timeout-protected: waitForSyncedState() can hang if the dust wallet's + // shareReplay buffer cleared or the indexer is slow. Throw a retryable error + // so registerNightUtxos' retry loop catches it. + await Promise.race([ + bundle.facade.dust.waitForSyncedState(), + new Promise((_, reject) => setTimeout(() => + reject(new Error('Insufficient funds: dust wallet sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), + ]); + + // The registration pays its own fee from the dust these coins generate, so + // wait until they've generated enough. Estimated per attempt: the fee drifts. + const { fee } = await bundle.facade.estimateRegistration(nightUtxos); + await bundle.facade.waitForGeneratedDust(nightUtxos, fee, { timeoutMs: waitTimeoutMs }); + + const recipe = await bundle.facade.registerNightUtxosForDustGeneration( + nightUtxos, + bundle.keystore.getPublicKey(), + bundle.keystore.signDataAsync, + dustReceiverAddress, + ); + let finalized; + try { + finalized = await bundle.facade.finalizeRecipe(recipe); + } catch (err) { + // Registering books the NIGHT UTXOs; release them so a retry can book them again. + try { await bundle.facade.revert(recipe); } catch { /* best-effort */ } + throw err; + } + return await bundle.facade.submitTransaction(finalized); +} + +/** + * Register NIGHT UTXOs for dust generation with retry on error 138. + * + * On a fresh localnet, the estimated dust capacity (allow_fee_payment) may + * be less than the registration fee for several minutes after UTXO creation. + * Each retry rebuilds the transaction with a newer timestamp, giving a + * larger time delta and thus a larger allow_fee_payment. + * + * The shell keeps the RPC noise off the terminal (sdk-noise.ts). + */ +export async function registerNightUtxos( + bundle: FacadeBundle, + nightUtxos: readonly UtxoWithMeta[], + dustReceiverAddress: DustAddress, + onStatus?: (status: string) => void, +): Promise { + const startTime = Date.now(); + const deadline = startTime + DUST_REGISTRATION_TIMEOUT_MS; + let lastError: Error | undefined; + let retrying = false; + + // Dust is generated in chain time, the SDK's estimates use this computer's + // clock: refuse while the chain's clock lags (unknown when the indexer can't say). + const chainTime = bundle.indexerHttpUrl ? await fetchChainTime(bundle.indexerHttpUrl) : null; + if (chainTime) assertChainClockCurrent(chainTime, new Date()); + + // The registration pays its fee from the Dust these UTXOs generate: say up + // front how long that takes, and don't wait when it outlasts the deadline. + const { fee, dustGenerationEstimations } = await bundle.facade.estimateRegistration(nightUtxos); + const plan = planRegistration(fee, dustGenerationEstimations); + if (plan.waitMs === null || plan.waitMs > deadline - Date.now()) { + throw new DustFeeNotGeneratedError(plan, new Date()); + } + const waitNote = plan.waitMs > 0 ? `, fee covered in ${formatWait(plan.waitMs)}` : ''; + if (plan.waitMs > 0) { + onStatus?.(`Waiting for the NIGHT to generate the ${toDust(plan.fee)} DUST registration fee (${formatWait(plan.waitMs)})...`); + } + + // Once in retry mode, tick the elapsed timer every second so the spinner + // updates continuously — during the sleep AND during submission attempts. + const elapsedInterval = setInterval(() => { + if (retrying && onStatus) { + const elapsed = formatElapsed(Date.now() - startTime); + onStatus(`Waiting for dust generation capacity (${elapsed} elapsed${waitNote})...`); + } + }, 1_000); + + try { + while (Date.now() < deadline) { + try { + return await submitDustRegistration(bundle, nightUtxos, dustReceiverAddress, deadline - Date.now()); + } catch (err: any) { + lastError = err; + if (isDustRelatedError(err) && Date.now() + DUST_REGISTRATION_RETRY_DELAY_MS < deadline) { + retrying = true; + const elapsed = formatElapsed(Date.now() - startTime); + onStatus?.(`Waiting for dust generation capacity (${elapsed} elapsed${waitNote})...`); + await new Promise(resolve => setTimeout(resolve, DUST_REGISTRATION_RETRY_DELAY_MS)); + continue; + } + throw err; + } + } + + throw lastError ?? new Error('Dust registration timed out'); + } finally { + clearInterval(elapsedInterval); + } +} + +// ── Ensure dust (shared by transfer, airdrop, and dust register) ───── + +/** + * Ensure dust tokens are available for paying transaction fees. + * + * 1. If dust coins already exist → return immediately (skip registration) + * 2. If unregistered NIGHT UTXOs exist → register them (retries up to 10 min) + * 3. Wait for balance to become positive + * + * Registration is skipped when dust is already available to avoid burning + * dust on unnecessary registration transactions. New UTXOs (e.g. change + * outputs) can be registered later via `midnight dust register`. + * + * Used by: executeTransfer (transfer/airdrop commands), dustRegister command. + * The shell keeps the RPC noise off the terminal (sdk-noise.ts). + */ +export async function ensureDust( + bundle: FacadeBundle, + onStatus?: (status: string) => void, + /** Pre-fetched synced state from the caller. Avoids re-fetching through + * facade.state() / waitForSyncedState() which are unreliable due to + * shareReplay({ refCount: true }) clearing its buffer between subscriptions. */ + syncedState?: FacadeState, +): Promise { + // Prefer caller-provided state; fall back to waitForSyncedState (best-effort). + const state = syncedState ?? await bundle.facade.waitForSyncedState(); + + // If dust coins are already available, proceed immediately. + // Skip registration even if unregistered UTXOs exist — registration costs + // dust, and we don't want to burn fees when dust is already sufficient. + if (hasDustAvailable(state)) { + onStatus?.('Dust available'); + return { alreadyAvailable: true }; + } + + // No NIGHT at all, not even in flight: there is nothing to register and no Dust will be generated. + if (state.unshielded.availableCoins.length === 0 && (state.unshielded.pendingCoins?.length ?? 0) === 0) { + throw new Error( + 'This wallet has no NIGHT, so it generates no Dust to pay fees. Fund it first ' + + '(on undeployed: midnight airdrop ), then run: midnight dust register', + ); + } + + // No dust — check for unregistered NIGHT UTXOs and register them. + const nightUtxos = state.unshielded.availableCoins.filter( + (coin) => !coin.meta.registeredForDustGeneration, + ); + + let txHash: string | undefined; + + if (nightUtxos.length > 0) { + onStatus?.(`Registering ${nightUtxos.length} UTXO(s) for dust generation...`); + + txHash = await registerNightUtxos(bundle, nightUtxos, state.dust.address, onStatus); + } else { + onStatus?.('UTXOs already registered, waiting for dust generation...'); + } + + // Poll for balance using waitForSyncedState() to avoid shareReplay + // buffer clearing between subscriptions (same issue as the initial check). + // Each call is timeout-protected so a hung waitForSyncedState() can't block + // the deadline check indefinitely. + onStatus?.('Waiting for dust tokens...'); + const pollStart = Date.now(); + while (Date.now() - pollStart < DUST_TIMEOUT_MS) { + try { + const pollState = await Promise.race([ + bundle.facade.waitForSyncedState(), + new Promise((_, reject) => setTimeout(() => + reject(new Error('Poll sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), + ]); + if (pollState.dust.balance(new Date()) > 0n) { + onStatus?.('Dust available'); + return { alreadyAvailable: false, txHash }; + } + } catch { + // Timeout or sync error — continue polling until deadline + } + await new Promise(resolve => setTimeout(resolve, 5_000)); + } + throw new Error( + 'Timed out waiting for dust tokens. ' + + 'Try running: midnight dust register' + ); +} + +// ── Transfer build/submit ──────────────────────────────────────────── + +/** + * Build, sign, prove, and submit a transfer transaction. + * + * Retries on: + * - Stale UTXO (error 115): quick-sync and retry immediately (up to 3 attempts) + * - Dust-related errors: re-ensure dust is available, then retry (up to 10 min) + */ +async function buildAndSubmitTransfer( + bundle: FacadeBundle, + recipientAddress: UnshieldedAddress, + amount: bigint, + onProving?: () => void, + onSubmitting?: () => void, + onDust?: (status: string) => void, + onSubmittingTick?: (elapsedMs: number) => void, + signal?: AbortSignal, + log?: VerboseLog, +): Promise { + const startTime = Date.now(); + // Use DUST_TIMEOUT_MS (2 min) not DUST_REGISTRATION_TIMEOUT_MS (10 min) — + // ensureDust already ran before us, so this is only for edge cases where + // dust became insufficient between ensureDust and transferTransaction. + const dustDeadline = startTime + DUST_TIMEOUT_MS; + let lastError: Error | undefined; + let staleAttempts = 0; + + while (true) { + try { + if (lastError) { + await quickSync(bundle, 'lite'); + } + + const ttl = new Date(Date.now() + TX_TTL_MINUTES * 60 * 1000); + + log?.('transfer', 'Building transfer transaction...'); + const unprovenRecipe = await bundle.facade.transferTransaction( + [ + { + type: 'unshielded', + outputs: [ + { + amount, + receiverAddress: recipientAddress, + type: ledger.unshieldedToken().raw, + }, + ], + }, + ], + bundle.secretKeys, + { ttl, payFees: true }, + ); + + log?.('transfer', 'Signing recipe...'); + const signedRecipe = await bundle.facade.signRecipe(unprovenRecipe, bundle.keystore.signDataAsync); + + log?.('transfer', 'Generating ZK proof...'); + onProving?.(); + const finalizedTx = await Promise.race([ + bundle.facade.finalizeRecipe(signedRecipe), + new Promise((_, reject) => { + setTimeout(() => reject(new Error('ZK proof generation timed out')), PROOF_TIMEOUT_MS); + }), + ]); + + log?.('transfer', 'Submitting transaction to node...'); + onSubmitting?.(); + // SDK v4's facade.submitTransaction blocks until block finalization + // (typically 12 to 30s on hosted networks). Tick a 1-second timer so + // callers can render an elapsed counter and not look stuck. + const submitStarted = Date.now(); + const tickInterval = onSubmittingTick + ? setInterval(() => onSubmittingTick(Date.now() - submitStarted), 1000) + : undefined; + let txHash: string; + try { + txHash = await bundle.facade.submitTransaction(finalizedTx); + } finally { + if (tickInterval) clearInterval(tickInterval); + } + log?.('transfer', `Transaction submitted: ${txHash}`); + return txHash; + } catch (err: any) { + lastError = err; + + // Stale UTXO: quick-sync and retry immediately (limited attempts) + const isStaleUtxo = err?.code === STALE_UTXO_ERROR_CODE || + err?.message?.includes('115') || + err?.message?.toLowerCase().includes('stale'); + + if (isStaleUtxo && ++staleAttempts < MAX_RETRY_ATTEMPTS) { + continue; + } + + // SDK "insufficient funds" (of NIGHT) means the internal coin index is + // empty even though we pre-flight-checked the balance. Bubble up — the + // outer retry will restart the facade. A Dust shortage is not that: it + // goes to the Dust path below, which waits for the fee. + if (isColdStartRace(err)) { + throw err; + } + + // Dust-related: check sufficiency, re-ensure dust, then retry + if (isDustRelatedError(err) && Date.now() < dustDeadline) { + const elapsed = formatElapsed(Date.now() - startTime); + onDust?.(`Dust insufficient, re-ensuring (${elapsed} elapsed)...`); + try { + const freshState = await quickSync(bundle, 'lite'); + // Below the fee threshold: wait when the Dust is moments away, else fail fast. + await awaitDustForFee(freshState.dust, MIN_DUST_FOR_TRANSFER, onDust, signal); + // At or above it, this transaction's fee is higher than the threshold + // (more inputs, other fee prices): give the Dust time to grow rather + // than rebuilding back to back. + if (freshState.dust.balance(new Date()) >= MIN_DUST_FOR_TRANSFER) { + onDust?.(`Dust is short of this transaction's fee; waiting ${DUST_GROW_WAIT_MS / 1000} s for more...`); + await sleep(DUST_GROW_WAIT_MS, signal); + } + await ensureDust(bundle, onDust, freshState); + } catch (retryErr: any) { + // Re-throw "Insufficient dust" immediately — not retryable + if (String(retryErr?.message).startsWith('Insufficient dust')) throw retryErr; + // quickSync or ensureDust may fail (shareReplay stale-read) — wait and retry anyway + await new Promise(resolve => setTimeout(resolve, 5_000)); + } + continue; + } + + throw err; + } + } +} + +// ── Main transfer flow ─────────────────────────────────────────────── + +/** + * Execute a full transfer flow. The lifecycle and recovery loops live in + * `repo.withFacade(...)`: pre-prime dust, sync-retry on stale-cache / + * timeout, cold-start race retry on SDK InsufficientFunds, save+invalidate + * on success, stopFacade in finally. This function only owns the + * transfer-specific work: pre-flight checks (balance, dust threshold), + * `ensureDust` orchestration, and the build/sign/prove/submit retry loop + * (handled inside `buildAndSubmitTransfer` for stale-UTXO + dust errors). + */ +export async function executeTransfer(params: TransferParams): Promise { + const { + seedBuffer, + networkConfig, + recipientAddress, + amountNight, + signal, + onSync, + onSyncDetail, + onDust, + onProving, + onSubmitting, + onSubmittingTick, + onSyncWarning, + sdkWarnings, + log, + } = params; + + const amount = nightToMicro(amountNight); + const decodedAddress = validateRecipientAddress(recipientAddress, networkConfig); + + // Suppress SDK transient errors + polkadot-js RPC noise for the duration + // of the transfer (covers dust registration AND tx submission). + const stopListening = sdkWarnings.listen(onSyncWarning); + + try { + return await defaultRepository().withFacade( + seedBuffer, + networkConfig, + async ({ bundle, state }) => { + throwIfCancelled(signal); + + log?.('transfer', 'Sync complete, checking balance...'); + const unshieldedBalance = state.unshielded.balances[ledger.unshieldedToken().raw] ?? 0n; + const availableCoinCount = state.unshielded.availableCoins?.length ?? 0; + log?.('transfer', `Balance: ${Number(unshieldedBalance) / TOKEN_MULTIPLIER} NIGHT, coins: ${availableCoinCount}`); + if (unshieldedBalance < amount) { + const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER; + throw new Error( + `Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + + `${amountNight} NIGHT requested` + ); + } + + // Pre-flight: below the fee threshold, wait when the Dust is moments + // away (just after registering), else fail fast with how long it takes. + await awaitDustForFee(state.dust, MIN_DUST_FOR_TRANSFER, onDust, signal); + + throwIfCancelled(signal); + + log?.('transfer', 'Ensuring dust availability...'); + const dustResult = await ensureDust(bundle, onDust, state); + // When ensureDust had to wait, it returned once any Dust showed (right + // after registering that can be less than the fee): wait for the fee on + // current state. Time-boxed like every other sync wait; skipped on timeout. + if (!dustResult.alreadyAvailable) { + let timer: ReturnType | undefined; + const current = await Promise.race([ + bundle.facade.waitForSyncedState(), + new Promise((resolve) => { timer = setTimeout(() => resolve(null), SYNC_ATTEMPT_TIMEOUT_MS); }), + ]).finally(() => clearTimeout(timer)); + if (current) await awaitDustForFee(current.dust, MIN_DUST_FOR_TRANSFER, onDust, signal); + } + log?.('transfer', 'Dust available'); + + throwIfCancelled(signal); + + log?.('transfer', 'Building and submitting transaction...'); + const txHash = await buildAndSubmitTransfer( + bundle, + decodedAddress, + amount, + onProving, + onSubmitting, + onDust, + onSubmittingTick, + signal, + log, + ); + return { txHash, amountMicroNight: amount }; + }, + { + syncMode: 'lite', + // Writes build ZK proofs — need strict sync or the commitment tree + // is stale and chain rejects with MalformedError::InvalidDustSpendProof. + requireStrictSync: true, + signal, + onStatus: onDust, + onSyncProgress: onSync, + onSyncDetail, + onSyncWarning, + log, + }, + ); + } finally { + stopListening(); + } +} diff --git a/packages/engine-beta/src/tx-inspect.ts b/packages/engine-beta/src/tx-inspect.ts new file mode 100644 index 00000000..9f0c302d --- /dev/null +++ b/packages/engine-beta/src/tx-inspect.ts @@ -0,0 +1,105 @@ +// Transaction inspection — extracts human-readable details from serialized transactions +// Used by the DApp Connector approval prompt to show Lace-style transaction summaries + +import { Transaction } from '@midnightntwrk/ledger-v9'; +import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; + +/** + * Try to extract structured details from a transaction hex string. + * Returns an array of label/value pairs for the approval prompt. + * Falls back gracefully — never throws. + */ +export function inspectTxHex(txHex: string, stage: 'unsealed' | 'sealed'): TransactionDetail[] { + const details: TransactionDetail[] = []; + details.push({ label: 'Tx size', value: formatBytes(txHex.length / 2) }); + + const summary = tryDeserializeAndSummarize(txHex, stage); + if (summary) { + const parsed = parseTxSummary(summary); + if (parsed.action) details.push({ label: 'Type', value: parsed.action }); + if (parsed.circuits.length > 0) details.push({ label: 'Circuits', value: parsed.circuits.join(', ') }); + if (parsed.ttl) details.push({ label: 'TTL', value: parsed.ttl }); + } + + return details; +} + +/** Try deserializing the tx and return toString(true), or null on failure. */ +function tryDeserializeAndSummarize(txHex: string, stage: 'unsealed' | 'sealed'): string | null { + const bytes = hexToBytes(txHex); + + // Try the expected format first, then fall back to alternatives + const attempts: Array<[string, string, string]> = stage === 'sealed' + ? [['signature', 'proof', 'binding'], ['signature', 'proof', 'pre-binding']] + : [['signature', 'proof', 'pre-binding'], ['signature', 'pre-proof', 'pre-binding']]; + + for (const [s, p, b] of attempts) { + try { + const tx = Transaction.deserialize(s as any, p as any, b as any, bytes); + return tx.toString(true); + } catch { /* try next */ } + } + return null; +} + +interface TxSummary { + networkId: string | null; + action: string | null; + circuits: string[]; + ttl: string | null; +} + +/** + * Parse the Rust debug output from Transaction.toString(true). + * Extracts network_id, action type (Deploy/Call), circuit names, and TTL. + */ +function parseTxSummary(summary: string): TxSummary { + const result: TxSummary = { networkId: null, action: null, circuits: [], ttl: null }; + + // network_id: "preview" + const networkMatch = summary.match(/network_id:\s*"([^"]+)"/); + if (networkMatch) result.networkId = networkMatch[1]; + + // Deploy ContractState or Call
+ if (summary.includes('Deploy ContractState')) { + result.action = 'Deploy contract'; + } else if (summary.match(/Call\s/)) { + result.action = 'Call contract'; + } + + // Verifier key names: submit_score: , prove_elite: + const verifierPattern = /(\w+):\s*/g; + let match; + while ((match = verifierPattern.exec(summary)) !== null) { + result.circuits.push(match[1]); + } + + // If no verifier keys found (call tx), look for circuit name in the call + if (result.circuits.length === 0) { + // Call patterns vary — try to extract from actions + const callMatch = summary.match(/Call\s+\S+\s+(\w+)/); + if (callMatch) result.circuits.push(callMatch[1]); + } + + // TTL: Timestamp(1773794982) + const ttlMatch = summary.match(/ttl:\s*Timestamp\((\d+)\)/); + if (ttlMatch) { + const ts = parseInt(ttlMatch[1], 10); + const date = new Date(ts * 1000); + result.ttl = date.toISOString().replace('T', ' ').slice(0, 19); + } + + return result; +} + +function hexToBytes(hex: string): Uint8Array { + return new Uint8Array(Buffer.from(hex, 'hex')); +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + const kb = bytes / 1024; + if (kb < 1024) return `${kb.toFixed(1)} KB`; + const mb = kb / 1024; + return `${mb.toFixed(1)} MB`; +} diff --git a/packages/engine-beta/src/wallet-data-repository.ts b/packages/engine-beta/src/wallet-data-repository.ts new file mode 100644 index 00000000..2b2fcd34 --- /dev/null +++ b/packages/engine-beta/src/wallet-data-repository.ts @@ -0,0 +1,743 @@ +// Wallet data repository — single owner of cache + tip-aware invalidation. +// +// What this hides from callers: +// • In-memory layer (per-process; matters for the long-lived MCP server) +// • On-disk layer (shared across `mn` shell invocations) +// • Tip-aware invalidation (cache valid iff chain tip unchanged) +// • Force-fresh override +// • Chain-id (genesis hash) validation on chain reset +// • Auto-invalidation of dependent reads after a write +// +// Four constructor seams (`now`, `fetchTip`, `fetchUnshielded`, `fetchDust`) +// make the cache + tip + invalidation logic unit-testable without spinning up +// the SDK, Docker, or the indexer. Production defaults wire to the existing +// `chain_getBlockHash` / `checkBalance` / `readDustBalanceDirect` paths. +// +// `withFacade` deliberately leaks the SDK's `FacadeBundle` so callers can +// build/sign/submit transactions. Tests of the write path remain integration +// tests against localnet — accepted scope per architecture-deepening.md. + +import { Buffer } from 'node:buffer'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; + +import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { isValidNetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { type FacadeState } from '@midnightntwrk/wallet-sdk-facade'; +import { + buildFacade, + startAndSyncFacade, + stopFacade, + StaleCacheError, + type FacadeBundle, + type SyncMode, + overlayDustDirectSnapshot, +} from './facade.ts'; +import { isColdStartRace } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from './dust-direct-cache.ts'; +import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { + loadWalletCache, + saveWalletCache, + clearWalletCache, + validateWalletCacheChainId, + type WalletCacheData, +} from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; +import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { checkBalance, type BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; +import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; +import { deriveDustSeed } from './derivation.ts'; +import { deriveUnshieldedAddress } from './derive-address.ts'; +import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain/lib/event-tip'; +import type { DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; + +// ── Public types ────────────────────────────────────────── + +export interface DustView extends DustBalance { + state: ledger.DustLocalState; +} + + +/** What the caller borrows during withFacade. SDK type leak is intentional. */ +export interface FacadeLease { + bundle: FacadeBundle; + state: FacadeState; +} + +export interface InvalidationScope { + network: NetworkConfig; + /** If set, scope invalidations to this seed's derived caches. */ + seed?: Buffer; + /** If set, scope unshielded invalidation to this address. */ + address?: string; + /** Which kinds to invalidate. Default: all. */ + kinds?: ReadonlyArray<'dust' | 'unshielded' | 'facade'>; +} + + +export interface FacadeOptions extends ReadOptions { + syncMode?: SyncMode; + requireStrictSync?: boolean; + /** If true, skip the post-resolve invalidation (read-only borrowers). */ + readOnly?: boolean; + /** + * If true, skip the automatic post-resolve `saveWalletCache`. For callers + * that have nuanced save logic — e.g. `mn serve` skips the save if there + * are pending in-flight transactions, because the SDK drops `pendingDustTokens` + * on serialization and persisting that state corrupts the dust balance. + */ + skipAutoSave?: boolean; + /** Per-attempt sync deadline. Default: SYNC_ATTEMPT_TIMEOUT_MS (local) or SYNC_ATTEMPT_REMOTE_TIMEOUT_MS (remote). */ + syncTimeoutMs?: number; + /** Per-emission sync progress hook (forwards startAndSyncFacade onProgress). */ + onSyncProgress?: (applied: number, highest: number) => void; + /** Per-emission detail hook (which wallets are still syncing). */ + onSyncDetail?: (detail: string) => void; + /** Suppressed-but-relayed SDK transient warnings (Wallet.Sync, etc). */ + onSyncWarning?: (tag: string, message: string) => void; + /** Suppress the dust pre-prime even in write mode (used by tests / debug). */ + noPrime?: boolean; +} + +export type TipFingerprint = string; + +export interface RepoDeps { + /** Wall-clock source. Default: Date.now. */ + now?: () => number; + /** Tip fetcher. Default: substrate `chain_getBlockHash`. */ + fetchTip?: (network: NetworkConfig, signal?: AbortSignal) => Promise; + /** Unshielded balance fetcher. Default: existing `checkBalance` over indexer WS. `signal` cancels it. */ + fetchUnshielded?: ( + address: string, + network: NetworkConfig, + onProgress?: (current: number, highest: number) => void, + signal?: AbortSignal, + ) => Promise; + /** Dust state fetcher. Default: existing `readDustBalanceDirect` over indexer WS. */ + fetchDust?: ( + seed: Buffer, + network: NetworkConfig, + opts: { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + /** Repo passes a callback to persist incremental progress during long syncs. */ + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + /** The cache folder the repository keeps; the native sidecar keeps its checkpoint there. */ + cacheDir?: string; + /** The call's verbose lines. */ + log?: VerboseLog; + }, + ) => Promise; + /** Chain genesis-hash fetcher (cache chain-reset guard). Default: `getChainGenesisHash`. */ + fetchChainId?: (nodeWsUrl: string) => Promise; + /** A ledger event stream's latest id, for the chain-reset check. Default: indexer subscription. */ + fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; + /** Chain protocol-version fetcher (ledger-9-only guard). Default: indexer `block { protocolVersion }`. */ + fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; + /** Override cache directory (tests use a tmp dir). */ + cacheDir?: string; +} + +// ── Implementation ──────────────────────────────────────── + +interface MemoEntry { + value: T; + fetchedAt: number; + tipAtFetch: TipFingerprint; +} + +/** Re-fetching the chain tip on every cache check is overkill; memo it briefly. */ +const TIP_PROBE_TTL_MS = 5_000; + +/** + * Wall-time ceiling of the partial-resume loop in `dust()`: enough to fully + * cold-sync any preprod wallet from event 0, and an indexer that streams + * events forever still terminates. The bound is time, not a count of + * windows, because a window can be short: Blockfrost drops a reader slower + * than its stream after about 80 s (some 80k events for the WASM reader), so + * a cold preprod sync is twenty windows or more, each resumed from the last. + */ +const DUST_SYNC_BUDGET_MS = 60 * 60_000; + +/** Windows in a row that apply no event before the loop gives up: the sync is stuck, not slow. */ +const DUST_STALLED_WINDOWS = 3; + +/** Default per-sync-attempt deadline (local). */ +const SYNC_ATTEMPT_LOCAL_MS = 30_000; +/** Default per-sync-attempt deadline (remote — preprod/preview Day 0). */ +const SYNC_ATTEMPT_REMOTE_MS = 120_000; +/** Sync-retry budget: number of build+sync attempts before giving up on transient sync errors. */ +const SYNC_MAX_ATTEMPTS = 3; +/** Cold-start race retry budget: how many times to stop+rebuild+re-sync when the SDK reports InsufficientFunds despite a synced state with coins. */ +const COLD_START_MAX_ATTEMPTS = 5; +/** Backoff between cold-start retries — gives the indexer time to settle. */ +const COLD_START_DELAY_MS = 5_000; + +export class WalletDataRepository { + private readonly now: () => number; + private readonly fetchTip: NonNullable; + private readonly fetchUnshielded: NonNullable; + private readonly fetchDust: NonNullable; + private readonly fetchChainId: NonNullable; + private readonly fetchEventTip: NonNullable; + private readonly fetchProtocolVersion: NonNullable; + private readonly cacheDir: string | undefined; + + private readonly dustMemo = new Map>(); + private readonly unshieldedMemo = new Map>(); + private readonly tipMemo = new Map(); + + constructor(deps: RepoDeps = {}) { + this.now = deps.now ?? Date.now; + this.fetchTip = deps.fetchTip ?? defaultTipFetcher; + this.fetchUnshielded = deps.fetchUnshielded ?? defaultUnshieldedFetcher; + this.fetchDust = deps.fetchDust ?? nativeOrWasmDustFetcher; + this.fetchChainId = deps.fetchChainId ?? getChainGenesisHash; + this.fetchEventTip = deps.fetchEventTip ?? fetchEventTip; + this.fetchProtocolVersion = deps.fetchProtocolVersion ?? fetchProtocolVersion; + this.cacheDir = deps.cacheDir; + } + + /** + * Indexer guard: cached sync state resumes from the indexer's own ids, so + * state read from another indexer is dropped before it is loaded, and the + * caller is told why this sync is a full one. + */ + private keepCachesOfThisIndexer(networkName: string, network: NetworkConfig, onStatus?: (s: string) => void): void { + const change = bindCachesToIndexer(networkName, network.indexerWS, this.cacheDir); + if (change) onStatus?.(describeIndexerChange(networkName, change)); + } + + /** + * What a wallet with no saved state restores from: a new wallet's state, + * with the Dust checkpoint the direct reader already holds in place of its + * empty Dust state. Without it the SDK replays the chain's whole Dust history + * itself, slowly enough that the first sync attempt of a first `serve` or + * transfer on a hosted network always timed out. Null when there is no + * checkpoint to start from: the wallet is then built from its keys. + */ + /** + * The saved state a wallet restores from: its own, else a new wallet's on + * the Dust checkpoint (see freshWalletOnDustCheckpoint). Null builds it from + * its keys. Every facade mn starts for writing starts from this. Building + * that new wallet's diagnostics go to `log`. + */ + async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise { + return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, this.cacheDir) + ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, log); + } + + private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise { + const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), this.cacheDir); + if (!checkpoint || checkpoint.lastAppliedEventId < 0) return null; + const fresh = await buildFacade(seed, network, null, log); + try { + const { shielded, unshielded, dust } = fresh.facade as unknown as Record<'shielded' | 'unshielded' | 'dust', { serializeState(): Promise }>; + const [shieldedState, unshieldedState, dustState] = await Promise.all([shielded.serializeState(), unshielded.serializeState(), dust.serializeState()]); + return { shielded: shieldedState, unshielded: unshieldedState, dust: overlayDustDirectSnapshot(dustState, checkpoint) }; + } finally { + await stopFacade(fresh).catch(() => {}); + } + } + + // ── Reads ───────────────────────────────────────── + + async dust(seed: Buffer, network: NetworkConfig, opts: ReadOptions = {}): Promise { + const networkName = networkNameOf(network); + await assertLedgerSupported(networkName, network, this.fetchProtocolVersion, opts.signal); + const pubkeyHex = dustPublicKeyHexFromSeed(seed); + const memoKey = `${networkName}:${pubkeyHex}`; + + if (!opts.forceFresh) { + const hit = await this.tryMemo(memoKey, network, this.dustMemo, opts.signal); + // `partial` rides through from the memoized view — a short state stays short. + if (hit) return { ...hit, fromCache: true, eventsApplied: 0 }; + } + + // Chain-reset guard: fetch the chain's genesis hash once, wipe any + // stale-chain dust files, and persist the same hash on every save so the + // guard has something to compare on the next run. + const currentChainId = await this.fetchChainId(network.node).catch(() => null); + validateDustCacheChainId(networkName, currentChainId, this.cacheDir); + this.keepCachesOfThisIndexer(networkName, network, opts.onStatus); + const chainId = currentChainId ?? undefined; + + let cached = opts.forceFresh ? null : loadDustCache(networkName, pubkeyHex, this.cacheDir); + // A cursor past the chain's latest event: the chain was reset under the + // cache (the genesis check above can't tell when the hash is reused). + if (cached && isCursorBeyondTip(cached.lastAppliedEventId, await this.fetchEventTip(network.indexerWS, 'dust'))) { + clearDustDirectCache(networkName, pubkeyHex, this.cacheDir); + cached = null; + } + const startedFromCache = cached !== null; + let totalEventsApplied = 0; + let lastAppliedEventId = cached?.lastAppliedEventId ?? -1; + let result: DustDirectResult | null = null; + + // Auto-resume on `partial: true`. The underlying fetcher resolves with + // `partial` when its window ends before the tip (its soft timeout, or the + // indexer dropping the connection) instead of throwing. Each call's + // `onCheckpoint` saves intermediate state to disk, so the next window + // resumes from where the last one stopped and never re-processes events. + // Bounded by time and by progress, so a broken indexer doesn't loop forever. + const startedAt = this.now(); + let stalledWindows = 0; + for (let attempt = 0; ; attempt++) { + throwIfCancelled(opts.signal); + const startFromId = cached ? cached.lastAppliedEventId + 1 : 0; + opts.onStatus?.( + attempt > 0 + ? `Resuming dust from event ${startFromId} (continuation ${attempt + 1})…` + : (cached ? `Resuming dust from event ${startFromId}…` : 'Reading dust events…'), + ); + + result = await this.fetchDust(seed, network, { + cacheDir: this.cacheDir, + startFromId, + initialState: cached?.state, + initialRetention: cached?.retention, + signal: opts.signal, + log: opts.log, + onProgress: (applied, max) => { + const target = Math.max(1, max + 1 - startFromId); + opts.onStatus?.(`Reading dust events… ${applied}/${target}`); + // Also forward the raw counts, as ReadOptions.onProgress documents. + // Callers that render their own progress (e.g. `dust export`'s spinner) + // have no other signal — without this they show a frozen spinner for + // the whole cold sync. + opts.onProgress?.(applied, max); + }, + // Persist after each chunk so a Ctrl+C / process kill / SIGTERM + // doesn't lose 100k events of work. + onCheckpoint: (state, lastAppliedEventId, retention) => { + try { saveDustCache(networkName, pubkeyHex, state, lastAppliedEventId, this.cacheDir, chainId, retention); } catch { /* best-effort */ } + }, + }); + + // Final save (covers the last sub-chunk that didn't trip onCheckpoint). + // A run that applied no events keeps the prior checkpoint's id rather than + // regressing to -1 — the state is still valid as far as that id. + lastAppliedEventId = result.lastAppliedEventId >= 0 + ? result.lastAppliedEventId + : (cached?.lastAppliedEventId ?? -1); + if (result.lastAppliedEventId >= 0 || !cached) { + try { saveDustCache(networkName, pubkeyHex, result.state, lastAppliedEventId, this.cacheDir, chainId, result.retention); } catch { /* best-effort */ } + } + + totalEventsApplied += result.eventCount; + if (!result.partial) break; + stalledWindows = result.eventCount > 0 ? 0 : stalledWindows + 1; + if (stalledWindows >= DUST_STALLED_WINDOWS || this.now() - startedAt >= DUST_SYNC_BUDGET_MS) break; + + // Reload for the next iteration so cached.state is the latest checkpoint. + cached = loadDustCache(networkName, pubkeyHex, this.cacheDir); + } + + if (!result) throw new Error('Dust sync exhausted retries without producing a result'); + const view: DustView = { + state: result.state, + balance: result.balance, + availableCoins: result.availableCoins, + ownedUtxoCount: result.ownedUtxoCount, + syncTime: result.syncTime, + fromCache: startedFromCache, + eventsApplied: totalEventsApplied, + lastAppliedEventId, + partial: result.partial, + fetchedAt: this.now(), + }; + await this.memoize(this.dustMemo, memoKey, view, network, opts.signal, opts.log); + return view; + } + + async unshielded( + identity: string | Buffer, + network: NetworkConfig, + opts: ReadOptions = {}, + ): Promise { + const networkName = networkNameOf(network); + const address = typeof identity === 'string' + ? identity + : deriveUnshieldedAddress(identity, networkName); + const memoKey = `${networkName}:${address}`; + + if (!opts.forceFresh) { + const hit = await this.tryMemo(memoKey, network, this.unshieldedMemo, opts.signal); + if (hit) return { ...hit, fromCache: true }; + } + + const summary = await this.fetchUnshielded(address, network, opts.onProgress, opts.signal); + const view: UnshieldedView = { ...summary, fromCache: false, fetchedAt: this.now() }; + await this.memoize(this.unshieldedMemo, memoKey, view, network, opts.signal, opts.log); + return view; + } + + // ── Borrow pattern (writes) ─────────────────────── + + /** + * Borrow a synced WalletFacade for a write or facade-bound read. Owns the + * full lifecycle plus the recovery loops every write path used to + * re-implement: + * + * 1. Optional dust pre-prime (skipped when `noPrime: true` or when in + * read-only mode). Warms the dust-direct cache so the facade's dust + * wallet restores from a near-tip checkpoint instead of cold-syncing + * via the SDK's `isConnected` path. + * 2. Sync-retry on `StaleCacheError` (chain reset / re-index): wipe both + * caches, re-prime, rebuild from a clean cache, re-sync. + * 3. Sync-retry on timeout: persist whatever progress the facade made, + * reload from disk so the next attempt resumes from the checkpoint. + * 4. Cold-start race retry around `fn`: when the SDK throws + * `Wallet.InsufficientFunds` despite the synced state showing coins + * (the SDK's internal coin index hadn't caught up to the state + * snapshot), stop+rebuild+re-sync and call fn again. Bounded. + * 5. Save wallet cache on success. + * 6. Auto-invalidate dust+unshielded+facade memo entries for this seed + * (writes mutate state). Read-only borrowers pass `readOnly: true`. + * 7. stopFacade in `finally`. + * + * The SDK's `FacadeBundle` is intentionally exposed via `lease.bundle` so + * callers can build/sign/submit transactions. Tests of write paths through + * this method are integration tests against a real network. + */ + async withFacade( + seed: Buffer, + network: NetworkConfig, + fn: (lease: FacadeLease) => Promise, + opts: FacadeOptions = {}, + ): Promise { + const syncMode = opts.syncMode ?? 'full'; + const requireStrictSync = opts.requireStrictSync ?? true; + const writeMode = requireStrictSync && !opts.readOnly; + const networkName = networkNameOf(network); + const address = deriveUnshieldedAddress(seed, networkName); + const isRemote = network.networkId !== 'Undeployed'; + const syncTimeoutMs = opts.syncTimeoutMs + ?? (isRemote ? SYNC_ATTEMPT_REMOTE_MS : SYNC_ATTEMPT_LOCAL_MS); + + // On a ledger-8 chain the SDK's sync retries forever; refuse up front. + await assertLedgerSupported(networkName, network, this.fetchProtocolVersion, opts.signal); + + const currentChainId = await this.fetchChainId(network.node).catch(() => null); + validateWalletCacheChainId(networkName, currentChainId, this.cacheDir); + this.keepCachesOfThisIndexer(networkName, network, opts.onStatus); + const chainId = currentChainId ?? undefined; + + // ── Pre-prime the dust-direct cache for write-mode borrowers ── + // Equivalent to the legacy `primeDustCacheWithFeedback` step: warms the + // dust state to chain tip on disk so buildFacade's dust bridge starts + // near-tip. Read-only borrowers skip it. + if (writeMode && !opts.noPrime && !opts.forceFresh) { + try { + await this.dust(seed, network, { signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + } catch (err) { + // Pre-prime is best-effort — the actual sync below will re-attempt + // anyway. Surface the error only via onSyncWarning if anyone cares. + opts.onSyncWarning?.('PrePrime', (err as Error).message); + } + } + + let bundle: FacadeBundle | undefined; + let syncedState: FacadeState | undefined; + let cleanupDone = false; + const cleanup = async () => { + if (cleanupDone || !bundle) return; + cleanupDone = true; + try { await stopFacade(bundle); } catch { /* best-effort */ } + }; + + try { + // ── Sync-retry loop (build + start) ──────────────────── + for (let attempt = 1; attempt <= SYNC_MAX_ATTEMPTS; attempt++) { + throwIfCancelled(opts.signal); + const cacheBeforeBuild = opts.forceFresh + ? null + : await this.walletStateToRestore(seed, network, networkName, opts.log); + bundle = await buildFacade(seed, network, cacheBeforeBuild, opts.log); + try { + syncedState = await startAndSyncFacade(bundle, { + onProgress: opts.onSyncProgress, + onSyncDetail: opts.onSyncDetail, + timeoutMs: syncTimeoutMs, + syncMode, + requireStrictSync, + log: opts.log, + }); + break; + } catch (err: any) { + throwIfCancelled(opts.signal); + + if (err instanceof StaleCacheError && attempt < SYNC_MAX_ATTEMPTS && writeMode) { + opts.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); + await stopFacade(bundle).catch(() => {}); + bundle = undefined; + clearWalletCache(address, networkName, this.cacheDir); + clearDustDirectCache(networkName, dustPublicKeyHexFromSeed(seed), this.cacheDir); + // Re-prime the dust cache so the next attempt restores from a + // current checkpoint instead of a full SDK resync. + try { + await this.dust(seed, network, { signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + } catch { /* best-effort */ } + continue; + } + + if (attempt < SYNC_MAX_ATTEMPTS && String(err?.message ?? '').includes('timed out')) { + // Save partial sync progress to cache before retrying so the next + // attempt resumes from the latest event id. + try { await saveWalletCache(address, networkName, bundle.facade, this.cacheDir, chainId); } catch { /* best-effort */ } + opts.onStatus?.(`Sync timed out, retrying (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); + await stopFacade(bundle).catch(() => {}); + bundle = undefined; + continue; + } + + throw err; + } + } + + if (!bundle || !syncedState) throw new Error('Sync failed: no facade state after retries'); + + // ── Cold-start race retry around fn ─────────────────── + // The SDK's state observable can emit a snapshot with coins populated + // BEFORE the internal #balanceSegment coin index is built. fn's call + // to transferTransaction then throws Wallet.InsufficientFunds. Recovery + // is a full facade restart, not in-place quick-sync. Bounded. + let result: T; + let attempt = 0; + while (true) { + attempt++; + throwIfCancelled(opts.signal); + try { + result = await fn({ bundle, state: syncedState }); + break; + } catch (err) { + // A Dust shortage is real, not the cold-start race: rebuilding the + // facade can't fix it (and repeated rebuilds crashed the ledger WASM). + const canRetry = writeMode && attempt < COLD_START_MAX_ATTEMPTS && isColdStartRace(err); + if (!canRetry) throw err; + opts.onStatus?.(`Refreshing wallet state (attempt ${attempt + 1}/${COLD_START_MAX_ATTEMPTS})...`); + await stopFacade(bundle).catch(() => {}); + bundle = undefined; + await new Promise((r) => setTimeout(r, COLD_START_DELAY_MS)); + throwIfCancelled(opts.signal); + const retryCache = loadWalletCache(address, networkName, this.cacheDir); + bundle = await buildFacade(seed, network, retryCache, opts.log); + syncedState = await startAndSyncFacade(bundle, { + onProgress: opts.onSyncProgress, + onSyncDetail: opts.onSyncDetail, + timeoutMs: syncTimeoutMs, + syncMode, + requireStrictSync, + log: opts.log, + }); + } + } + + if (!opts.skipAutoSave) { + try { await saveWalletCache(address, networkName, bundle.facade, this.cacheDir, chainId); } catch { /* best-effort */ } + } + if (!opts.readOnly) this.invalidate({ network, seed }); + return result; + } finally { + await cleanup(); + } + } + + // ── Invalidation ────────────────────────────────── + + invalidate(scope: InvalidationScope): void { + const networkName = networkNameOf(scope.network); + const kinds = scope.kinds ?? ['dust', 'unshielded', 'facade']; + + if (kinds.includes('dust')) { + if (scope.seed) { + const pubkeyHex = dustPublicKeyHexFromSeed(scope.seed); + this.dustMemo.delete(`${networkName}:${pubkeyHex}`); + } else { + this.deleteByPrefix(this.dustMemo, `${networkName}:`); + } + } + + if (kinds.includes('unshielded')) { + const addr = scope.address + ?? (scope.seed ? deriveUnshieldedAddress(scope.seed, networkName) : null); + if (addr) this.unshieldedMemo.delete(`${networkName}:${addr}`); + else this.deleteByPrefix(this.unshieldedMemo, `${networkName}:`); + } + + if (kinds.includes('facade') && scope.seed) { + const address = deriveUnshieldedAddress(scope.seed, networkName); + try { clearWalletCache(address, networkName, this.cacheDir); } catch { /* best-effort */ } + } + } + + /** Drop the chain-tip memo so the next read re-checks. Test/diagnostic helper. */ + resetTipMemo(): void { + this.tipMemo.clear(); + } + + // ── Internals ───────────────────────────────────── + + private async tryMemo( + key: string, + network: NetworkConfig, + memo: Map>, + signal?: AbortSignal, + ): Promise { + const entry = memo.get(key); + if (!entry) return null; + let tip: TipFingerprint; + try { + tip = await this.getTip(network, signal); + } catch { + // A cancelled call stops here rather than being served the cache. + throwIfCancelled(signal); + // Network down on the tip-check → serve cache. Caller can pass forceFresh + // if they need certainty over availability. + return entry.value; + } + if (tip === entry.tipAtFetch) return entry.value; + memo.delete(key); + return null; + } + + /** + * Record a freshly-fetched view in a memo, stamped with the current chain tip. + * + * The tip fetch is best-effort: `tryMemo` already treats an unreachable node as + * "serve the cache" rather than an error, and the same has to hold here. A cold + * dust sync can be 5-22 minutes of work, and letting a 3s RPC timeout throw it + * away — after it completed and was written to disk — would be absurd. Skipping + * the memo just means the next read re-checks. + */ + private async memoize( + memo: Map>, + key: string, + value: T, + network: NetworkConfig, + signal?: AbortSignal, + log?: VerboseLog, + ): Promise { + try { + const tip = await this.getTip(network, signal); + memo.set(key, { value, fetchedAt: this.now(), tipAtFetch: tip }); + } catch { + // Also swallows an abort landing on this final tip probe — fine: the sync + // already completed and was persisted, so there is no work left to cancel. + log?.('repo', `tip unavailable; skipping memo for ${key}`); + } + } + + private async getTip(network: NetworkConfig, signal?: AbortSignal): Promise { + const cached = this.tipMemo.get(network.networkId); + if (cached && this.now() - cached.fetchedAt < TIP_PROBE_TTL_MS) return cached.tip; + const tip = await this.fetchTip(network, signal); + this.tipMemo.set(network.networkId, { tip, fetchedAt: this.now() }); + return tip; + } + + private deleteByPrefix(memo: Map, prefix: string): void { + for (const k of memo.keys()) { + if (k.startsWith(prefix)) memo.delete(k); + } + } +} + +// ── Default seam implementations ────────────────────────── + +function defaultTipFetcher(network: NetworkConfig, signal?: AbortSignal): Promise { + return callNodeRpc({ url: network.node, timeoutMs: 3_000, signal }, 'chain_getBlockHash', []); +} + +function defaultUnshieldedFetcher( + address: string, + network: NetworkConfig, + onProgress?: (current: number, highest: number) => void, + signal?: AbortSignal, +): Promise { + return checkBalance(address, network.indexerWS, onProgress, signal); +} + +function defaultDustFetcher( + seed: Buffer, + network: NetworkConfig, + opts: { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + cacheDir?: string; + log?: VerboseLog; + }, +): Promise { + const dustSeed = deriveDustSeed(seed); + const dustSecretKey = ledger.DustSecretKey.fromSeed(dustSeed); + return readDustBalanceDirect(dustSecretKey, network.indexerWS, opts); +} + +// Said once per process: the first sync from the start of a chain's Dust history. +let saidWasmDust = false; + +/** + * Prefer the native sidecar (~5x faster cold dust sync) when it's available; + * fall back to the WASM reader on a missing binary or any failure. The sidecar + * is an optional accelerator, so a fallback is a slowdown, never a break. + * No sidecar replays ledger 9 yet, so this engine reads Dust in WASM, and says + * so before a sync from the start of the chain's history. + */ +async function nativeOrWasmDustFetcher( + seed: Buffer, + network: NetworkConfig, + opts: Parameters[2], +): Promise { + if (!nativeDustSyncAvailable() && opts.startFromId === 0 && !saidWasmDust) { + saidWasmDust = true; + notice(` Reading ${network.networkId}'s Dust history in WASM: no native sidecar runs ledger 9 yet, so a first sync takes a few minutes (about 2.5 on stagenet), then it is cached.`); + } + if (nativeDustSyncAvailable()) { + try { + return await runDustSyncNative(seed, network, opts); + } catch (err) { + opts.log?.('dust', `native sidecar failed, using WASM: ${(err as Error).message}`); + } + } + return defaultDustFetcher(seed, network, opts); +} + +// ── Helpers ─────────────────────────────────────────────── + +function networkNameOf(network: NetworkConfig): NetworkName { + const lower = network.networkId.toLowerCase(); + if (isValidNetworkName(lower)) return lower; + throw new Error(`Unsupported network: ${network.networkId}`); +} + +// ── Process-wide singleton ──────────────────────────────── + +let defaultRepo: WalletDataRepository | null = null; + +/** + * Process-wide repository instance. Long-lived MCP sessions share this so + * the in-memory cache layer is meaningful across tool calls. + */ +export function defaultRepository(): WalletDataRepository { + if (!defaultRepo) defaultRepo = new WalletDataRepository(); + return defaultRepo; +} + +/** Test/diagnostic: replace the process singleton (e.g. with a different `cacheDir`). */ +export function setDefaultRepository(repo: WalletDataRepository | null): void { + defaultRepo = repo; +} diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts new file mode 100644 index 00000000..ff943347 --- /dev/null +++ b/packages/engine-beta/src/wallet.ts @@ -0,0 +1,303 @@ +// The beta engine's wallet, as the rest of mn uses it: each operation runs the +// SDK's wallet (the facade) or mn's readers and hands back mn's own types. +// The flows are the ones the commands, the test preparation and mn serve ran +// themselves before the SDK moved behind the engine. + +import * as ledger from '@midnightntwrk/ledger-v9'; +import { MidnightBech32m } from '@midnightntwrk/wallet-sdk-address-format'; +import type { + DAppConnector, + EngineWallet, + OpenedConnector, + PrepWallet, + ServedWalletSession, + ShieldedTransferParams, +} from '@kuiralabs/midnight-cli-core/lib/engine'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { decodeShieldedAddress } from './addresses.ts'; +import { buildFacade, hasDustAvailable, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; +import { ensureDust, executeTransfer } from './transfer.ts'; +import { airdropNight } from './airdrop.ts'; +import { registerDust } from './dust-register.ts'; +import { exportDustSnapshot } from './dust-export.ts'; +import { defaultRepository } from './wallet-data-repository.ts'; +import { createDAppConnector } from './dapp-connector.ts'; + +const HOUR_MS = 60 * 60 * 1000; + +async function shieldedTransfer(params: ShieldedTransferParams): Promise { + const { seed, network, networkConfig, amount, progress, signal } = params; + const networkId = getNetworkId(networkConfig.networkId); + const nightToken = ledger.unshieldedToken().raw; + const receiverAddress = decodeShieldedAddress(params.recipient, network); + + return defaultRepository().withFacade( + seed, + networkConfig, + async ({ bundle, state }) => { + params.onSenderShieldedAddress?.(MidnightBech32m.encode(networkId, state.shielded.address).asString()); + + const shieldedBalance = state.shielded.balances[nightToken] ?? 0n; + if (shieldedBalance < amount) { + throw new Error(params.insufficient((Number(shieldedBalance) / 1_000_000).toFixed(6))); + } + + progress.update('Checking dust...'); + await ensureDust(bundle, (status: string) => progress.update(status)); + + throwIfCancelled(signal); + + progress.update('Building shielded transaction...'); + const build = () => bundle.facade.transferTransaction( + [{ + type: 'shielded' as const, + outputs: [{ type: nightToken, amount, receiverAddress }], + }], + bundle.secretKeys, + { ttl: new Date(Date.now() + HOUR_MS) }, + ); + const recipe = params.waitForDustToCover + ? await payWhenDustCovers(build, state.dust, { maxWaitMs: DUST_SHORT_WAIT_MS, onStatus: (status) => progress.update(status), signal }) + : await build(); + + progress.update('Signing...'); + const signed = await bundle.facade.signRecipe(recipe, bundle.keystore.signDataAsync); + + progress.update('Generating ZK proof (this may take a few minutes)...'); + const finalized = await bundle.facade.finalizeRecipe(signed); + + // facade.submitTransaction blocks until the chain finalizes the block + // (typically 12 to 30s on hosted networks, ~6 to 12s on localnet). + // trackElapsed updates the spinner once a second so users see the wait + // is alive, not stuck. + const txId = await trackElapsed( + progress, + 'Submitting and waiting for finalization (typically 12 to 30s)...', + bundle.facade.submitTransaction(finalized), + ); + return String(txId); + }, + { + syncMode: 'full', + log: params.log, + requireStrictSync: true, + signal, + onStatus: params.onStatus, + onSyncProgress: params.onSyncProgress, + onSyncDetail: params.onSyncDetail, + }, + ); +} + +/** The wallet a test's preparation checks, built from its saved state and synced quickly (no shielded sync). */ +async function syncedPrepWallet(wallet: PrepWallet, reportSync: boolean, beforeSync?: () => void) { + bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS); + const bundle = await buildFacade(wallet.seed, wallet.networkConfig, loadWalletCache(wallet.address, wallet.network)); + try { + beforeSync?.(); + const state = await startAndSyncFacade(bundle, { + syncMode: 'lite', + signal: wallet.signal, + ...(reportSync + ? { + onProgress: (applied: number, highest: number) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + wallet.onMessage(`Syncing wallet... ${pct}%`); + } + }, + onSyncDetail: (detail: string) => wallet.onMessage(`Syncing wallet... (${detail})`), + } + : {}), + }); + return { bundle, state }; + } catch (err) { + try { await stopFacade(bundle); } catch { /* best-effort */ } + throw err; + } +} + +async function prepNightBalance(wallet: PrepWallet): Promise { + const { bundle, state } = await syncedPrepWallet(wallet, true); + try { + const balance = state.unshielded.balances[ledger.unshieldedToken().raw] ?? 0n; + if (balance > 0n) { + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + } + return balance; + } finally { + try { await stopFacade(bundle); } catch { /* best-effort */ } + } +} + +async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAvailable: boolean; dustAvailable: boolean }> { + const { bundle } = await syncedPrepWallet(wallet, false, () => wallet.onMessage('Syncing wallet...')); + try { + // Register dust (auto-registers UTXOs if needed, no-op if already available) + wallet.onMessage('Ensuring dust...'); + const result = await ensureDust(bundle, (status) => wallet.onMessage(`Dust: ${status}`)); + if (result.alreadyAvailable) { + wallet.onMessage('Dust already available'); + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + return { alreadyAvailable: true, dustAvailable: true }; + } + + // Dust was just registered: wait for coins to actually appear on chain. + // This must use the same facade to get real-time state updates. + wallet.onMessage('Dust registered. Waiting for coins to become available...'); + const dustAvailable = hasDustAvailable(await waitForDustAvailable(bundle, waitMs, wallet.signal)); + if (dustAvailable) { + wallet.onMessage('Dust is available'); + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + } + return { alreadyAvailable: false, dustAvailable }; + } finally { + try { await stopFacade(bundle); } catch { /* best-effort */ } + } +} + +const openConnector: EngineWallet['openConnector'] = async (options): Promise => { + const { seed, network, networkConfig, address, syncMode, signal, onMessage } = options; + // On a ledger-8 chain the SDK's sync would retry forever. + await assertLedgerSupported(network, networkConfig, undefined, signal); + // A failure before the connector is handed back stops what was started, so + // the facade doesn't keep syncing. + let bundle: Awaited> | undefined; + let connector: DAppConnector; + try { + // Build & sync facade + onMessage('Building wallet facade...'); + const indexerChange = bindCachesToIndexer(network, networkConfig.indexerWS); + if (indexerChange) onMessage(describeIndexerChange(network, indexerChange)); + // As the repository's own borrowers do: warm the Dust checkpoint, then + // restore from it when there is no saved wallet, instead of the SDK + // replaying the chain's whole Dust history (minutes on a hosted network). + const repo = defaultRepository(); + // Best-effort, as there: a failed warm-up leaves the sync below to do it. + try { + await repo.dust(seed, networkConfig, { signal, onStatus: onMessage }); + } catch { + throwIfCancelled(signal); // a cancel is not a failed warm-up + } + const cache = await repo.walletStateToRestore(seed, networkConfig, network); + const built = await buildFacade(seed, networkConfig, cache); + bundle = built; + + onMessage('Syncing wallet...'); + await startAndSyncFacade(built, { + syncMode, + signal, + onProgress: (applied, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + onMessage(`Syncing wallet... ${pct}%`); + } + }, + }); + onMessage('Wallet synced'); + + // Wait for dust + onMessage('Waiting for dust...'); + const syncedState = await waitForDustAvailable(built, undefined, signal); + onMessage('Dust ready'); + + // Save cache after sync + try { await saveWalletCache(address, network, built.facade); } catch { /* best-effort */ } + + // Create DApp Connector — approve-all mode for tests + connector = createDAppConnector({ + bundle: built, + networkConfig, + approvalOptions: { approveAll: true, autoApproveReads: true }, + // Reads answer from the state this sync ended on, and from every later + // one that is synced by the rule the sync used. + initialState: syncedState, + isCurrent: (state) => isFacadeSynced(state, syncMode, built.emptyStreams), + dustWaitMs: options.dustWaitMs, + callbacks: { + onPhaseStart: (_connId, _method, phase) => { + onMessage(`${phase}...`); + }, + onPhaseComplete: (_connId, _method, phase, durationMs) => { + onMessage(`${phase} ${Math.round(durationMs)}ms`); + }, + }, + }); + } catch (err) { + if (bundle !== undefined) { try { await stopFacade(bundle); } catch { /* best-effort */ } } + throw err; + } + const started = bundle; + return { + connector, + async stop() { + connector.dispose(); + try { await stopFacade(started); } catch { /* best-effort */ } + }, + }; +}; + +const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { + const { seed, networkConfig, network, address, syncMode } = options; + // The repository owns validating the caches, priming Dust, building the + // facade, syncing (with retries) and stopping it. Its save is skipped: mn + // serve saves only when no transaction is pending, since the SDK drops + // pending Dust on serialization and would persist dust=0. + return defaultRepository().withFacade(seed, networkConfig, async ({ bundle }) => { + let lastState: Awaited> | undefined; + const session: ServedWalletSession = { + async waitForDust() { + lastState = await waitForDustAvailable(bundle); + return hasDustAvailable(lastState); + }, + async saveState() { + try { await saveWalletCache(address, network, bundle.facade); } catch { /* best-effort */ } + }, + connect: ({ approvalOptions, feeLimits, callbacks }) => createDAppConnector({ + bundle, + networkConfig, + approvalOptions, + feeLimits, + callbacks, + // Reads answer from the state this sync ended on, and from every later + // one that is synced by the rule the sync used. + initialState: lastState, + isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), + }), + }; + return serve(session); + }, { + syncMode, + // serve accepts write requests from dApps — must be strictly synced. + requireStrictSync: true, + skipAutoSave: true, + signal: options.signal, + log: options.log, + onStatus: options.onStatus, + onSyncProgress: options.onSyncProgress, + onSyncDetail: options.onSyncDetail, + }); +}; + +export const betaWallet: EngineWallet = { + unshieldedBalance: (address, networkConfig, options) => defaultRepository().unshielded(address, networkConfig, options), + async dustBalance(seed, networkConfig, options) { + const { state: _state, ...balance } = await defaultRepository().dust(seed, networkConfig, options); + return balance; + }, + transfer: executeTransfer, + airdrop: airdropNight, + shieldedTransfer, + registerDust, + exportDust: (seed, network, networkConfig, options) => exportDustSnapshot(seed, network, networkConfig, options), + prepNightBalance, + prepDust, + openConnector, + serveWallet, +}; diff --git a/packages/engine-beta/tsconfig.build.json b/packages/engine-beta/tsconfig.build.json new file mode 100644 index 00000000..16f7d7d6 --- /dev/null +++ b/packages/engine-beta/tsconfig.build.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node", + "ws" + ] + }, + "include": [ + "src/**/*.ts" + ] +} diff --git a/packages/engine-rc/src/dust-sync-native.ts b/packages/engine-rc/src/dust-sync-native.ts index a66f304b..d648988d 100644 --- a/packages/engine-rc/src/dust-sync-native.ts +++ b/packages/engine-rc/src/dust-sync-native.ts @@ -20,7 +20,7 @@ import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { cacheRootDir } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { cacheRootDir, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; /** Sidecar checkpoint JSON shape (snake_case — matches the Rust `Checkpoint`). */ @@ -126,7 +126,7 @@ function readCheckpointCursor(path: string): number { /** The sidecar's checkpoint file for a Dust key, beside the other Dust caches. */ function nativeCheckpointPath(networkName: string, pubkeyHex: string, cacheDir?: string): string { - const dir = join(cacheRootDir(cacheDir), networkName); + const dir = join(cacheRootDir(cacheDir), networkCacheFolder(networkName)); if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE }); return join(dir, nativeCheckpointName(pubkeyHex)); } diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 700d79a3..8113888c 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -112,6 +112,7 @@ export const WORKSPACE_PACKAGES = [ { name: '@kuiralabs/midnight-chain', dir: join(ROOT, 'packages', 'chain', 'src') }, // The rc engine: its files read as engine/rc/, its index the package itself. { name: '@kuiralabs/midnight-engine-rc', dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/' }, + { name: '@kuiralabs/midnight-engine-beta', dir: join(ROOT, 'packages', 'engine-beta', 'src'), prefix: 'engine/beta/' }, ]; /** The package source folder a file is in, or undefined for one under src/. */ diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 6a09e813..7c7fe4cd 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -85,11 +85,16 @@ export const ALLOWED_STATE = { // Shared on purpose: none holds a call's state. 'lib/passphrase.ts': { unlocked: 'shared on purpose: the passphrase this process has unlocked, by state root (one prompt per run)' }, 'engine/rc/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, + 'engine/beta/wallet-data-repository.ts': { + defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls', + saidWasmDust: 'shared on purpose: the WASM Dust notice is said once per process', + }, 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/ws-rpc.ts': { connectionCounter: 'shared on purpose: the RPC connection id counter, unique across servers in the process' }, 'lib/engine.ts': { loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)', loader: 'shared on purpose: the host sets the engine loader once', + preferred: 'shared on purpose: the set work every set does alike loads while no engine is loaded, the set of the call it runs for', }, 'lib/wallet-config.ts': { warnedPlain: 'shared on purpose: each plain-text wallet is warned about once per run' }, // The host sources, set once by the host at start (handlers see them through the context). diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index 572413d1..b076b2c8 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -10,7 +10,13 @@ import { unsetConfigValue, getValidConfigKeys, getBlockfrostProjectId, + getSdkSetOverride, } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { sdkSetOfNetwork } from '@kuiralabs/midnight-cli-core/lib/network'; +import { getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; const TEST_DIR = path.join(os.tmpdir(), `midnight-cli-config-test-${process.pid}`); @@ -556,3 +562,50 @@ describe('endpoint keys for a network other than the selected one (--network)', expect(() => getConfigValue('network', TEST_DIR, 'preprod')).toThrow('--network only applies to the endpoint keys'); }); }); + +describe('the sdk-set key', () => { + it('sets, reads and unsets a network\'s SDK set, the selected network\'s unless --network says', () => { + expect(getConfigValue('sdk-set', TEST_DIR)).toBe('(not set)'); + setConfigValue('sdk-set', 'beta', TEST_DIR); + setConfigValue('sdk-set', 'rc', TEST_DIR, 'stagenet'); + expect(getConfigValue('sdk-set', TEST_DIR)).toBe('beta'); + expect(getConfigValue('sdk-set', TEST_DIR, 'stagenet')).toBe('rc'); + expect(getSdkSetOverride(loadCliConfig(TEST_DIR), 'undeployed')).toBe('beta'); + unsetConfigValue('sdk-set', TEST_DIR); + expect(getConfigValue('sdk-set', TEST_DIR)).toBe('(not set)'); + expect(getConfigValue('sdk-set', TEST_DIR, 'stagenet')).toBe('rc'); + }); + + it('refuses a set mn has no engine for', () => { + expect(() => setConfigValue('sdk-set', 'mainnet', TEST_DIR)).toThrow('Invalid SDK set: "mainnet"\nValid SDK sets: rc, beta'); + }); + + it('drops a set it doesn\'t know from a hand-edited file', () => { + fs.writeFileSync(path.join(TEST_DIR, 'config.json'), JSON.stringify({ network: 'undeployed', networks: { undeployed: { 'sdk-set': 'gamma' } } })); + expect(getSdkSetOverride(loadCliConfig(TEST_DIR), 'undeployed')).toBeUndefined(); + }); +}); + +describe('the SDK set a network runs on', () => { + const root = path.join(TEST_DIR, 'state'); + beforeEach(() => setHostPathsSource(() => ({ stateRoot: root, home: TEST_DIR }))); + afterEach(() => setHostPathsSource(() => ({ stateRoot: path.join(os.homedir(), MIDNIGHT_DIR), home: os.homedir() }))); + + it('is the table\'s until config gives the network another, and the caches follow it to a folder of the set\'s own', () => { + expect(sdkSetOfNetwork('undeployed')).toBe('rc'); + expect(networkCacheFolder('undeployed')).toBe('undeployed'); + expect(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')).toBe(path.join(root, 'cache', 'undeployed', 'mn_addr_undeployed1a.json')); + + setConfigValue('sdk-set', 'beta', undefined, 'undeployed'); + expect(sdkSetOfNetwork('undeployed')).toBe('beta'); + expect(networkCacheFolder('undeployed')).toBe('undeployed.beta'); + expect(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')).toBe(path.join(root, 'cache', 'undeployed.beta', 'mn_addr_undeployed1a.json')); + expect(getDustCachePath('undeployed', 'ab'.repeat(32))).toBe(path.join(root, 'cache', 'undeployed.beta', `dust-${'ab'.repeat(10)}.json`)); + + // Back on the network's own set, the caches it kept there are the ones read. + unsetConfigValue('sdk-set', undefined, 'undeployed'); + expect(networkCacheFolder('undeployed')).toBe('undeployed'); + expect(sdkSetOfNetwork('stagenet')).toBe('beta'); + expect(networkCacheFolder('stagenet')).toBe('stagenet'); + }); +}); diff --git a/src/__tests__/derive-address.test.ts b/src/__tests__/derive-address.test.ts index f1c67154..87cae70f 100644 --- a/src/__tests__/derive-address.test.ts +++ b/src/__tests__/derive-address.test.ts @@ -72,7 +72,7 @@ describe('deriveUnshieldedAddress', () => { describe('deriveAllShieldedAddresses', () => { it('returns one shielded address per supported network', () => { const out = deriveAllShieldedAddresses(genesisSeedBuffer); - expect(Object.keys(out).sort()).toEqual(['preprod', 'preview', 'undeployed']); + expect(Object.keys(out).sort()).toEqual(['preprod', 'preview', 'stagenet', 'undeployed']); }); it('each address has the correct network prefix', () => { diff --git a/src/__tests__/engine-beta.test.ts b/src/__tests__/engine-beta.test.ts new file mode 100644 index 00000000..56b90341 --- /dev/null +++ b/src/__tests__/engine-beta.test.ts @@ -0,0 +1,110 @@ +// The beta engine, the one stagenet runs, in a process of its own: its set, +// its compiler, keys that match the rc engine's, and its connector, whose +// facade (stubbed at the SDK boundary) takes the wallet's secret keys on every +// call that spends, and refuses transaction work before the wallet's first state. + +import { describe, it, expect, vi } from 'vitest'; +import * as rx from 'rxjs'; +import { betaEngine } from '@kuiralabs/midnight-engine-beta'; +import { createDAppConnector } from '@kuiralabs/midnight-engine-beta/dapp-connector'; +import type { FacadeBundle } from '@kuiralabs/midnight-engine-beta/facade'; +import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-beta/derive-address'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; + +// The beta set's own address classes, as the engine resolves them: the +// repository's root holds the rc set's. +const { DustAddress, UnshieldedAddress } = await import(new URL('../../packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-address-format/dist/index.js', import.meta.url).href) as typeof import('@midnightntwrk/wallet-sdk-address-format'); + +const STAGENET: NetworkConfig = { + indexer: 'http://localhost:8088/api/v4/graphql', + indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', + node: 'ws://localhost:9944', + proofServer: 'http://localhost:6300', + networkId: 'StageNet', +}; + +const NIGHT = '0000000000000000000000000000000000000000000000000000000000000000'; +const ctx = (): RpcHandlerContext => ({ notify: vi.fn(), connectionId: 'conn_beta', requestId: 1, metadata: {} }); + +/** A facade state with NIGHT and Dust, as the beta SDK reports it (no protocol versions). */ +function stateWithFunds() { + return { + isSynced: true, + unshielded: { balances: { [NIGHT]: 5_000_000n }, address: new UnshieldedAddress(Buffer.alloc(32, 7)), progress: { appliedId: 1n, highestTransactionId: 1n } }, + shielded: { balances: {}, address: deriveShieldedAddress(Buffer.from('00'.repeat(31) + '07', 'hex')) }, + dust: { balance: () => 1_000_000_000_000_000n, availableCoins: [], address: new DustAddress(7n) }, + }; +} + +const SECRET_KEYS = { shieldedSecretKeys: { tag: 'zswap' }, dustSecretKey: { tag: 'dust' } }; + +function bundleWith(states: rx.Observable, facade: Record = {}): FacadeBundle { + return { + facade: { + state: () => states, + transferTransaction: vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }), + initSwap: vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }), + signRecipe: vi.fn().mockResolvedValue({ type: 'SIGNED' }), + finalizeRecipe: vi.fn().mockResolvedValue({ serialize: () => new Uint8Array([0xab, 0xcd]) }), + ...facade, + }, + keystore: { signDataAsync: vi.fn(), getPublicKey: vi.fn() }, + secretKeys: SECRET_KEYS, + } as unknown as FacadeBundle; +} + +const RECIPIENT = 'mn_addr_stagenet1ugtvumxjrspvh598y6agtw3sdk06qf8sl0x0pfu6lf2080wrnprsqxvrpj'; + +describe('the beta engine', () => { + it('runs the beta set, on contracts compactc 0.33 writes', () => { + expect(betaEngine.set).toBe('beta'); + expect(betaEngine.contracts.scripts.compiler).toBe('compactc 0.33'); + expect(betaEngine.contracts.scripts.compactRuntimeVersion).toBe('0.18.0-rc.1'); + expect(betaEngine.contracts.scripts.acceptsRuntime('0.18.0')).toBe(true); + expect(betaEngine.contracts.scripts.acceptsRuntime('0.20.0')).toBe(false); + }); + + it('derives the addresses the rc engine derives, on every network', () => { + // The rc engine's address for this seed on stagenet, as a new wallet's file records it. + const seed = Buffer.alloc(32, 2); + expect(betaEngine.keys.unshieldedAddress(seed, 'stagenet')).toBe(RECIPIENT); + expect(betaEngine.keys.unshieldedAddresses(seed).undeployed).toBe('mn_addr_undeployed1ugtvumxjrspvh598y6agtw3sdk06qf8sl0x0pfu6lf2080wrnprsdj8xxx'); + }); +}); + +describe('the beta engine\'s connector', () => { + it('refuses transaction work before the wallet\'s first state, as the rc engine does', async () => { + const connector = createDAppConnector({ bundle: bundleWith(rx.NEVER), networkConfig: STAGENET, approvalOptions: { approveAll: true } }); + try { + await expect(connector.handlers.makeTransfer({ desiredOutputs: [{ kind: 'unshielded', type: NIGHT, value: '1', recipient: RECIPIENT }] }, ctx())) + .rejects.toMatchObject({ code: 'Disconnected', reason: 'Wallet not synced yet' }); + await expect(connector.handlers.getUnshieldedBalances({}, ctx())).rejects.toMatchObject({ code: 'Disconnected' }); + } finally { + connector.dispose(); + } + }); + + it('hands the facade the wallet\'s secret keys to build a transfer and a swap', async () => { + const bundle = bundleWith(rx.of(stateWithFunds())); + const connector = createDAppConnector({ bundle, networkConfig: STAGENET, approvalOptions: { approveAll: true } }); + try { + const output = { kind: 'unshielded', type: NIGHT, value: '1', recipient: RECIPIENT }; + await expect(connector.handlers.makeTransfer({ desiredOutputs: [output] }, ctx())).resolves.toEqual({ tx: 'abcd' }); + expect((bundle.facade.transferTransaction as unknown as ReturnType).mock.calls[0]![1]).toBe(SECRET_KEYS); + await expect(connector.handlers.makeIntent({ desiredInputs: [{ kind: 'unshielded', type: NIGHT, value: '1' }], desiredOutputs: [output], options: {} }, ctx())).resolves.toEqual({ tx: 'abcd' }); + expect((bundle.facade.initSwap as unknown as ReturnType).mock.calls[0]![2]).toBe(SECRET_KEYS); + } finally { + connector.dispose(); + } + }); + + it('refuses a transaction it can\'t read as ledger 9 as the caller\'s mistake', async () => { + const connector = createDAppConnector({ bundle: bundleWith(rx.of(stateWithFunds())), networkConfig: STAGENET, approvalOptions: { approveAll: true } }); + try { + await expect(connector.handlers.balanceUnsealedTransaction({ tx: 'beef' }, ctx())).rejects.toMatchObject({ code: 'InvalidRequest' }); + } finally { + connector.dispose(); + } + }); +}); diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index 611700f0..7ca91bc5 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -2,17 +2,26 @@ // same for work every set does alike. import { describe, expect, it } from 'vitest'; -import { anyEngine, engineFor, sdkSetOf, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { OtherSdkSetError, anyEngine, engineFor, preferEngineOf, sdkSetOf, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { getValidNetworkNames, sdkSetOfNetwork, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { rcEngine } from '@kuiralabs/midnight-engine-rc'; describe('the engine for a network', () => { - it('is the rc engine for every network mn knows today', async () => { + it('is the rc engine for every network but stagenet, which runs the beta set', async () => { for (const network of getValidNetworkNames() as NetworkName[]) { + if (network === 'stagenet') continue; expect(sdkSetOf(network)).toBe('rc'); expect(await engineFor(network)).toBe(rcEngine); } + expect(sdkSetOf('stagenet')).toBe('beta'); + }); + + it('refuses stagenet in a process that has loaded the rc engine, naming both sets', async () => { + await engineFor('undeployed'); + const refusal = await engineFor('stagenet').catch((err: unknown) => err); + expect(refusal).toBeInstanceOf(OtherSdkSetError); + expect(refusal).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'rc', wantedSet: 'beta' }); }); it('is the one loaded in this process for work every set does alike', async () => { @@ -47,6 +56,20 @@ describe('the network picks the engine', () => { } }); + it('loads the set of the call\'s network for work every set does alike, before any engine is loaded', async () => { + const asked: string[] = []; + const beta = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; + setEngineLoader(async (set) => { asked.push(set); return set === 'beta' ? beta : rcEngine; }); + try { + preferEngineOf('stagenet'); + expect(await anyEngine()).toBe(beta); + expect(asked).toStrictEqual(['beta']); + } finally { + preferEngineOf('undeployed'); + setEngineLoader(loadInstalledEngine); + } + }); + it('refuses a second set in a process that has loaded one', async () => { const other = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; setEngineLoader(async () => other); diff --git a/src/__tests__/grant-prepare.test.ts b/src/__tests__/grant-prepare.test.ts index 447d5213..c039fd6e 100644 --- a/src/__tests__/grant-prepare.test.ts +++ b/src/__tests__/grant-prepare.test.ts @@ -52,6 +52,13 @@ describe('prepareGrant', () => { expect(fs.existsSync(accounts())).toBe(false); }); + it('refuses stagenet, which runs the beta SDK set the account package has no build for, saying so', async () => { + const refusal = asAlice('status', '--network', 'stagenet'); + await expect(refusal).rejects.toThrow(UnreachableByAccountError); + await expect(refusal).rejects.toThrow('mn grant runs on the rc SDK set, and StageNet runs on the beta set'); + expect(fs.existsSync(accounts())).toBe(false); + }); + it('prepares the deploy of a new account: records under the wallet\'s name, readable by their owner only', async () => { aliceWallet(); const prepared = await asAlice('deploy'); diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index ec8f7bd6..b346d367 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -185,7 +185,7 @@ describe('help — the lists come from the registry', () => { expect(manifest.globalFlags).toStrictEqual([ { name: '--json', description: 'Output structured JSON to stdout (suppresses all stderr)' }, { name: '--wallet ', description: 'Wallet name or path' }, - { name: '--network ', description: 'Override network (preprod, preview, undeployed)' }, + { name: '--network ', description: 'Override network (preprod, preview, stagenet, undeployed)' }, { name: '--version, -v', description: 'Print CLI version' }, { name: '--help, -h', description: 'Show help' }, ]); diff --git a/src/__tests__/mcp-server-advice.test.ts b/src/__tests__/mcp-server-advice.test.ts new file mode 100644 index 00000000..74addceb --- /dev/null +++ b/src/__tests__/mcp-server-advice.test.ts @@ -0,0 +1,23 @@ +// A call the MCP server can't take because of the SDK set it runs is told to use a server of its own. + +import { describe, expect, it } from 'vitest'; +import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { withServerAdvice } from '../lib/mcp/server-advice.ts'; + +describe('the MCP server\'s advice for a call on the other SDK set', () => { + it('names the networks of the set it can\'t load, and says to start a server for them', () => { + const advised = withServerAdvice(new OtherSdkSetError('rc', 'beta')); + expect(advised).toBeInstanceOf(OtherSdkSetError); + expect(advised).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'rc', wantedSet: 'beta' }); + expect(advised.message).toBe("This MCP server runs the rc SDK set, and stagenet runs on the beta set: two sets' ledgers can't share a process. Start another MCP server for stagenet and make the call there."); + }); + + it('names every network of the rc set the other way round', () => { + expect(withServerAdvice(new OtherSdkSetError('beta', 'rc')).message).toContain('and preprod, preview, undeployed run on the rc set'); + }); + + it('leaves every other error as it was', () => { + const error = new Error('something else'); + expect(withServerAdvice(error)).toBe(error); + }); +}); diff --git a/src/__tests__/mcp-server-unknown-parameter.test.ts b/src/__tests__/mcp-server-unknown-parameter.test.ts index 1075b7bf..07addefe 100644 --- a/src/__tests__/mcp-server-unknown-parameter.test.ts +++ b/src/__tests__/mcp-server-unknown-parameter.test.ts @@ -47,7 +47,7 @@ describe('a tool\'s schema, generated from its command\'s flags', () => { 'to', 'amount', 'wallet', 'force-shielded', 'network', 'shielded', 'node', 'indexer-ws', 'proof-server', ]); expect(transfer.inputSchema.properties!.network).toStrictEqual({ - type: 'string', enum: ['preprod', 'preview', 'undeployed'], description: 'Network to send on (default: the selected one)', + type: 'string', enum: ['preprod', 'preview', 'stagenet', 'undeployed'], description: 'Network to send on (default: the selected one)', }); expect(transfer.inputSchema.required).toStrictEqual(['to', 'amount']); }, 60_000); @@ -151,7 +151,7 @@ describe('a tool parameter of the wrong type', () => { expect(body).toMatchObject({ error: true, code: 'INVALID_ARGS', - message: 'Invalid parameters for midnight_address: network must be one of preprod, preview, undeployed, not "mainnet"; index must be a string, not {"n":1}', + message: 'Invalid parameters for midnight_address: network must be one of preprod, preview, stagenet, undeployed, not "mainnet"; index must be a string, not {"n":1}', }); }, 60_000); diff --git a/src/__tests__/network.test.ts b/src/__tests__/network.test.ts index 5a04ca64..295a3783 100644 --- a/src/__tests__/network.test.ts +++ b/src/__tests__/network.test.ts @@ -105,12 +105,13 @@ describe('getNetworkConfig', () => { }); describe('getValidNetworkNames', () => { - it('returns all three networks', () => { + it('returns all four networks', () => { const names = getValidNetworkNames(); expect(names).toContain('preprod'); expect(names).toContain('preview'); + expect(names).toContain('stagenet'); expect(names).toContain('undeployed'); - expect(names).toHaveLength(3); + expect(names).toHaveLength(4); }); it('agrees with isValidNetworkName', () => { diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index c9ba2ca7..d4b64616 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -65,7 +65,10 @@ describe('the state root the host gives', () => { expect(fs.readFileSync(path.join(root, 'config.json'), 'utf8')).toBe(before.config); expect(fs.readFileSync(path.join(root, 'cache/undeployed/indexer.host'), 'utf8')).toBe(before.marker); expect(Object.keys(wallet)).toEqual(before.walletKeys); - expect(wallet.addresses).toEqual(before.walletAddresses); + // Every address the layout had, and stagenet's, which a new wallet has had since mn added stagenet. + const { stagenet, ...recorded } = wallet.addresses; + expect(recorded).toEqual(before.walletAddresses); + expect(stagenet).toMatch(/^mn_addr_stagenet1/); expect(Object.keys(JSON.parse(fs.readFileSync(path.join(root, 'keystore.json'), 'utf8')))).toEqual(before.keystoreKeys); expect({ walletCache: rel(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')), diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 428c2dbc..630926af 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import { loadWalletConfig, matchWalletAddress, unlockWallet, writeSealedWallet, type WalletInfo } from '../lib/wallet-config.ts'; +import { loadWalletConfig, matchWalletAddress, unlockWallet, walletAddress, writeSealedWallet, type WalletInfo } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -224,3 +224,36 @@ describe('matchWalletAddress', () => { expect(matchWalletAddress([], VALID_ADDRESSES.undeployed)).toBeUndefined(); }); }); + +describe('a wallet written before stagenet', () => { + // The addresses an earlier mn wrote: every network but stagenet. + const { stagenet: stagenetAddress, ...earlierAddresses } = VALID_ADDRESSES; + const { stagenet: stagenetShielded, ...earlierShielded } = deriveAllShieldedAddresses(Buffer.from(VALID_SEED, 'hex')); + + it('gets its stagenet address derived and saved when a plain-text wallet is read', async () => { + const filePath = path.join(TEST_DIR, 'plain.json'); + fs.writeFileSync(filePath, JSON.stringify({ seed: VALID_SEED, addresses: earlierAddresses, createdAt: VALID_CONFIG.createdAt })); + const config = await loadWalletConfig(filePath); + expect(config.addresses.stagenet).toBe(stagenetAddress); + expect(JSON.parse(fs.readFileSync(filePath, 'utf-8')).addresses).toEqual(VALID_ADDRESSES); + expect(await walletAddress(filePath, 'stagenet')).toBe(stagenetAddress); + }); + + it('keeps a sealed wallet as written until it is unlocked, then derives and saves its stagenet addresses beside the sealed secret', async () => { + const filePath = path.join(TEST_DIR, 'sealed.json'); + writeSealedWallet(filePath, { addresses: earlierAddresses as typeof VALID_ADDRESSES, shieldedAddresses: earlierShielded as typeof VALID_ADDRESSES, createdAt: VALID_CONFIG.createdAt }, { seed: VALID_SEED }, PASSPHRASE); + const sealedBefore = JSON.parse(fs.readFileSync(filePath, 'utf-8')).sealed; + + expect((await loadWalletConfig(filePath)).addresses.stagenet).toBeUndefined(); + + const unlocked = await unlockWallet(filePath, UNLOCK); + expect(unlocked.addresses.stagenet).toBe(stagenetAddress); + expect(unlocked.shieldedAddresses?.stagenet).toBe(stagenetShielded); + const saved = JSON.parse(fs.readFileSync(filePath, 'utf-8')); + expect(saved.addresses).toEqual(VALID_ADDRESSES); + expect(saved.shieldedAddresses.stagenet).toBe(stagenetShielded); + expect(saved.sealed).toEqual(sealedBefore); + expect(saved.seed).toBeUndefined(); + expect((await loadWalletConfig(filePath)).addresses.stagenet).toBe(stagenetAddress); + }); +}); diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index d4b99768..98427c89 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -11,7 +11,7 @@ import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { loadWalletConfig, resolveWalletPath, saveShieldedAddress } from '../lib/wallet-config.ts'; +import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAddress } from '../lib/wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -98,17 +98,17 @@ async function resolveDestination( // Fall back to wallet file (name, path, or active wallet) const walletPath = resolveWalletPath(walletFlag); - const config = await loadWalletConfig(walletPath); if (isShielded) { - // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase. - const stored = config.shieldedAddresses?.[networkName]; + // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase + // (unless the network was added after the wallet was written). + const stored = await walletShieldedAddress(walletPath, networkName); if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${networkName}.`); const decoded = await resolveAddressDestination(stored, networkName, true) as ShieldedDestination; return { kind: 'wallet', bech32m: decoded.bech32m, walletPath }; } - return { kind: 'address', address: config.addresses[networkName] }; + return { kind: 'address', address: await walletAddress(walletPath, networkName) }; } async function resolveAddressDestination( diff --git a/src/commands/connect.guidance.ts b/src/commands/connect.guidance.ts index 8528a471..1f53f155 100644 --- a/src/commands/connect.guidance.ts +++ b/src/commands/connect.guidance.ts @@ -59,7 +59,7 @@ DApp developers connect via the midnight-wallet-connector npm package: import { createWalletClient } from 'midnight-wallet-connector'; const wallet = await createWalletClient({ url: 'ws://localhost:9932', - networkId: 'undeployed', // or 'preprod', 'preview' — lowercase per @midnightntwrk/wallet-sdk + networkId: 'undeployed', // or 'preprod', 'preview', 'stagenet' — lowercase per @midnightntwrk/wallet-sdk }); const balances = await wallet.getUnshieldedBalances(); diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index a225af8a..8fcad9c1 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -1,5 +1,6 @@ // The `generate` command, described once. +import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const generateDefinition: CommandDefinition = { @@ -19,7 +20,7 @@ export const generateDefinition: CommandDefinition = { { name: 'network', takesValue: true, - help: ['--network Network: preprod, preview, undeployed'], + help: [`--network Network: ${getValidNetworkNames().join(', ')}`], }, { name: 'output', @@ -46,7 +47,7 @@ export const generateDefinition: CommandDefinition = { ], examples: ['midnight generate --network preprod'], jsonFields: { - addresses: 'Per-network unshielded addresses { preprod, preview, undeployed }', + addresses: `Per-network unshielded addresses { ${getValidNetworkNames().join(', ')} }`, activeAddress: 'Unshielded address on the active network (bech32m)', activeNetwork: 'The active network', seed: 'Hex-encoded seed (32-byte raw, or 64-byte if mnemonic-derived)', diff --git a/src/commands/info.definition.ts b/src/commands/info.definition.ts index f154373f..062b2cee 100644 --- a/src/commands/info.definition.ts +++ b/src/commands/info.definition.ts @@ -1,5 +1,6 @@ // The `info` command, described once. +import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const infoDefinition: CommandDefinition = { @@ -24,8 +25,8 @@ export const infoDefinition: CommandDefinition = { flags: [{ flag: 'wallet' }], examples: ['midnight info', 'midnight info --wallet my-wallet.json'], jsonFields: { - addresses: 'Per-network unshielded addresses { preprod, preview, undeployed }', - shieldedAddresses: 'Per-network shielded addresses { preprod, preview, undeployed }', + addresses: `Per-network unshielded addresses { ${getValidNetworkNames().join(', ')} }`, + shieldedAddresses: `Per-network shielded addresses { ${getValidNetworkNames().join(', ')} }`, activeNetwork: 'Currently active network', activeAddress: 'Unshielded address for active network (also written to stdout)', createdAt: 'ISO 8601 creation timestamp', diff --git a/src/commands/info.ts b/src/commands/info.ts index ed198873..5c0dc769 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -2,7 +2,7 @@ // Shows addresses for all networks + shielded, creation date, file path import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { loadWalletConfig, resolveWalletPath } from '../lib/wallet-config.ts'; +import { loadWalletConfig, resolveWalletPath, walletAddress } from '../lib/wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; import { formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; @@ -13,7 +13,7 @@ export default async function infoCommand(args: ParsedArgs, ctx: CallContext): P const resolvedPath = resolveWalletPath(getFlag(args, 'wallet')); const config = await loadWalletConfig(resolvedPath); const activeNetwork = resolveNetworkName({ args }); - const activeAddress = config.addresses[activeNetwork]; + const activeAddress = await walletAddress(resolvedPath, activeNetwork); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/manual.ts b/src/commands/manual.ts index f3d1d120..618286a9 100644 --- a/src/commands/manual.ts +++ b/src/commands/manual.ts @@ -73,8 +73,8 @@ export function buildManual(): string { out.push(''); out.push(`${bold('DESCRIPTION')}`); out.push(` midnight-wallet-cli is a standalone CLI that handles wallet`); - out.push(` operations, contract deployment, and a development loop, on three`); - out.push(` networks (undeployed, preprod, preview). Every command speaks`); + out.push(` operations, contract deployment, and a development loop, on four`); + out.push(` networks (undeployed, preprod, preview, stagenet). Every command speaks`); out.push(` JSON via --json for use with AI agents and scripts. An MCP`); out.push(` server ships with the package.`); out.push(''); @@ -176,6 +176,8 @@ export function buildManual(): string { out.push(` Your Blockfrost project id for preprod, whose indexer and`); out.push(` node Blockfrost serves. Kept per network, shown masked,`); out.push(` never printed. Or: MN_BLOCKFROST_PROJECT_ID / BLOCKFROST_PROJECT_ID.`); + out.push(` ${yellow('sdk-set')} The SDK set a network runs on (rc or beta), per network;`); + out.push(` each network has its own (stagenet beta, the rest rc).`); out.push(''); out.push(` ${bold('Compatibility alias')}`); out.push(` ${yellow('network-id')} Resolves transparently to ${yellow('network')}.`); diff --git a/src/commands/test.ts b/src/commands/test.ts index 6f3f7f7a..02bfe371 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -2,6 +2,7 @@ // Usage: midnight test [options] // Discovers dapp.test.json in the current directory and executes test suites. +import { isValidNetworkName, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { StringDecoder } from 'node:string_decoder'; import { join } from 'node:path'; import { mkdirSync } from 'node:fs'; @@ -59,7 +60,7 @@ export default async function testCommand(args: ParsedArgs, ctx: CallContext): P import type { CreateStrategy, BrowserOptions } from '../lib/test/create.ts'; -type NetworkOpt = 'preprod' | 'preview' | 'undeployed'; +type NetworkOpt = NetworkName; /** Allow either canonical strategy names or the friendlier "ui" alias. */ function parseStrategyFlag(flag: string | undefined): CreateStrategy | undefined { @@ -72,7 +73,7 @@ function parseStrategyFlag(flag: string | undefined): CreateStrategy | undefined /** Narrow a free-form network flag down to the supported set, or undefined. */ function parseNetworkFlag(flag: string | undefined): NetworkOpt | undefined { - return flag === 'preprod' || flag === 'preview' || flag === 'undeployed' ? flag : undefined; + return flag !== undefined && isValidNetworkName(flag) ? flag : undefined; } /** Collect browser-specific flags into a partial; throws on bad port or browser-mode. */ diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index f0ed60e2..00fe382a 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -1,5 +1,6 @@ // The `wallet` command, described once. +import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; export const walletDefinition: CommandDefinition = { @@ -38,7 +39,7 @@ export const walletDefinition: CommandDefinition = { takesValue: true, // list and info show the addresses for it. subcommands: ['generate', 'list', 'info'], - help: ['--network Network: preprod, preview, undeployed'], + help: [`--network Network: ${getValidNetworkNames().join(', ')}`], agent: NETWORK_PARAM, }, { @@ -92,8 +93,8 @@ export const walletDefinition: CommandDefinition = { network: 'Network the address is for (info, slim output over MCP)', address: 'Unshielded address on that network (info, slim output over MCP)', shieldedAddress: 'Shielded address on that network, or null before the first sync (info, slim output over MCP)', - addresses: 'Per-network unshielded addresses { preprod, preview, undeployed } (generate, info)', - shieldedAddresses: 'Per-network shielded addresses { preprod, preview, undeployed } (generate, info)', + addresses: `Per-network unshielded addresses { ${getValidNetworkNames().join(', ')} } (generate, info)`, + shieldedAddresses: `Per-network shielded addresses { ${getValidNetworkNames().join(', ')} } (generate, info)`, activeAddress: 'Unshielded address on the active network (generate, info)', activeNetwork: 'The active network (generate, list, info)', createdAt: 'ISO 8601 creation timestamp (generate, info)', diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index a03c76a4..2abdcccc 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -55,7 +55,7 @@ proofs. The CLI provides full shielded support: address is one of your wallets, it maps to that wallet's full sync; otherwise it errors and points you to --wallet --shielded. - On preview/preprod, shielded sync is off by default (no faucet there). + On preview, preprod and stagenet, shielded sync is off by default (no faucet there). Pass --force-shielded to midnight balance or midnight transfer to force the shielded sync on for those networks. @@ -147,6 +147,9 @@ starts with mn_addr_ or mn_shield-addr_, it's used as an address directly. 5. midnight_balance → Check balance 6. midnight_transfer → midnight_confirm_operation → transfer + Stagenet (Sig Network's testnet, on the beta SDK set): the same steps + with value "stagenet", funded at https://faucet.stagenet.shielded.tools/. + `, }, { diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index 3616f720..6068a067 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -10,6 +10,7 @@ import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-net import { parseSeedHex } from '../lib/seed-resolver.ts'; import { loadWalletConfig, + walletAddress, unlockWallet, protectAllWallets, setActiveWallet, @@ -237,7 +238,7 @@ async function walletInfo(args: ParsedArgs, ctx: CallContext): Promise { const config = await loadWalletConfig(walletPath); const isActive = name === getActiveWalletName(); const networkName = resolveNetworkName({ args }); - const activeAddress = config.addresses[networkName]; + const activeAddress = await walletAddress(walletPath, networkName); if (hasFlag(args, 'json')) { // Agent-slim shape: drops the per-network addresses map (3× repetition diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index f2ce4d39..a4ddc8bf 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -77,8 +77,10 @@ blockchain. It manages wallets, balances, transfers (unshielded and shielded), dust fees, a DApp connector server, contract inspection, E2E testing, and a local devnet — all from the terminal. -Wallets are network-agnostic: one seed derives addresses for all three -networks (undeployed, preprod, preview). Network is chosen at runtime. +Wallets are network-agnostic: one seed derives addresses for all four +networks (undeployed, preprod, preview, stagenet). Network is chosen at +runtime. Stagenet is Sig Network's chain on the beta SDK set; mn runs it +through its own engine, picked by the network. Preprod's indexer and node are served by Blockfrost (Midnight shut its own preprod indexer down on 2026-10-09). Every request needs the user's own diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index ce0e9477..6a7298f5 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -37,7 +37,8 @@ import { sealedPrivateStatePassword, } from './sealed-account.ts'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { isValidNetworkName, sdkSetOfNetwork, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** Where the account package caches its proving artefacts, under ~/.midnight: each file is fetched the first time a command proves with it. */ @@ -67,8 +68,11 @@ export function privateStateLocationOf(recordsDir: string, password: () => strin /** A network the account package can't reach yet. */ export class UnreachableByAccountError extends UsageError { - constructor(networkId: string) { - super(`mn grant runs on ledger 9, which only a local network (undeployed) runs so far; ${networkId} is not one.`); + constructor(networkId: string, sdkSet: SdkSet = 'rc') { + super(sdkSet === 'rc' + ? `mn grant runs on ledger 9, which only a local network (undeployed) runs so far; ${networkId} is not one.` + // The account package is built on the rc set: its contracts, proving files and providers. + : `mn grant runs on the rc SDK set, and ${networkId} runs on the ${sdkSet} set. The account package has no ${sdkSet} build yet (its contracts need recompiling and new proving files), so grant can't act on it for now.`); this.name = 'UnreachableByAccountError'; Object.setPrototypeOf(this, UnreachableByAccountError.prototype); } @@ -76,6 +80,9 @@ export class UnreachableByAccountError extends UsageError { /** Throws when the account package can't act on `networkConfig`'s network. */ export function assertAccountNetwork(networkConfig: NetworkConfig): void { + const id = networkConfig.networkId.toLowerCase(); + const sdkSet = isValidNetworkName(id) ? sdkSetOfNetwork(id) : 'rc'; + if (sdkSet !== 'rc') throw new UnreachableByAccountError(networkConfig.networkId, sdkSet); if (networkConfig.networkId.toLowerCase() !== ACCOUNT_NETWORK_ID) throw new UnreachableByAccountError(networkConfig.networkId); } diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 5d46e7c6..4504a1e5 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -5,6 +5,7 @@ // flag checks read it, and so do help, the manual and the intro, the MCP // server's tools, and the agent manual and skills. +import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { walletDefinition } from '../commands/wallet.definition.ts'; import { generateDefinition } from '../commands/generate.definition.ts'; @@ -54,7 +55,7 @@ const GLOBAL_FLAGS: readonly FlagDefinition[] = [ const GLOBAL_FLAGS_HELP: readonly GlobalFlagHelp[] = [ { name: '--json', description: 'Output structured JSON to stdout (suppresses all stderr)' }, { name: '--wallet ', description: 'Wallet name or path' }, - { name: '--network ', description: 'Override network (preprod, preview, undeployed)' }, + { name: '--network ', description: `Override network (${getValidNetworkNames().join(', ')})` }, { name: '--version, -v', description: 'Print CLI version' }, { name: '--help, -h', description: 'Show help' }, ]; diff --git a/src/lib/installed-engines.ts b/src/lib/installed-engines.ts index ff2ba28f..d3644d7b 100644 --- a/src/lib/installed-engines.ts +++ b/src/lib/installed-engines.ts @@ -9,5 +9,7 @@ export async function loadInstalledEngine(set: SdkSet): Promise { switch (set) { case 'rc': return (await import('@kuiralabs/midnight-engine-rc')).rcEngine; + case 'beta': + return (await import('@kuiralabs/midnight-engine-beta')).betaEngine; } } diff --git a/src/lib/mcp/server-advice.ts b/src/lib/mcp/server-advice.ts new file mode 100644 index 00000000..af4d1d34 --- /dev/null +++ b/src/lib/mcp/server-advice.ts @@ -0,0 +1,14 @@ +// What the MCP server tells a call it can't take because of the SDK set it +// runs: a server loads one set's engine, so a call on a network of the other +// set is told to use a server of its own. + +import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { networksOnSdkSet } from '@kuiralabs/midnight-cli-core/lib/network'; + +/** The server runs one SDK set: a call on the other set's network is told to use a server of its own. */ +export function withServerAdvice(error: Error): Error { + if (!(error instanceof OtherSdkSetError)) return error; + const networks = networksOnSdkSet(error.wantedSet).join(', '); + return new OtherSdkSetError(error.loadedSet, error.wantedSet, + `This MCP server runs the ${error.loadedSet} SDK set, and ${networks} run${networks.includes(',') ? '' : 's'} on the ${error.wantedSet} set: two sets' ledgers can't share a process. Start another MCP server for ${networks} and make the call there.`); +} diff --git a/src/lib/mcp/skills.ts b/src/lib/mcp/skills.ts index 358b80ac..e3b3e990 100644 --- a/src/lib/mcp/skills.ts +++ b/src/lib/mcp/skills.ts @@ -122,6 +122,7 @@ Act on the user's behalf on Midnight, through what the installed packages bring: - \`undeployed\` — local network. Use this for dev iteration. On this build it must be a ledger-9 stack the user runs (\`mn localnet up\` is refused, see the note at the top). - \`preprod\` — public testnet (ledger 8 today, so refused by this build). Its indexer and node are served by Blockfrost and need the user's own project id (see "Preprod needs a Blockfrost project id" below). First-time wallet sync processes the full event history and can take significantly longer than subsequent syncs (which restore from cached wallet state). Exact time depends on wallet age, event density, network, and hardware. - \`preview\` — public preview testnet (ledger 8 today, so refused by this build). Same first-sync trade-off as preprod. + - \`stagenet\` — Sig Network's testnet, on the beta SDK set (mn loads its beta engine for it). No shielded faucet, so shielded sync is off by default; NIGHT from https://faucet.stagenet.shielded.tools. Its proof server must match its node (\`midnightntwrk/proof-server:9.0.0-rc.5_experimental\`). Grant is refused there for now. - **Proof server** — local HTTP service that generates ZK proofs for transactions. Default port 6300. Version must match the network's ledger version or writes fail with "Custom error 170". `, diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 73ca7e13..66e6de52 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -4,7 +4,7 @@ // Always runs in approve-all mode. import { Socket } from 'node:net'; -import { loadWalletConfig, resolveWalletPath, unlockWallet } from './wallet-config.ts'; +import { resolveWalletPath, unlockWallet, walletAddress } from './wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -192,7 +192,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise is parametric, rest are fixed export type PrepStepId = diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 02bd984a..828f51ad 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -4,7 +4,7 @@ import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { loadWalletConfig, resolveWalletPath, type WalletConfig } from './wallet-config.ts'; +import { loadWalletConfig, resolveWalletPath, walletAddress, walletShieldedAddress, type WalletConfig } from './wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { engineFor, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; @@ -80,11 +80,11 @@ async function resolveRecipient(input: string, args: ParsedArgs, shielded: boole return input; } - const recipientConfig = await loadWalletConfig(resolveWalletPath(input)); + const recipientPath = resolveWalletPath(input); const networkName = resolveNetworkName({ args }); if (shielded) { - const shieldedAddr = recipientConfig.shieldedAddresses?.[networkName]; + const shieldedAddr = await walletShieldedAddress(recipientPath, networkName); if (!shieldedAddr) { throw new Error( `Wallet "${input}" has no shielded address for network "${networkName}".\n` + @@ -94,7 +94,7 @@ async function resolveRecipient(input: string, args: ParsedArgs, shielded: boole return shieldedAddr; } - const address = recipientConfig.addresses[networkName]; + const address = await walletAddress(recipientPath, networkName); if (!address) { throw new Error(`Wallet "${input}" has no address for network "${networkName}". Regenerate the wallet to derive one.`); } diff --git a/src/lib/wallet-config.ts b/src/lib/wallet-config.ts index 9f541147..d40f8cc7 100644 --- a/src/lib/wallet-config.ts +++ b/src/lib/wallet-config.ts @@ -2,7 +2,7 @@ import * as fs from 'fs'; import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; import * as path from 'path'; import { DEFAULT_WALLET_FILENAME, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, FILE_MODE, isValidWalletName } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { loadCliConfig, saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { getDefaultWalletPath, getWalletsDir } from './wallet-paths.ts'; import { anyEngine, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -76,6 +76,41 @@ export function getAddress(config: WalletConfig, network: NetworkName): string { return config.addresses[network]; } +/** + * A wallet's unshielded address on `network`. A sealed wallet written before + * that network existed has none saved yet: it is unlocked, which derives and + * saves it. + */ +export async function walletAddress(walletPath: string, network: NetworkName): Promise { + const config = await loadWalletConfig(walletPath); + return config.addresses[network] ?? (await unlockWallet(walletPath)).addresses[network]; +} + +/** A wallet's shielded address on `network`, unlocking a sealed wallet that has none saved yet (see walletAddress); undefined when the wallet keeps no shielded addresses. */ +export async function walletShieldedAddress(walletPath: string, network: NetworkName): Promise { + const config = await loadWalletConfig(walletPath); + if (config.shieldedAddresses === undefined || config.shieldedAddresses[network] !== undefined) return config.shieldedAddresses?.[network]; + return (await unlockWallet(walletPath)).shieldedAddresses?.[network]; +} + +/** The networks an address map has no address for: a wallet written before they existed. */ +function missingNetworks(map: Partial> | undefined): NetworkName[] { + return (getValidNetworkNames() as NetworkName[]).filter((network) => typeof map?.[network] !== 'string' || map[network] === ''); +} + +/** The wallet's address maps with every network's address, derived from its seed where missing; null when none was missing. */ +async function completedAddresses(config: WalletConfig, seed: Buffer): Promise | null> { + const lacksUnshielded = missingNetworks(config.addresses).length > 0; + const lacksShielded = config.shieldedAddresses !== undefined && missingNetworks(config.shieldedAddresses).length > 0; + if (!lacksUnshielded && !lacksShielded) return null; + const { keys } = await anyEngine(); + return { + // Saved addresses win: they are what the wallet has shown so far. + addresses: { ...keys.unshieldedAddresses(seed), ...config.addresses }, + ...(config.shieldedAddresses !== undefined ? { shieldedAddresses: { ...keys.shieldedAddresses(seed), ...config.shieldedAddresses } } : {}), + }; +} + /** * Determine if a --wallet value looks like a file path (contains / or .json) * versus a wallet name (simple string like "alice"). @@ -379,13 +414,22 @@ export async function loadWalletConfig(walletPath?: string): Promise, call: function errorResponse(thrown: Error) { // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. - const error = withNodeReason(thrown); + const error = withServerAdvice(withNodeReason(thrown)); const { errorCode } = classifyError(error); return { content: [{ diff --git a/tsconfig.json b/tsconfig.json index 417ff391..a7f80773 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts"], + "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts"], "exclude": ["node_modules"] } From edf8e74fc7ce9b1fd695e68f8b76653c17c8903c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 22:22:05 -0800 Subject: [PATCH 39/88] README: stagenet, on the beta SDK set --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 947010f0..deec0a64 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ A standalone CLI wallet for the Midnight blockchain. Manage wallets, check balan Built for two audiences: **beginners** starting their first Midnight project (a local chain + funded wallets + contract deploy in minutes), and **AI agents** (Cursor, Claude Code, any MCP client) using the same primitives via a built-in MCP server. > [!IMPORTANT] -> **0.6.0 (prerelease, `npm install -g midnight-wallet-cli@next`) is ledger-9 only.** It is built on wallet-sdk 2.0.0-rc.0, ledger-v9 1.0.0-rc.5, midnight-js 5.0.0-rc.1 and compact-runtime 0.20.0 (contracts compiled with Compact 0.35 / language 0.27). It refuses any chain still on ledger 8, which today includes `preview` and `preprod`: stay on 0.5.x (`npm install -g midnight-wallet-cli@latest`) for those. +> **0.6.0 (prerelease, `npm install -g midnight-wallet-cli@next`) is ledger-9 only.** It is built on wallet-sdk 2.0.0-rc.0, ledger-v9 1.0.0-rc.5, midnight-js 5.0.0-rc.1 and compact-runtime 0.20.0 (contracts compiled with Compact 0.35 / language 0.27). `stagenet` runs on the beta set instead (wallet-sdk 5.0 beta split packages, ledger-v9 1.0.0-rc.3, midnight-js 5.0.0-beta.6, compact-runtime 0.18.0-rc.1, contracts compiled with compactc 0.33), which mn loads for that network alone. It refuses any chain still on ledger 8, which today includes `preview` and `preprod`: stay on 0.5.x (`npm install -g midnight-wallet-cli@latest`) for those. > > `midnight localnet up` is refused on this build, because no published indexer image runs ledger 9 yet. Run a ledger-9 stack yourself (node 2.1.0-rc.2, proof-server 9.0.0-rc.8, a 4.4 indexer) and point mn at it. On the default ports (node 9944, indexer 8088, proof server 6300) `--network undeployed` reaches it with no configuration. On other ports pass `--node`, `--indexer-ws` and `--proof-server` per command, or save them once with `midnight config set node `, `midnight config set indexer-ws ` and `midnight config set proof-server `. @@ -108,8 +108,9 @@ midnight transfer mn_addr_preprod1... 100 | `undeployed` | Local network. On this build: a ledger-9 stack you run yourself (`midnight localnet up` is refused) | | `preprod` | Midnight pre-production testnet (ledger 8 today: refused by this build, use 0.5.x). Its indexer and node are served by Blockfrost: needs a project id | | `preview` | Midnight preview testnet (ledger 8 today: refused by this build, use 0.5.x) | +| `stagenet` | Sig Network's testnet, on the beta SDK set: mn runs it through its beta engine, picked by the network. NIGHT from https://faucet.stagenet.shielded.tools; no shielded faucet, so shielded sync is off by default. Its proof server must match its node (`midnightntwrk/proof-server:9.0.0-rc.5_experimental`). `mn grant` is refused there for now | -Wallets are network-agnostic — one seed derives addresses for all three networks. Use `--network ` on any command, or persist it with `midnight config set network preview`. +Wallets are network-agnostic — one seed derives addresses for all four networks. Use `--network ` on any command, or persist it with `midnight config set network preview`. ### Preprod and Blockfrost From 42007547936666e1fa7ee420fdeac6f917db9a90 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 23:14:56 -0800 Subject: [PATCH 40/88] The runner links a tree whole only when it holds every script package In the workspace the beta engine's own SDK copies sit under it while a package both engines share (ws) is hoisted to the root, so linking the engine's node_modules whole left ws out and a stagenet deploy failed with ERR_MODULE_NOT_FOUND. A tree or scope is now linked whole only when it holds all the script packages of its kind; otherwise the dApp gets a folder of its own with a link to each. Live on stagenet: deploy, call and state pass. --- .../contract-script-packages.test.ts | 35 ++++++++- src/lib/contract/runner.ts | 71 ++++++++++++++----- 2 files changed, 86 insertions(+), 20 deletions(-) diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index ec3db323..38229a9a 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -140,8 +140,10 @@ describe('a dApp laid out unlike ours', () => { expect(fs.readdirSync(dir)).toEqual([]); }); - it('links nothing inside a scope it linked whole, which would write into the engine\'s install', () => { - // A tree holding @x/a, and @x/b found elsewhere: the dApp has no @x, so @x is linked whole to the tree. + it('links a scope whole only when one folder holds all its packages, and then nothing inside it', () => { + // A tree holding @x/a, and @x/b found elsewhere (an install that hoisted it): + // linking @x whole to the tree would leave @x/b out, so @x is a folder of the + // dApp's own with a link to each, and the engine's install is left as it was. const tree = path.join(dir, 'tree', '@x'); fs.mkdirSync(path.join(tree, 'a'), { recursive: true }); const elsewhere = path.join(dir, 'elsewhere', '@x', 'b'); @@ -150,9 +152,36 @@ describe('a dApp laid out unlike ours', () => { fs.mkdirSync(dapp, { recursive: true }); const packages = { set: 'rc', packages: ['@x/a', '@x/b'], packageFolder: (name: string) => (name === '@x/a' ? path.join(tree, 'a') : elsewhere) }; const made = overlayScriptPackagesFor(dapp, packages); - expect(made.map((m) => path.relative(dir, m.path))).toEqual([path.join('dapp', 'node_modules', '@x')]); + expect(made.map((m) => [path.relative(dir, m.path), m.kind])).toEqual([ + [path.join('dapp', 'node_modules', '@x'), 'folder'], + [path.join('dapp', 'node_modules', '@x', 'a'), 'link'], + [path.join('dapp', 'node_modules', '@x', 'b'), 'link'], + ]); + expect(fs.realpathSync(path.join(dapp, '@x', 'b'))).toBe(fs.realpathSync(elsewhere)); expect(fs.readdirSync(tree)).toEqual(['a']); undoOverlay(made); + expect(fs.readdirSync(dapp)).toEqual([]); + }); + + it('gives a dApp with no node_modules a folder of links when the packages sit in more than one tree', () => { + // As in a workspace: the engine's own copies nested under it, a package it shares hoisted to the root. + const nested = path.join(dir, 'engine', 'node_modules'); + fs.mkdirSync(path.join(nested, '@x', 'a'), { recursive: true }); + const hoisted = path.join(dir, 'root', 'node_modules', 'ws'); + fs.mkdirSync(hoisted, { recursive: true }); + const dapp = path.join(dir, 'dapp', 'node_modules'); + fs.mkdirSync(path.dirname(dapp), { recursive: true }); + const packages = { set: 'beta', packages: ['@x/a', 'ws'], packageFolder: (name: string) => (name === 'ws' ? hoisted : path.join(nested, '@x', 'a')) }; + const made = overlayScriptPackagesFor(dapp, packages); + expect(made.map((m) => [path.relative(dir, m.path), m.kind])).toEqual([ + [path.join('dapp', 'node_modules'), 'folder'], + [path.join('dapp', 'node_modules', '@x'), 'link'], + [path.join('dapp', 'node_modules', 'ws'), 'link'], + ]); + expect(fs.realpathSync(path.join(dapp, 'ws'))).toBe(fs.realpathSync(hoisted)); + expect(fs.readdirSync(nested)).toEqual(['@x']); + undoOverlay(made); + expect(fs.readdirSync(path.dirname(dapp))).toEqual([]); }); it('refuses another SDK set\'s packages while a run uses its overlay, and replaces it once none does', () => { diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index a69dbcab..e932f0b9 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -289,17 +289,35 @@ type Made = { path: string; kind: 'link' | 'folder' }; /** The packages a script imports, where the engine's install has each, and the SDK set they are. */ type ScriptPackages = Pick & { readonly set: string }; -/** The installed copy of each scope the script packages use (`@midnight-ntwrk`, …), and the node_modules holding them. */ +/** + * The installed copy of each scope the script packages use (`@midnight-ntwrk`, + * …), and the node_modules holding them: each only when it holds every script + * package of its kind. An install can hoist some of an engine's packages away + * from the rest (a workspace puts a package both engines share at its root), + * and a tree linked whole must then not stand in for the packages it lacks. + */ function installedTrees({ packages, packageFolder }: ScriptPackages): { root: string | null; scopes: Map } { - const scopes = new Map(); - let root: string | null = null; + const folders = new Map(); for (const name of packages) { - if (!name.startsWith('@')) continue; const folder = packageFolder(name); - if (folder === null) continue; - const scope = name.slice(0, name.indexOf('/')); - if (!scopes.has(scope)) scopes.set(scope, dirname(folder)); - root ??= dirname(dirname(folder)); + if (folder !== null) folders.set(name, folder); + } + const scopeOf = (name: string): string => name.slice(0, name.indexOf('/')); + const holderOf = (name: string): string | undefined => { + const folder = folders.get(name); + if (folder === undefined) return undefined; + return name.startsWith('@') ? dirname(dirname(folder)) : dirname(folder); + }; + const holders = new Set(packages.map(holderOf)); + const root = holders.size === 1 ? [...holders][0] ?? null : null; + const scopes = new Map(); + for (const scope of new Set(packages.filter((name) => name.startsWith('@')).map(scopeOf))) { + const inScope = new Set(packages.filter((name) => name.startsWith(scope + '/')).map((name) => { + const folder = folders.get(name); + return folder === undefined ? undefined : dirname(folder); + })); + const only = inScope.size === 1 ? [...inScope][0] : undefined; + if (only !== undefined) scopes.set(scope, only); } return { root, scopes }; } @@ -308,8 +326,10 @@ function installedTrees({ packages, packageFolder }: ScriptPackages): { root: st * Make the script packages, and whatever else a dApp's witnesses import from * the same installed tree, resolvable from `userNodeModules`, finding the * engine's copy by name (never by walking up from this file): - * - a dApp with no node_modules gets a link to the node_modules holding them; - * - a dApp without one of their scopes gets a link to that whole scope; + * - a dApp with no node_modules gets a link to the node_modules holding them + * all, or else a folder of its own for the links below; + * - a dApp without one of their scopes gets a link to that whole scope, when + * one folder holds all of the scope's script packages; * - a package still missing (in a scope the dApp has, or unscoped) is linked * on its own. * Never replaces what the dApp has: the user may pin a version we shouldn't @@ -324,26 +344,43 @@ export function overlayScriptPackages(userNodeModules: string, scriptPackages: S made.push({ path: at, kind: 'link' }); } catch { /* left out: the script reports the missing package */ } }; + const folder = (at: string): boolean => { + if (existsSync(at)) return true; + try { + mkdirSync(at); + made.push({ path: at, kind: 'folder' }); + return true; + } catch { + return false; + } + }; const { root, scopes } = installedTrees(scriptPackages); if (!existsSync(userNodeModules)) { - if (root !== null) link(root, userNodeModules); - return made; + if (root !== null) { + link(root, userNodeModules); + return made; + } + if (!folder(userNodeModules)) return made; } // A scope linked whole is the engine's own folder: nothing is linked inside // it, which would write into the engine's install. const linkedWhole = new Set(); - for (const [scope, folder] of scopes) { + for (const [scope, scopeFolder] of scopes) { const at = join(userNodeModules, scope); if (!existsSync(at)) { - link(folder, at); + link(scopeFolder, at); linkedWhole.add(scope); } } for (const name of scriptPackages.packages) { - if (name.startsWith('@') && linkedWhole.has(name.slice(0, name.indexOf('/')))) continue; + const scope = name.startsWith('@') ? name.slice(0, name.indexOf('/')) : null; + if (scope !== null && linkedWhole.has(scope)) continue; const at = join(userNodeModules, name); - const target = existsSync(at) ? null : scriptPackages.packageFolder(name); - if (target !== null) link(target, at); + if (existsSync(at)) continue; + const target = scriptPackages.packageFolder(name); + if (target === null) continue; + if (scope !== null && !folder(join(userNodeModules, scope))) continue; + link(target, at); } return made; } From 3256cbb06883d052b37aa35ae27d27fd04cdeaa7 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Sun, 1 Nov 2026 23:43:41 -0800 Subject: [PATCH 41/88] The beta engine runs wallet-sdk-node-client 2.0.0-beta.4 2.0.0-beta.2, which the beta set's wallet-sdk-capabilities pins exactly, disconnects its shared node connection whenever any operation ends, so a submit still in flight was cut off ("disconnected ... 1000 Normal Closure"): every transfer and swap the connector built on stagenet failed. 2.0.0-beta.4 holds the connection until the last operation ends, as the rc set's client does. An override replaces beta.2 only, so the rc set is untouched; the release's shrinkwrap carries it to installs. Live on stagenet: the wallet session reads, signs, reverts an unsent swap on close and submits one. --- package-lock.json | 33 ++++++++++++++++++++++++++------- package.json | 3 +++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2a4fef89..b876e279 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6072,13 +6072,13 @@ } }, "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-node-client": { - "version": "2.0.0-beta.2", - "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-node-client/-/wallet-sdk-node-client-2.0.0-beta.2.tgz", - "integrity": "sha512-jW9Mu37a1B9kpUSVAg0PTu7agPza4ffUCLS8rCAWDbAfa65xoECFXUH2FzWR95uxVPes8XY7+onNeBQN7ffJ3w==", + "version": "2.0.0-beta.4", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-node-client/-/wallet-sdk-node-client-2.0.0-beta.4.tgz", + "integrity": "sha512-PNkeQvlmZwqipwc7mE9uymUjIyEScjQcUYfguB7zNQvOcbLPY4na08FmIMGWxPJDTBTiMNxLZokVgPHb1vC4Ow==", "license": "Apache-2.0", "dependencies": { - "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.0", - "@midnightntwrk/wallet-sdk-utilities": "1.2.0", + "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-beta.2", + "@midnightntwrk/wallet-sdk-utilities": "1.2.2-beta.0", "@polkadot/api": "^16.5.4", "@polkadot/types": "^16.5.4", "@polkadot/util": "^14.0.1", @@ -6087,8 +6087,8 @@ "effect": "^3.19.19" }, "peerDependencies": { - "@midnightntwrk/ledger-v9": "1.0.0-rc.3", - "@midnightntwrk/wallet-sdk-prover-client": "2.0.0-beta.2" + "@midnightntwrk/ledger-v9": "1.0.0-rc.5", + "@midnightntwrk/wallet-sdk-prover-client": "2.0.0-beta.4" }, "peerDependenciesMeta": { "@midnightntwrk/ledger-v9": { @@ -6099,6 +6099,25 @@ } } }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-node-client/node_modules/@midnightntwrk/wallet-sdk-abstractions": { + "version": "3.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-abstractions/-/wallet-sdk-abstractions-3.0.0-beta.2.tgz", + "integrity": "sha512-ygZ2FB3uE2j40ctWMAlsSRjfI5HcOItGqfnRtgYIyjY/y6F8W2bXIwOVmM1iCNqitDQ2MAx2MfRp1f1FDwmkhg==", + "license": "Apache-2.0", + "dependencies": { + "effect": "^3.19.19" + } + }, + "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-node-client/node_modules/@midnightntwrk/wallet-sdk-utilities": { + "version": "1.2.2-beta.0", + "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-utilities/-/wallet-sdk-utilities-1.2.2-beta.0.tgz", + "integrity": "sha512-oSL0JrzB6M9gon8wuKBYNtKhhoWAkFR+5BPHX0dgJExO8jwPutT/F1py1dO3nLWA+uskwyMQDKgkq0hHsIBQRg==", + "license": "Apache-2.0", + "dependencies": { + "effect": "^3.19.19", + "rxjs": "^7.8.2" + } + }, "packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-prover-client": { "version": "2.0.0-beta.2", "resolved": "https://registry.npmjs.org/@midnightntwrk/wallet-sdk-prover-client/-/wallet-sdk-prover-client-2.0.0-beta.2.tgz", diff --git a/package.json b/package.json index 99577f50..71e72c4c 100644 --- a/package.json +++ b/package.json @@ -78,5 +78,8 @@ "tsx": "^4.21.0", "typescript": "^5.9.3", "vitest": "^3.2.4" + }, + "overrides": { + "@midnightntwrk/wallet-sdk-node-client@2.0.0-beta.2": "2.0.0-beta.4" } } From f86148234e2031758248b3cbaee1064ae6ae59d6 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 01:21:29 -0800 Subject: [PATCH 42/88] Both engines in CI; the release ships a shrinkwrap of the tested tree (EH) - make-shrinkwrap.mjs writes the npm-shrinkwrap.json mn ships from package-lock.json: the entries mn's production dependencies reach, with the workspace packages as their published tarballs. A user's npm then installs the tree the tests ran on, each engine resolving its SDK set once. Resolving afresh instead let the beta set's loose ranges reach newer betas built on ledger rc.5. - The release job publishes core, chain and both engines (unless that version is out already), writes the shrinkwrap, then publishes mn. - fresh-install-check.mjs installs mn globally from a local registry that serves the packed tarballs as npm serves published ones (npm honours a shrinkwrap only then), and checks each engine resolves one copy of each WASM package, both engines load, and what it checked before. - Each engine refuses to load when its SDK packages reach more than one copy of a WASM package (MIXED_SDK_LAYOUT), as under bun's installer, which ignores the shrinkwrap; checked live under bun, where stagenet commands are refused saying to install with npm. - CI runs the suite once per engine (test:rc, test:beta); a test keeps each file to one engine, and the beta ones named for it. --- .github/workflows/ci.yml | 18 ++- .github/workflows/release-sidecar.yml | 23 +++ .gitignore | 3 + README.md | 2 + package.json | 5 +- .../cli-core/src/commands/core.guidance.ts | 2 + packages/cli-core/src/lib/exit-codes.ts | 5 + packages/cli-core/src/lib/sdk-layout.ts | 61 ++++++++ packages/engine-beta/src/index.ts | 11 ++ packages/engine-rc/src/index.ts | 11 ++ scripts/check-layering.mjs | 2 +- scripts/fresh-install-check.mjs | 117 +++++++++++---- scripts/local-registry.mjs | 117 +++++++++++++++ scripts/make-shrinkwrap.mjs | 136 ++++++++++++++++++ src/__tests__/exit-codes.test.ts | 7 + src/__tests__/sdk-layout.test.ts | 49 +++++++ src/__tests__/test-engines.test.ts | 26 ++++ 17 files changed, 561 insertions(+), 34 deletions(-) create mode 100644 packages/cli-core/src/lib/sdk-layout.ts create mode 100644 scripts/local-registry.mjs create mode 100644 scripts/make-shrinkwrap.mjs create mode 100644 src/__tests__/sdk-layout.test.ts create mode 100644 src/__tests__/test-engines.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9869ca14..145ecda1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,8 +37,13 @@ jobs: - name: Build run: npm run build - - name: Run tests - run: npm test + # Once per SDK engine: each test file loads one engine at most, and the + # beta engine's are named for it (src/__tests__/test-engines.test.ts). + - name: Tests — rc engine (and the SDK-free rest) + run: npm run test:rc + + - name: Tests — beta engine + run: npm run test:beta # ── Connector package ── @@ -79,10 +84,11 @@ jobs: - name: Check CLI package run: npm pack --dry-run - # The tests above run on the lockfile's dependency tree. A user's install - # has no lockfile: this installs the packed tarball as they would and - # checks the tree npm resolves today (one copy of each ledger package, a - # shielded address still parses). + # The tests above run on the lockfile's dependency tree. This packs mn + # with the shrinkwrap the release ships, installs it from a local + # registry as a user's npm would, and checks the tree it gets: one copy + # of each WASM package per SDK engine, both engines loading, a shielded + # address still parsing, the MCP server's files present. - name: Check a fresh install run: node scripts/fresh-install-check.mjs diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index 767f5682..1aa80978 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -158,6 +158,29 @@ jobs: echo "skipping $pkg — no binary" fi done + # mn depends on its workspace packages (core, chain, one engine per SDK + # set) at exact versions: each publishes first, unless that version is + # on npm already, under the same dist-tag as mn. + - run: npm run build + - name: Publish the workspace packages mn depends on + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + shell: bash + run: | + set -euo pipefail + for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta; do + name="$(node -p "require('./$dir/package.json').name")" + version="$(node -p "require('./$dir/package.json').version")" + if npm view "$name@$version" version >/dev/null 2>&1; then + echo "$name@$version is published already" + else + ( cd "$dir" && npm publish --access public ${{ env.PRERELEASE == 'true' && '--tag next' || '' }} ) + fi + done + # The tree the tests ran on, shipped with mn so a user's npm installs it + # (each engine's SDK set kept apart). Written only here, never committed. + - name: Write the shrinkwrap mn ships + run: node scripts/make-shrinkwrap.mjs - name: Publish main package env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore index 527de743..0025cc47 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,6 @@ tasks/ # Native sidecar binaries — built fresh by CI into the platform packages, never committed packages/dust-sync-*/dust-sync packages/dust-sync-*/dust-sync.exe + +# Written by the release job just before publishing (scripts/make-shrinkwrap.mjs), never kept. +/npm-shrinkwrap.json diff --git a/README.md b/README.md index deec0a64..021d2363 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ npm install -g midnight-wallet-cli@next # this ledger-9 prerelease This installs two commands: `midnight` (or `mn` for short) and `midnight-wallet-mcp`. +Install the prerelease with npm (or run it with `npx`). It ships an `npm-shrinkwrap.json` that keeps each SDK set's packages apart; bun's installer ignores it, and a command whose SDK set it then mixes up is refused, saying so (`MIXED_SDK_LAYOUT`; under bun today, every stagenet command). + ## Commands diff --git a/package.json b/package.json index 71e72c4c..60373294 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,8 @@ "dist", "docs/SKILL.md", "docs/SKILL-CORE.md", - "NOTICE" + "NOTICE", + "npm-shrinkwrap.json" ], "engines": { "node": ">=22", @@ -54,6 +55,8 @@ "link": "bun link", "prepublishOnly": "npm run build && npm run test", "test": "vitest run", + "test:rc": "vitest run --exclude 'src/__tests__/engine-beta*.test.ts'", + "test:beta": "vitest run src/__tests__/engine-beta", "test:live": "vitest run --config vitest.live.config.ts", "test:watch": "vitest", "typecheck": "tsc --noEmit", diff --git a/packages/cli-core/src/commands/core.guidance.ts b/packages/cli-core/src/commands/core.guidance.ts index cf74778a..80cab0e9 100644 --- a/packages/cli-core/src/commands/core.guidance.ts +++ b/packages/cli-core/src/commands/core.guidance.ts @@ -52,6 +52,8 @@ export const coreGuidance: PackageGuidance = { network runs on the other (an MCP server that served rc now asked for stagenet); start a server for that network + MIXED_SDK_LAYOUT 1 mn was installed without its shrinkwrap (bun's + installer): install it with npm CANCELLED 7 Operation cancelled (SIGINT) UNKNOWN 1 Unclassified error `, diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index 165dc58d..b8ad34e8 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -57,6 +57,8 @@ export const ERROR_CODES = { ENDPOINT_SHUT_DOWN: 'ENDPOINT_SHUT_DOWN', /** The process has loaded one SDK set's engine and the call's network runs on the other. Recovery: run the call in a process of its own (for MCP, a server for that network). */ OTHER_SDK_SET: 'OTHER_SDK_SET', + /** An engine's SDK packages reach more than one copy of its ledger: mn was installed without its shrinkwrap (bun's installer). Recovery: install mn with npm. */ + MIXED_SDK_LAYOUT: 'MIXED_SDK_LAYOUT', /** mn's passphrase was wrong, or a sealed secret was changed. Recovery: run it again with the passphrase mn was protected with. */ WRONG_PASSPHRASE: 'WRONG_PASSPHRASE', /** A secret was needed and no passphrase could be had. Recovery: set MN_PASSPHRASE, or run at a terminal. */ @@ -107,6 +109,9 @@ export function classifyError(err: Error): ClassifiedError { if (code === ERROR_CODES.UNSUPPORTED_NODE) { return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNSUPPORTED_NODE }; } + if (code === ERROR_CODES.MIXED_SDK_LAYOUT) { + return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.MIXED_SDK_LAYOUT }; + } if (code === ERROR_CODES.OTHER_SDK_SET) { return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.OTHER_SDK_SET }; } diff --git a/packages/cli-core/src/lib/sdk-layout.ts b/packages/cli-core/src/lib/sdk-layout.ts new file mode 100644 index 00000000..d7dfa543 --- /dev/null +++ b/packages/cli-core/src/lib/sdk-layout.ts @@ -0,0 +1,61 @@ +// Whether an engine's install holds its SDK set once. An engine's ledger is +// WASM: an object one copy made is refused by another ("expected instance of +// LedgerParameters"). npm installs mn with the shrinkwrap it ships, which keeps +// each engine's set apart; an installer that ignores it (bun's) can leave an +// engine's SDK packages reaching different copies of its ledger, and every +// call would then fail obscurely. An engine checks at load and refuses, +// saying how to install mn instead. + +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import { dirname, join } from 'node:path'; + +/** The folder of the package `name` that Node resolves from `from`, or null. */ +export function resolvedPackageFolder(from: string, name: string): string | null { + for (let at = from; ; at = dirname(at)) { + const manifest = join(at, 'node_modules', name, 'package.json'); + if (existsSync(manifest)) return realpathSync(dirname(manifest)); + if (dirname(at) === at) return null; + } +} + +/** An engine's SDK packages reach more than one copy of a WASM package. */ +export class MixedSdkLayoutError extends Error { + readonly code = 'MIXED_SDK_LAYOUT'; + constructor(engine: string, wasmPackage: string, copies: string[]) { + super( + `${engine}'s SDK packages reach ${copies.length} copies of ${wasmPackage} (${copies.join(', ')}), so its calls would fail. ` + + 'This happens when mn is installed without the shrinkwrap it ships (bun\'s installer ignores it). ' + + 'Install mn with npm: npm install -g midnight-wallet-cli', + ); + this.name = 'MixedSdkLayoutError'; + } +} + +/** + * Throws MixedSdkLayoutError unless every package in `packages`, resolved from + * `engineDir`, reaches the same copy of each of `wasmPackages` the engine + * itself does. + */ +export function assertOneSdkCopy(engine: string, engineDir: string, packages: readonly string[], wasmPackages: readonly string[]): void { + const holders = [engineDir, ...packages.map((name) => resolvedPackageFolder(engineDir, name)).filter((dir): dir is string => dir !== null)]; + for (const wasm of wasmPackages) { + const copies = new Set(); + for (const holder of holders) { + // A package that doesn't use this WASM package reaches none, which is no copy. + const declares = holder === engineDir || dependsOn(holder, wasm); + if (!declares) continue; + const copy = resolvedPackageFolder(holder, wasm); + if (copy !== null) copies.add(copy); + } + if (copies.size > 1) throw new MixedSdkLayoutError(engine, wasm, [...copies]); + } +} + +function dependsOn(packageDir: string, name: string): boolean { + try { + const manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf-8')) as { dependencies?: Record; peerDependencies?: Record }; + return manifest.dependencies?.[name] !== undefined || manifest.peerDependencies?.[name] !== undefined; + } catch { + return false; + } +} diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts index 106df18e..0dd7fc12 100644 --- a/packages/engine-beta/src/index.ts +++ b/packages/engine-beta/src/index.ts @@ -2,7 +2,11 @@ // 5.0 beta split packages, ledger 9 rc.3 and midnight-js 5 beta, as mn pins // them. +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; import * as ledger from '@midnightntwrk/ledger-v9'; import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; @@ -16,6 +20,13 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; +// The engine's folder (above src/ or dist/), and the SDK packages it declares: +// each must reach the engine's own copy of every WASM package. +const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); +const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) + .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name)); +assertOneSdkCopy("mn's beta engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); + export const betaEngine: Engine = { set: 'beta', keys: { diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index f047ecc7..3317e855 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -1,7 +1,11 @@ // The engine for the SDK's release candidates (rc): the wallet SDK 2.0 // release candidates, ledger 9 and midnight-js 5 as mn pins them. +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; import * as ledger from '@midnightntwrk/ledger-v9'; import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; @@ -15,6 +19,13 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; +// The engine's folder (above src/ or dist/), and the SDK packages it declares: +// each must reach the engine's own copy of every WASM package. +const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); +const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) + .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name)); +assertOneSdkCopy("mn's rc engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); + export const rcEngine: Engine = { set: 'rc', keys: { diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 8113888c..09115e9d 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -42,7 +42,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 0bc7493f..8743ade1 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -1,6 +1,9 @@ -// What a user gets from npm, checked: packs this package, installs the tarball -// into an empty directory (no lockfile there, as for any consumer), and checks -// that the dependency tree npm resolves today still works. +// What a user gets from npm, checked: packs mn and the workspace packages it +// depends on, serves them from a local registry as npm serves published +// packages, installs mn globally from it into an empty prefix, and checks the +// tree the install holds still works: one copy of each WASM package per SDK +// engine (the shrinkwrap mn ships keeps each engine's set apart), each engine +// loading, and the files the code reads at run time. // // The test suite runs on the lockfile's tree, which a consumer never sees. Two // features broke that way without a test noticing: a newer @scure/base refused @@ -13,9 +16,11 @@ // node scripts/fresh-install-check.mjs (after `npm run build`) import { execFileSync, spawn } from 'node:child_process'; -import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; +import { startLocalRegistryProcess } from './local-registry.mjs'; +import { makeShrinkwrap, registryDist } from './make-shrinkwrap.mjs'; const repo = new URL('..', import.meta.url).pathname; const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); @@ -38,6 +43,37 @@ function copiesOf(root, name) { return found; } +/** + * Every copy of `name` that the package in `dir` reaches through its + * dependencies, by Node's resolution from each package's folder: the copies a + * process that loads it can load. + */ +function resolvedCopies(dir, name) { + const found = new Map(); + const seen = new Set(); + const resolveFrom = (from, dep) => { + for (let at = from; ; at = dirname(at)) { + const manifest = join(at, 'node_modules', dep, 'package.json'); + if (existsSync(manifest)) return realpathSync(dirname(manifest)); + if (dirname(at) === at) return null; + } + }; + // By the name code imports it under: an npm alias of the same package under another name is another package to its importers. + const walk = (pkgDir) => { + if (seen.has(pkgDir)) return; + seen.add(pkgDir); + const manifest = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf-8')); + for (const dep of Object.keys({ ...manifest.dependencies, ...manifest.peerDependencies })) { + const resolved = resolveFrom(pkgDir, dep); + if (resolved === null) continue; + if (dep === name) found.set(resolved, JSON.parse(readFileSync(join(resolved, 'package.json'), 'utf-8')).version); + walk(resolved); + } + }; + walk(realpathSync(dir)); + return [...found].map(([at, version]) => ({ dir: at, version })); +} + /** * What the MCP server at `server` offers, asked over stdio as an MCP client * would: the names of its tools, and every resource it lists with its text @@ -90,33 +126,50 @@ const check = (what, ok, detail = '') => { }; const work = mkdtempSync(join(tmpdir(), 'mn-fresh-install-')); +const shrinkwrapPath = join(repo, 'npm-shrinkwrap.json'); +let registry; try { - const tarball = run('npm', ['pack', '--pack-destination', work], repo).trim().split('\n').pop(); - // The workspace packages mn depends on, packed from this checkout too (until - // they are published, a consumer's npm finds them nowhere else), and - // installed beside it so they satisfy its dependencies. + // The workspace packages mn depends on, packed from this checkout (until they + // are published, a consumer's npm finds them nowhere else), served with mn by + // a local registry, as npm installs a published package: npm honours mn's + // shrinkwrap only when its registry says the package has one. + const tarballs = join(work, 'registry'); + mkdirSync(tarballs); const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); - const workspaceTarballs = manifest.workspaces + const workspaces = manifest.workspaces .map((dir) => ({ dir, name: JSON.parse(readFileSync(join(repo, dir, 'package.json'), 'utf-8')).name })) - .filter(({ name }) => manifest.dependencies[name] !== undefined) - .map(({ dir }) => run('npm', ['pack', '--pack-destination', work], join(repo, dir)).trim().split('\n').pop()); - writeFileSync(join(work, 'package.json'), JSON.stringify({ name: 'fresh-install-check', private: true })); - run('npm', ['install', '--no-audit', '--no-fund', ...workspaceTarballs.map((t) => join(work, t)), join(work, tarball)], work); + .filter(({ name }) => manifest.dependencies[name] !== undefined); + for (const { dir } of workspaces) run('npm', ['pack', '--pack-destination', tarballs], join(repo, dir)); + registry = await startLocalRegistryProcess(tarballs); + + // mn, packed with the shrinkwrap the release job writes. + makeShrinkwrap({ dist: registryDist(registry.url), out: shrinkwrapPath }); + try { + run('npm', ['pack', '--pack-destination', tarballs], repo); + } finally { + rmSync(shrinkwrapPath, { force: true }); + } - const version = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')).version; - const mn = join(work, 'node_modules', '.bin', 'mn'); + const version = manifest.version; + const prefix = join(work, 'prefix'); + run('npm', ['install', '-g', '--prefix', prefix, '--cache', join(work, 'npm-cache'), '--registry', registry.url, '--no-audit', '--no-fund', `${manifest.name}@${version}`], work); + const installed = join(prefix, 'lib', 'node_modules', manifest.name); + const mn = join(prefix, 'bin', 'mn'); check('the installed mn runs', run(mn, ['--version'], work).trim() === version, version); + check('the package shipped its shrinkwrap', existsSync(join(installed, 'npm-shrinkwrap.json'))); // One copy of each workspace package: a second copy of core's module state (its settings, its typed errors) splits the process. - for (const tarball of workspaceTarballs) { - const name = JSON.parse(run('tar', ['-xOzf', join(work, tarball), 'package/package.json'], work)).name; - const copies = copiesOf(work, name); + for (const { name } of workspaces) { + const copies = copiesOf(installed, name); check(`one copy of ${name}`, copies.length === 1, copies.join(', ')); } - // One copy each: an object made by one copy of a WASM package is refused by another. - for (const name of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/ledger-v8', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { - const copies = copiesOf(work, name); - check(`one copy of ${name}`, copies.length === 1, copies.join(', ')); + // Each engine resolves one copy of each WASM package: an object made by one copy is refused by another. + for (const { name } of workspaces.filter(({ name }) => name.startsWith('@kuiralabs/midnight-engine-'))) { + const engine = join(installed, 'node_modules', name); + for (const sdk of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { + const copies = resolvedCopies(engine, sdk); + check(`${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(installed.length)}`).join(', ')); + } } // A shielded address is longer than bech32's 90 characters; the address @@ -137,9 +190,20 @@ try { } catch (error) { console.log(error.message); } - `], join(work, 'node_modules', 'midnight-wallet-cli')); + `], join(installed, 'node_modules', '@kuiralabs', 'midnight-engine-rc')); check('a shielded address parses', parsed.trim() === 'parsed' && address.length > 90, `${address.length} characters${parsed.trim() === 'parsed' ? '' : `, ${parsed.trim()}`}`); + // Each engine loads from the install: deriving a network's address loads the engine of its set. + for (const [network, prefixOf] of [['undeployed', 'mn_addr_undeployed1'], ['stagenet', 'mn_addr_stagenet1']]) { + let derived = ''; + try { + derived = JSON.parse(execFileSync(mn, ['address', '--wallet', 'check', '--network', network, '--json'], { cwd: work, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], env })).address ?? ''; + } catch (error) { + derived = String(error.stderr ?? error.message).trim().split('\n').pop(); + } + check(`the ${network === 'stagenet' ? 'beta' : 'rc'} engine derives a ${network} address`, derived.startsWith(prefixOf), derived.slice(0, 40)); + } + // mn grant drives the account package it installed: its owner records load // from the installed tree and answer that the new wallet has no account. // Asking that reaches no chain and opens no proving-artefact cache (the @@ -155,11 +219,11 @@ try { } check('mn grant drives the installed account package', /Wallet "check" has no account on undeployed yet/.test(grant), grant.includes('has no account') ? 'no account yet, as for a new wallet' : grant.trim().split('\n').slice(-2).join(' | ')); check('it opens no proving-artefact cache', !existsSync(join(home, '.midnight', 'account-artifacts')), 'none under ~/.midnight'); - const chains = copiesOf(work, '@kuiralabs/midnight-account-chain'); + const chains = copiesOf(installed, '@kuiralabs/midnight-account-chain'); check('one copy of @kuiralabs/midnight-account-chain', chains.length === 1, chains.join(', ')); // The MCP server reads its skill documents from the installed package. - const { tools, resources } = await askMcpServer(join(work, 'node_modules', '.bin', 'midnight-wallet-mcp'), env); + const { tools, resources } = await askMcpServer(join(prefix, 'bin', 'midnight-wallet-mcp'), env); check('the MCP server lists its skill resources', resources.length >= 2, `${resources.length}`); for (const { uri, text, error } of resources) { check(`the MCP server serves ${uri}`, error === undefined && text.length > 0, error ? error.replace(work, '') : `${text.length} characters`); @@ -171,6 +235,7 @@ try { } catch (error) { check('the fresh install and its checks ran', false, String(error.stderr || error.message).trim().split('\n').slice(-3).join(' | ')); } finally { + await registry?.close(); rmSync(work, { recursive: true, force: true }); } diff --git a/scripts/local-registry.mjs b/scripts/local-registry.mjs new file mode 100644 index 00000000..e2c6034c --- /dev/null +++ b/scripts/local-registry.mjs @@ -0,0 +1,117 @@ +// A read-only npm registry on 127.0.0.1 serving packed tarballs as published +// versions, for installing mn the way users do before its packages are on npm. +// +// Each *.tgz in the folder is served as a version of the package it holds, +// with the fields the public registry adds at publish time: dist.tarball, +// dist.integrity, dist.shasum and _hasShrinkwrap (true when the tarball holds +// npm-shrinkwrap.json: npm honours a dependency's shrinkwrap only when its +// registry says so, so a tarball installed by path ignores it). Every other +// package passes through from registry.npmjs.org unchanged. +// +// node scripts/local-registry.mjs + +import http from 'node:http'; +import { createHash } from 'node:crypto'; +import { execFileSync, spawn } from 'node:child_process'; +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const UPSTREAM = 'https://registry.npmjs.org'; + +/** The packages the tarballs in `dir` hold, as packuments, and the file behind each tarball URL. */ +function packumentsIn(dir, base) { + const packuments = new Map(); + const files = new Map(); + for (const name of readdirSync(dir).filter((f) => f.endsWith('.tgz'))) { + const file = join(dir, name); + const listing = execFileSync('tar', ['-tzf', file], { encoding: 'utf8' }).split('\n'); + const manifest = JSON.parse(execFileSync('tar', ['-xzOf', file, 'package/package.json'], { encoding: 'utf8' })); + const bytes = readFileSync(file); + const packument = packuments.get(manifest.name) ?? { name: manifest.name, 'dist-tags': {}, versions: {} }; + packument.versions[manifest.version] = { + ...manifest, + _id: `${manifest.name}@${manifest.version}`, + _hasShrinkwrap: listing.includes('package/npm-shrinkwrap.json'), + dist: { + tarball: `${base}/-/local/${encodeURIComponent(name)}`, + integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`, + shasum: createHash('sha1').update(bytes).digest('hex'), + }, + }; + packument['dist-tags'].latest = manifest.version; + packuments.set(manifest.name, packument); + files.set(name, file); + } + return { packuments, files }; +} + +/** Serves the tarballs in `dir` on `port` (0: any free one); resolves to its URL and a close function. Rereads the folder when the tarballs in it change. */ +export function startLocalRegistry(dir, port = 0) { + return new Promise((resolve, reject) => { + let base = ''; + let scanned = { key: '', packuments: new Map(), files: new Map() }; + const current = () => { + const key = readdirSync(dir).filter((f) => f.endsWith('.tgz')).map((f) => `${f}:${statSync(join(dir, f)).mtimeMs}`).join('|'); + if (key !== scanned.key) scanned = { key, ...packumentsIn(dir, base) }; + return scanned; + }; + const server = http.createServer(async (req, res) => { + const { packuments, files } = current(); + const url = decodeURIComponent((req.url ?? '/').split('?')[0]); + if (url.startsWith('/-/local/')) { + const file = files.get(url.slice('/-/local/'.length)); + if (file === undefined) { res.writeHead(404); res.end(); return; } + res.writeHead(200, { 'content-type': 'application/octet-stream' }); + res.end(readFileSync(file)); + return; + } + const packument = packuments.get(url.slice(1)); + if (packument !== undefined) { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify(packument)); + return; + } + try { + const upstream = await fetch(UPSTREAM + req.url, { headers: { accept: req.headers.accept ?? 'application/json' } }); + res.writeHead(upstream.status, { 'content-type': upstream.headers.get('content-type') ?? 'application/json' }); + res.end(Buffer.from(await upstream.arrayBuffer())); + } catch (error) { + res.writeHead(502); + res.end(String(error)); + } + }); + server.on('error', reject); + server.listen(port, '127.0.0.1', () => { + base = `http://127.0.0.1:${server.address().port}`; + resolve({ url: base, close: () => new Promise((done) => server.close(() => done())) }); + }); + }); +} + +/** + * The same registry in a process of its own, for a caller that runs npm + * synchronously (and so can't answer npm's requests itself); resolves to its + * URL and a close function. + */ +export function startLocalRegistryProcess(dir) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [fileURLToPath(import.meta.url), dir, '0'], { stdio: ['ignore', 'pipe', 'inherit'] }); + child.on('error', reject); + child.on('exit', (code) => reject(new Error(`the local registry exited (${code}) before it was ready`))); + child.stdout.on('data', (chunk) => { + const ready = /registry on (http:\/\/\S+),/.exec(chunk.toString()); + if (ready) resolve({ url: ready[1], close: async () => { child.kill(); } }); + }); + }); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const [dir, port] = process.argv.slice(2); + if (!dir || !port) { + console.error('usage: node scripts/local-registry.mjs '); + process.exit(2); + } + const { url } = await startLocalRegistry(dir, Number(port)); + console.log(`registry on ${url}, serving ${dir}`); +} diff --git a/scripts/make-shrinkwrap.mjs b/scripts/make-shrinkwrap.mjs new file mode 100644 index 00000000..1bef0c49 --- /dev/null +++ b/scripts/make-shrinkwrap.mjs @@ -0,0 +1,136 @@ +// The npm-shrinkwrap.json mn ships: the tree package-lock.json resolves for +// mn's own dependencies, the one the tests ran on, as an install of the +// published package lays it out. Each SDK engine there resolves its own SDK +// set once (the rc set at the top, the beta set nested under its engine). +// Left to resolve on its own, an install mixes the sets: the beta set's loose +// ranges reach newer betas built on the rc ledger, and an engine's ledger then +// refuses the objects another copy made. +// +// From the lockfile: every entry mn's production dependencies reach, by +// Node's resolution over the lockfile's paths. The workspace packages mn +// depends on are links there (node_modules/ -> packages/); in the +// shrinkwrap each is the published package, with its own nested entries moved +// under it, and its tarball and integrity from `dist`. +// +// The release job writes it beside package.json just before publishing (npm +// packs npm-shrinkwrap.json with the package); the workspace never keeps one, +// since npm ci would then install from it instead of package-lock.json. +// +// node scripts/make-shrinkwrap.mjs [--registry ] [--out ] + +import { execFileSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const repo = fileURLToPath(new URL('..', import.meta.url)); + +/** A published package's tarball and integrity, as `registry` serves them. */ +export function registryDist(registry) { + return (name, version) => { + const dist = JSON.parse(execFileSync('npm', ['view', `${name}@${version}`, 'dist', '--json', '--registry', registry], { encoding: 'utf-8' })); + return { resolved: dist.tarball, integrity: dist.integrity }; + }; +} + +/** The lockfile path a package named `name` resolves to from the package at `from`, or undefined. */ +function resolveIn(packages, from, name) { + for (let dir = from; ; dir = dir === '' ? null : parentOf(dir)) { + if (dir === null) return undefined; + const path = dir === '' ? `node_modules/${name}` : `${dir}/node_modules/${name}`; + if (packages[path] !== undefined) return path; + } +} + +/** The folder whose node_modules a package at `path` resolves from next: the package holding it, or the root. */ +function parentOf(path) { + const at = path.lastIndexOf('/node_modules/'); + if (at !== -1) return path.slice(0, at); + return path.startsWith('node_modules/') || path.startsWith('packages/') ? '' : null; +} + +/** + * mn's shrinkwrap from `lock` (package-lock.json) and `manifest` + * (package.json); `dist(name, version)` gives a workspace package's published + * tarball and integrity. + */ +export function shrinkwrapFrom(lock, manifest, dist) { + const packages = lock.packages; + // The workspace packages, by their folder: what mn's links point at. + const workspaces = new Map( + Object.entries(packages) + .filter(([path, entry]) => path.startsWith('node_modules/') && entry.link === true) + .map(([path, entry]) => [entry.resolved, path.slice('node_modules/'.length)]), + ); + // Where each lockfile path lands in an install of mn. + const placed = (path) => { + for (const [dir, name] of workspaces) { + if (path === dir) return `node_modules/${name}`; + if (path.startsWith(dir + '/node_modules/')) return `node_modules/${name}${path.slice(dir.length)}`; + } + return path; + }; + + const reached = new Set(); + const visit = (from, deps) => { + for (const [name, optional] of deps) { + let path = resolveIn(packages, from, name); + if (path === undefined) { + if (optional) continue; + throw new Error(`package-lock.json resolves no ${name} for ${from || 'mn'}`); + } + if (packages[path].link === true) path = packages[path].resolved; + if (reached.has(path)) continue; + reached.add(path); + visit(path, depsOf(packages[path])); + } + }; + const depsOf = (entry) => [ + ...Object.keys(entry.dependencies ?? {}).map((name) => [name, false]), + ...Object.keys(entry.optionalDependencies ?? {}).map((name) => [name, true]), + ...Object.keys(entry.peerDependencies ?? {}).map((name) => [name, entry.peerDependenciesMeta?.[name]?.optional === true]), + ]; + visit('', depsOf(manifest)); + + const { name, version, license, bin, engines, dependencies, optionalDependencies } = manifest; + const out = { '': { name, version, license, dependencies, optionalDependencies, bin, engines } }; + for (const path of [...reached].sort()) { + const entry = { ...packages[path] }; + delete entry.dev; + delete entry.devOptional; + if (workspaces.has(path)) { + Object.assign(entry, dist(workspaces.get(path), entry.version)); + delete entry.name; + } + out[placed(path)] = entry; + } + return { name, version, lockfileVersion: 3, requires: true, packages: out }; +} + +/** Writes mn's shrinkwrap to `out`; returns its packages. */ +export function makeShrinkwrap({ dist = registryDist('https://registry.npmjs.org'), out = join(repo, 'npm-shrinkwrap.json') } = {}) { + const lock = JSON.parse(readFileSync(join(repo, 'package-lock.json'), 'utf-8')); + const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); + const shrinkwrap = shrinkwrapFrom(lock, manifest, dist); + writeFileSync(out, JSON.stringify(shrinkwrap, null, 2) + '\n'); + return shrinkwrap.packages; +} + +/** The copies of `name` an install of the shrinkwrap holds, by path, with their versions. */ +export function copiesInShrinkwrap(packages, name) { + return Object.entries(packages) + .filter(([path]) => path === `node_modules/${name}` || path.endsWith(`/node_modules/${name}`)) + .map(([path, entry]) => ({ path, version: entry.version })); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const flag = (name) => { + const at = process.argv.indexOf(name); + return at === -1 ? undefined : process.argv[at + 1]; + }; + const out = flag('--out') ?? join(repo, 'npm-shrinkwrap.json'); + const packages = makeShrinkwrap({ dist: registryDist(flag('--registry') ?? 'https://registry.npmjs.org'), out }); + for (const copy of copiesInShrinkwrap(packages, '@midnightntwrk/ledger-v9')) console.log(`ledger-v9 ${copy.version} ${copy.path}`); + console.log(`wrote ${out}`); +} + diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 6226116e..ceae91cb 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -4,6 +4,8 @@ import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/gra import { NoAccountError } from '../lib/grant/prepare.ts'; import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { NoPassphraseError } from '../lib/passphrase.ts'; +import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { MixedSdkLayoutError } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; describe('humanizeNetworkError', () => { it('rewrites the empty-reason node-fetch tail with URL + cause hint', () => { @@ -84,6 +86,11 @@ describe('classifyError: mn grant', () => { expect(classifyError(new UnreachableByAccountError('PreProd'))).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); }); + it('names a call on the other SDK set\'s network, and an install that mixes an engine\'s SDK copies', () => { + expect(classifyError(new OtherSdkSetError('rc', 'beta'))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.OTHER_SDK_SET }); + expect(classifyError(new MixedSdkLayoutError("mn's beta engine", '@midnightntwrk/ledger-v9', ['/a', '/b']))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.MIXED_SDK_LAYOUT }); + }); + it('says a Node.js too old for the account package is an unsupported Node.js', () => { expect(classifyError(new NodeTooOldForAccountError('22.10.0'))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNSUPPORTED_NODE }); }); diff --git a/src/__tests__/sdk-layout.test.ts b/src/__tests__/sdk-layout.test.ts new file mode 100644 index 00000000..d58b6d32 --- /dev/null +++ b/src/__tests__/sdk-layout.test.ts @@ -0,0 +1,49 @@ +// An engine refuses to load when its SDK packages reach more than one copy of +// a WASM package, as an install that ignores mn's shrinkwrap can leave them. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { MixedSdkLayoutError, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; + +let dir: string; +beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-sdk-layout-')); }); +afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + +/** A package at `at` with `dependencies`. */ +function pkg(at: string, name: string, dependencies: Record = {}): string { + fs.mkdirSync(at, { recursive: true }); + fs.writeFileSync(path.join(at, 'package.json'), JSON.stringify({ name, version: '1.0.0', dependencies })); + return at; +} + +describe('an engine\'s SDK layout', () => { + it('passes when every SDK package reaches the engine\'s own ledger', () => { + const engine = pkg(path.join(dir, 'node_modules', 'engine'), 'engine', { ledger: '1', facade: '1' }); + pkg(path.join(engine, 'node_modules', 'ledger'), 'ledger'); + pkg(path.join(engine, 'node_modules', 'facade'), 'facade', { ledger: '1' }); + expect(() => assertOneSdkCopy('the test engine', engine, ['facade'], ['ledger'])).not.toThrow(); + }); + + it('refuses, saying how to install mn, when a package reaches a ledger of its own', () => { + const engine = pkg(path.join(dir, 'node_modules', 'engine'), 'engine', { ledger: '1', facade: '1' }); + pkg(path.join(engine, 'node_modules', 'ledger'), 'ledger'); + // As a hoisting installer leaves it: the facade at the top, with another ledger beside it. + pkg(path.join(dir, 'node_modules', 'facade'), 'facade', { ledger: '2' }); + pkg(path.join(dir, 'node_modules', 'facade', 'node_modules', 'ledger'), 'ledger'); + fs.rmSync(path.join(engine, 'node_modules', 'facade'), { recursive: true, force: true }); + const refusal = (() => { try { assertOneSdkCopy('the test engine', engine, ['facade'], ['ledger']); } catch (error) { return error; } })(); + expect(refusal).toBeInstanceOf(MixedSdkLayoutError); + expect((refusal as Error).message).toContain('the test engine\'s SDK packages reach 2 copies of ledger'); + expect((refusal as Error).message).toContain('Install mn with npm: npm install -g midnight-wallet-cli'); + }); + + it('counts no copy for a package that doesn\'t use the WASM package', () => { + const engine = pkg(path.join(dir, 'node_modules', 'engine'), 'engine', { ledger: '1', utils: '1' }); + pkg(path.join(engine, 'node_modules', 'ledger'), 'ledger'); + pkg(path.join(dir, 'node_modules', 'utils'), 'utils'); + pkg(path.join(dir, 'node_modules', 'ledger'), 'ledger'); + expect(() => assertOneSdkCopy('the test engine', engine, ['utils'], ['ledger'])).not.toThrow(); + }); +}); diff --git a/src/__tests__/test-engines.test.ts b/src/__tests__/test-engines.test.ts new file mode 100644 index 00000000..371dc178 --- /dev/null +++ b/src/__tests__/test-engines.test.ts @@ -0,0 +1,26 @@ +// Each test file loads one SDK engine at most, as mn's processes do, and the +// files that load the beta engine are named for it (engine-beta*.test.ts), so +// CI runs the suite once per engine: `npm run test:rc` and `npm run test:beta`. + +import { describe, expect, it } from 'vitest'; +import { readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; + +const TESTS = new URL('.', import.meta.url).pathname; +const files = [ + ...readdirSync(TESTS).filter((f) => f.endsWith('.ts')).map((f) => join(TESTS, f)), + ...readdirSync(join(TESTS, 'helpers')).filter((f) => f.endsWith('.ts')).map((f) => join(TESTS, 'helpers', f)), +]; +const loads = (file: string, engine: 'rc' | 'beta') => readFileSync(file, 'utf-8').includes(`@kuiralabs/midnight-engine-${engine}`); + +describe('the tests, per SDK engine', () => { + it('load one engine per file', () => { + expect(files.filter((f) => loads(f, 'rc') && loads(f, 'beta')).map((f) => f.slice(TESTS.length))).toEqual([]); + }); + + it('load the beta engine only from files named for it', () => { + const beta = files.filter((f) => loads(f, 'beta') && f !== new URL(import.meta.url).pathname).map((f) => f.slice(TESTS.length)); + expect(beta.length).toBeGreaterThan(0); + for (const file of beta) expect(file).toMatch(/^engine-beta[\w-]*\.test\.ts$/); + }); +}); From 7ff233a412592af6fae7e5d2e42754276c73b575 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 11:02:45 -0800 Subject: [PATCH 43/88] The connector's tests run on both engines The DApp connector's 144 tests ran only against the rc engine's copy of the connector, though the beta engine carries its own. They now live in one suite (helpers/connector-suite.ts) that each engine's test file runs with its own pieces: dapp-connector.test.ts for rc and engine-beta-dapp-connector.test.ts for beta, which takes its SDK modules from the copies the beta engine resolves. Where the engines differ, the suite says which: the rc SDK reads a dApp's transaction through the facade and waits for the ledger-9 fork; the beta engine reads it with its own ledger, waits only for the first state and passes the wallet's secret keys to the facade. The stub's finalized transactions are now real sealed transactions built with the engine's ledger, since the beta engine reads what it submits. ledger-tx.ts and connector-stub.ts build over a given engine's pieces, so neither loads an engine itself. --- src/__tests__/dapp-connector.test.ts | 1890 +--------------- .../engine-beta-dapp-connector.test.ts | 43 + src/__tests__/helpers/connector-stub.ts | 198 +- src/__tests__/helpers/connector-suite.ts | 1938 +++++++++++++++++ src/__tests__/helpers/ledger-tx.ts | 113 +- src/__tests__/wallet-session.test.ts | 11 +- 6 files changed, 2191 insertions(+), 2002 deletions(-) create mode 100644 src/__tests__/engine-beta-dapp-connector.test.ts create mode 100644 src/__tests__/helpers/connector-suite.ts diff --git a/src/__tests__/dapp-connector.test.ts b/src/__tests__/dapp-connector.test.ts index 1718b45a..7d252a76 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/src/__tests__/dapp-connector.test.ts @@ -1,1869 +1,33 @@ -// Tests for dapp-connector.ts — createDAppConnector handler map -// Stubs the FacadeBundle at the SDK boundary (per CLAUDE.md: no mocks of our own code). -// SDK address encoding is stubbed at the boundary; transactions reach the code -// as opaque handles the stub facade adopts, and leave as their real hex. +// The DApp connector's tests over the rc engine (preprod, preview, undeployed). +// The tests are the suite both engines run: helpers/connector-suite.ts. -import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import * as rx from 'rxjs'; -// The wallet SDK's own copy of Effect (mn declares none of its own): its submit runs on it. -import { Effect } from 'effect'; - -// Stub SDK address encoding — MidnightBech32m.encode returns a mock - -import { createDAppConnector, signatureScheme, toHistoryEntry, type DAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; -import { HISTORY, TEST_NETWORK_CONFIG, WALLET_DUST, WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, createConnector, finalizedTx, mockState } from './helpers/connector-stub.ts'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { createDAppConnector, signatureScheme, toHistoryEntry } from '@kuiralabs/midnight-engine-rc/dapp-connector'; import { PartlySignedTransactionError } from '@kuiralabs/midnight-engine-rc/sign-recipe'; -import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; -import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; -import { Intent, UnshieldedOffer, verifySignature } from '@midnightntwrk/ledger-v9'; -import type { RpcHandlerContext } from '../lib/ws-rpc.ts'; -import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { deriveAllShieldedAddresses, deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; -import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; -import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; -import { - AGENT_SK, NIGHT, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, sealedBytes, spend, unsealedBytes, -} from './helpers/ledger-tx.ts'; - - -/** Real undeployed addresses for a fixed seed, so outputs decode as they would from a dApp. */ -const RECIPIENT_SEED = Buffer.from('00'.repeat(31) + '42', 'hex'); -const UNSHIELDED_RECIPIENT = deriveUnshieldedAddress(RECIPIENT_SEED, 'undeployed'); -const SHIELDED_RECIPIENT = deriveAllShieldedAddresses(RECIPIENT_SEED).undeployed; - - -/** Mock handler context with no-op notify */ -const ctx = (connectionId = 'conn_test'): RpcHandlerContext => ({ notify: vi.fn(), connectionId, requestId: 1, metadata: {} }); - -// ── Tests ──────────────────────────────────────────────────────────── - -/** A real unsealed ledger-9 dApp transaction (the agent pays from its own signed input), as hex. */ -let AGENT_TX: string; -/** The same payment sealed (bound), as balanceSealedTransaction takes it. */ -let SEALED_AGENT_TX: string; - -beforeAll(async () => { - AGENT_TX = Buffer.from(await unsealedBytes(agentPaysMerchant())).toString('hex'); - SEALED_AGENT_TX = Buffer.from(await sealedBytes(agentPaysMerchant())).toString('hex'); -}); - -describe('dapp-connector', () => { - let connector: DAppConnector | undefined; - let origStderrWrite: typeof process.stderr.write; - - beforeEach(() => { - origStderrWrite = process.stderr.write; - }); - - afterEach(() => { - // Always restore stderr first, even if dispose throws - process.stderr.write = origStderrWrite; - connector?.dispose(); - connector = undefined; - }); - - describe('createDAppConnector', () => { - it('throws for unknown networkId', () => { - expect(() => createConnector({ - networkConfig: { ...TEST_NETWORK_CONFIG, networkId: 'Mainnet' }, - })).toThrow('Unknown networkId: Mainnet'); - }); - - it('returns all 18 handler methods', () => { - connector = createConnector(); - const methods = Object.keys(connector.handlers); - expect(methods).toContain('connect'); - expect(methods).toContain('getUnshieldedBalances'); - expect(methods).toContain('getShieldedBalances'); - expect(methods).toContain('getDustBalance'); - expect(methods).toContain('getUnshieldedAddress'); - expect(methods).toContain('getShieldedAddresses'); - expect(methods).toContain('getDustAddress'); - expect(methods).toContain('getTxHistory'); - expect(methods).toContain('getConfiguration'); - expect(methods).toContain('getConnectionStatus'); - expect(methods).toContain('makeTransfer'); - expect(methods).toContain('submitTransaction'); - expect(methods).toContain('balanceUnsealedTransaction'); - expect(methods).toContain('balanceSealedTransaction'); - expect(methods).toContain('makeIntent'); - expect(methods).toContain('signData'); - expect(methods).toContain('getProvingProvider'); - expect(methods).toContain('hintUsage'); - expect(methods.length).toBe(18); - }); - - it('dispose() unsubscribes from state', () => { - const subject = new rx.BehaviorSubject(mockState()); - connector = createConnector({ - bundleOverrides: { stateFn: () => subject.asObservable() }, - }); - expect(subject.observed).toBe(true); - connector.dispose(); - expect(subject.observed).toBe(false); - connector = undefined; // Already disposed - }); - }); - - // ── Handshake ── - - describe('connect', () => { - it('returns networkId on match', async () => { - connector = createConnector(); - const result = await connector.handlers.connect({ networkId: 'Undeployed' }, ctx()); - expect(result).toEqual({ networkId: 'Undeployed' }); - }); - - it('matches case-insensitively', async () => { - connector = createConnector(); - const result = await connector.handlers.connect({ networkId: 'undeployed' }, ctx()); - expect(result).toEqual({ networkId: 'Undeployed' }); - }); - - it('throws InvalidRequest on network mismatch', async () => { - connector = createConnector(); - await expect(connector.handlers.connect({ networkId: 'PreProd' }, ctx())) - .rejects.toThrow('Network mismatch'); - }); - - it('throws InvalidRequest when networkId is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.connect({}, ctx())) - .rejects.toThrow('Network mismatch'); - }); - }); - - // ── Read-Only Methods ── - - describe('getUnshieldedBalances', () => { - it('returns balances from state', async () => { - const balances = { 'token-a': 100n, 'token-b': 200n }; - connector = createConnector({ - bundleOverrides: { stateFn: () => rx.of(mockState({ unshieldedBalances: balances })) }, - }); - const result = await connector.handlers.getUnshieldedBalances({}, ctx()); - expect(result).toEqual(balances); - }); - }); - - describe('getShieldedBalances', () => { - it('returns balances from state', async () => { - const balances = { 'shielded-token': 999n }; - connector = createConnector({ - bundleOverrides: { stateFn: () => rx.of(mockState({ shieldedBalances: balances })) }, - }); - const result = await connector.handlers.getShieldedBalances({}, ctx()); - expect(result).toEqual(balances); - }); - }); - - describe('getDustBalance', () => { - it('returns { cap, balance } with balance from state.dust.balance()', async () => { - connector = createConnector({ - bundleOverrides: { stateFn: () => rx.of(mockState({ dustBalance: 42000n })) }, - }); - const result = await connector.handlers.getDustBalance({}, ctx()) as any; - expect(result.balance).toBe(42000n); - expect(result.cap).toBe(42000n); - }); - }); - - describe('getTxHistory', () => { - it('returns entries with correct TxStatus object shape', async () => { - connector = createConnector(); - const result = await connector.handlers.getTxHistory({ pageNumber: 0, pageSize: 10 }, ctx()) as any[]; - expect(result).toEqual([ - { txHash: 'tx-hash-001', txStatus: { status: 'finalized', executionStatus: { 0: 'Success' } } }, - { txHash: 'tx-hash-002', txStatus: { status: 'discarded' } }, - { txHash: 'tx-hash-003', txStatus: { status: 'pending' } }, - ]); - }); - - it('paginates correctly', async () => { - connector = createConnector(); - const result = await connector.handlers.getTxHistory({ pageNumber: 0, pageSize: 1 }, ctx()) as any[]; - expect(result).toHaveLength(1); - expect(result[0].txHash).toBe('tx-hash-001'); - }); - - it('returns page 2', async () => { - connector = createConnector(); - const result = await connector.handlers.getTxHistory({ pageNumber: 1, pageSize: 1 }, ctx()) as any[]; - expect(result).toHaveLength(1); - expect(result[0].txHash).toBe('tx-hash-002'); - }); - - it.each([ - [{ pageNumber: -1 }, 'Invalid pageNumber: -1'], - [{ pageNumber: 1.5 }, 'Invalid pageNumber: 1.5'], - [{ pageNumber: '1' }, 'Invalid pageNumber: "1"'], - [{ pageSize: 0 }, 'Invalid pageSize: 0'], - [{ pageSize: -5 }, 'Invalid pageSize: -5'], - [{ pageSize: 'all' }, 'Invalid pageSize: "all"'], - ])('refuses paging %o as InvalidRequest before reading the history', async (paging, message) => { - const history = vi.fn().mockResolvedValue(HISTORY); - connector = createConnector({ bundleOverrides: { getAllFromTxHistory: history } }); - - const err: any = await connector.handlers.getTxHistory(paging, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain(message); - expect(history).not.toHaveBeenCalled(); - }); - - it('returns an empty page past the end of the history', async () => { - connector = createConnector(); - const result = await connector.handlers.getTxHistory({ pageNumber: 5, pageSize: 1 }, ctx()); - expect(result).toEqual([]); - }); - - describe('execution status of finalized transactions', () => { - const finalized = (hash: string, status?: string) => ({ - hash, identifiers: [], ...(status ? { status } : {}), - lifecycle: { status: 'finalized', finalizedBlock: { hash: 'b', height: 1, timestamp: new Date(0) } }, - }); - let indexer: LocalIndexer | undefined; - afterEach(async () => { await indexer?.close(); indexer = undefined; }); - - function connectorWith(history: unknown[], indexerUrl = TEST_NETWORK_CONFIG.indexer): DAppConnector { - return createDAppConnector({ - bundle: createBundleStub({ getAllFromTxHistory: () => Promise.resolve(history as any[]) }), - networkConfig: { ...TEST_NETWORK_CONFIG, indexer: indexerUrl }, - approvalOptions: { approveAll: true }, - }); - } - - it('reports a success as segment 0 succeeding and a failure as segment 0 failing, without asking the indexer', async () => { - indexer = await startLocalIndexer(() => '{}'); - connector = connectorWith([finalized('ok', 'SUCCESS'), finalized('bad', 'FAILURE'), finalized('unknown')], indexer.url); - - const result = await connector.handlers.getTxHistory({}, ctx()); - - expect(result).toEqual([ - { txHash: 'ok', txStatus: { status: 'finalized', executionStatus: { 0: 'Success' } } }, - { txHash: 'bad', txStatus: { status: 'finalized', executionStatus: { 0: 'Failure' } } }, - // No recorded outcome: none is claimed. - { txHash: 'unknown', txStatus: { status: 'finalized', executionStatus: {} } }, - ]); - expect(indexer.requests).toEqual([]); - }); - - it('reads a partial success\'s segments from the indexer, by the entry\'s hash', async () => { - indexer = await startLocalIndexer(() => JSON.stringify({ data: { transactions: [{ - __typename: 'RegularTransaction', - transactionResult: { status: 'PARTIAL_SUCCESS', segments: [{ id: 0, success: true }, { id: 1, success: true }, { id: 2, success: false }] }, - }] } })); - connector = connectorWith([finalized('ok', 'SUCCESS'), finalized('partly', 'PARTIAL_SUCCESS')], indexer.url); - - const result = await connector.handlers.getTxHistory({}, ctx()); - - expect(result).toEqual([ - { txHash: 'ok', txStatus: { status: 'finalized', executionStatus: { 0: 'Success' } } }, - { txHash: 'partly', txStatus: { status: 'finalized', executionStatus: { 0: 'Success', 1: 'Success', 2: 'Failure' } } }, - ]); - expect(indexer.requests.map((r) => r.variables)).toEqual([{ hash: 'partly' }]); - }); - - it('fails as InternalError, naming the transaction, when the indexer cannot give a partial success\'s segments', async () => { - connector = connectorWith([finalized('partly', 'PARTIAL_SUCCESS')], 'http://127.0.0.1:9/api/v4/graphql'); - - const err: any = await connector.handlers.getTxHistory({}, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InternalError'); - expect(err.message).toContain('segment results of transaction partly'); - }); - - it('toHistoryEntry refuses a partial success without its segments rather than report it as anything else', () => { - expect(() => toHistoryEntry(finalized('partly', 'PARTIAL_SUCCESS') as any)).toThrow('segment results are missing'); - expect(() => toHistoryEntry(finalized('partly', 'PARTIAL_SUCCESS') as any, [])).toThrow('segment results are missing'); - }); - }); - - it('defaults to pageNumber 0 and pageSize 20', async () => { - const many = Array.from({ length: 25 }, (_, i) => ({ ...HISTORY[2], hash: `h${i}` })); - connector = createConnector({ bundleOverrides: { getAllFromTxHistory: () => Promise.resolve(many) } }); - const result = await connector.handlers.getTxHistory({}, ctx()) as any[]; - expect(result.map((e) => e.txHash)).toEqual(many.slice(0, 20).map((e) => e.hash)); - }); - }); - - describe('getConfiguration', () => { - it('maps NetworkConfig fields to Configuration shape', async () => { - connector = createConnector(); - const result = await connector.handlers.getConfiguration({}, ctx()) as any; - expect(result).toEqual({ - indexerUri: 'http://localhost:8088/api/v4/graphql', - indexerWsUri: 'ws://localhost:8088/api/v4/graphql/ws', - proverServerUri: 'http://localhost:6300', - substrateNodeUri: 'ws://localhost:9944', - networkId: 'Undeployed', - }); - }); - }); - - describe('getConnectionStatus', () => { - it('returns connected status with the lowercase abstractions networkId', async () => { - // Bech32m HRPs are lowercase and addresses are encoded with the lowercase - // abstractions form ('undeployed'). getConnectionStatus must report the - // same lowercase form so dApps that round-trip the value back into - // setNetworkId() before decoding addresses don't see a case-mismatch. - connector = createConnector(); - const result = await connector.handlers.getConnectionStatus({}, ctx()); - expect(result).toEqual({ status: 'connected', networkId: 'undeployed' }); - }); - }); - - // ── Ledger-9 guard on transaction methods ── - - describe('transaction methods wait for all three wallets to reach ledger 9', () => { - // The facade reads a dApp's transaction at the lowest of the three - // wallets' versions, so one wallet behind the fork would make it read - // ledger-9 bytes as ledger 8. - const DUST_BEHIND = { shielded: FORK_SCHEDULE.v9, unshielded: FORK_SCHEDULE.v9, dust: 1000300n }; - const calls = (txHex: () => string) => [ - ['balanceUnsealedTransaction', () => ({ tx: txHex() })], - ['balanceSealedTransaction', () => ({ tx: txHex() })], - ['submitTransaction', () => ({ tx: txHex() })], - ['makeTransfer', () => ({ desiredOutputs: [{ kind: 'unshielded', type: '00'.repeat(32), value: '1', recipient: 'x' }] })], - ['makeIntent', () => ({ options: { intentId: 'random', payFees: true } })], - ] as const; - - it.each(calls(() => AGENT_TX))('%s refuses as Disconnected, naming the wallet behind, before touching the facade', async (method, params) => { - const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ protocolVersion: DUST_BEHIND })) }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const err: any = await (connector.handlers as any)[method](params(), ctx()).catch((e: any) => e); - - expect(err.code).toBe('Disconnected'); - expect(err.message).toContain('still behind: dust at 1000300'); - expect(bundle.facade.adoptTransaction).not.toHaveBeenCalled(); - expect(bundle.facade.balanceUnboundTransaction).not.toHaveBeenCalled(); - expect(bundle.facade.transferTransaction).not.toHaveBeenCalled(); - expect(bundle.facade.initSwap).not.toHaveBeenCalled(); - }); - - it('accepts transactions once the lagging wallet crosses the fork', async () => { - const states = new rx.BehaviorSubject(mockState({ protocolVersion: DUST_BEHIND })); - const bundle = createBundleStub({ stateFn: () => states }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toMatchObject({ code: 'Disconnected' }); - - states.next(mockState()); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).resolves.toHaveProperty('tx'); - }); - - it('does not require a strictly synced state, which an idle chain\'s dust wallet never reports', async () => { - const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ isSynced: false })) }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).resolves.toHaveProperty('tx'); - }); - }); - - // ── State guard ── - - describe('state guard', () => { - it('throws Disconnected when wallet not synced', async () => { - const neverSynced = new rx.Subject(); - connector = createConnector({ - bundleOverrides: { stateFn: () => neverSynced.asObservable() }, - }); - await expect(connector.handlers.getUnshieldedBalances({}, ctx())) - .rejects.toThrow('Wallet not synced yet'); - }); - - // On preprod through Blockfrost a server that said "ready" refused reads - // for about 40 s: the wallet's next state the SDK calls synced came that late. - it('answers at once from the state the caller\'s sync ended on', async () => { - const quiet = new rx.Subject(); - const synced = { unshielded: { balances: { ['00'.repeat(32)]: 5n } } }; - connector = createDAppConnector({ - bundle: createBundleStub({ stateFn: () => quiet.asObservable() }), - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - initialState: synced as any, - }); - expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 5n }); - }); - - it('moves on to each later state that is current by the caller\'s rule, not only by the SDK\'s', async () => { - const states = new rx.Subject(); - connector = createDAppConnector({ - bundle: createBundleStub({ stateFn: () => states.asObservable() }), - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - initialState: { unshielded: { balances: {} } } as any, - isCurrent: (state: any) => state.caughtUp === true, - }); - // Not synced by the SDK's rule (a wallet the caller didn't sync is behind), current by the caller's. - states.next({ isSynced: false, caughtUp: true, unshielded: { balances: { ['00'.repeat(32)]: 7n } } }); - expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 7n }); - // Behind by the caller's rule: reads keep the last current state. - states.next({ isSynced: false, caughtUp: false, unshielded: { balances: { ['00'.repeat(32)]: 9n } } }); - expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 7n }); - }); - - it('throws Disconnected with correct error code', async () => { - const neverSynced = new rx.Subject(); - connector = createConnector({ - bundleOverrides: { stateFn: () => neverSynced.asObservable() }, - }); - try { - await connector.handlers.getUnshieldedBalances({}, ctx()); - expect.unreachable('should have thrown'); - } catch (err: any) { - expect(err.code).toBe('Disconnected'); - expect(err.type).toBe('DAppConnectorAPIError'); - } - }); - }); - - // ── Write method approval gating ── - - describe('write method approval', () => { - it('proceeds when approveAll is true', async () => { - connector = createConnector({ approvalOptions: { approveAll: true } }); - const result = await connector.handlers.signData({ - data: 'deadbeef', - options: { encoding: 'hex', keyType: 'unshielded' }, - }, ctx()) as any; - expect(result.data).toBe('deadbeef'); - expect(result.signature).toBe('abcd1234signature'); - expect(result.verifyingKey).toBe('5678efghpubkey'); - }); - - it('rejects when stdin is not TTY and no approveAll', async () => { - const origIsTTY = process.stdin.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - process.stderr.write = (() => true) as any; - - try { - connector = createConnector({ approvalOptions: {} }); - await expect(connector.handlers.signData({ - data: 'deadbeef', - options: { encoding: 'hex', keyType: 'unshielded' }, - }, ctx())).rejects.toThrow('User rejected the request'); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - } - }); - - it('rejects with Rejected error code', async () => { - const origIsTTY = process.stdin.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - process.stderr.write = (() => true) as any; - - try { - connector = createConnector({ approvalOptions: {} }); - try { - await connector.handlers.submitTransaction({ tx: 'aabb' }, ctx()); - expect.unreachable('should have thrown'); - } catch (err: any) { - expect(err.code).toBe('Rejected'); - expect(err.type).toBe('DAppConnectorAPIError'); - } - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - } - }); - }); - - // ── signData ── - - describe('signData', () => { - it('refuses data that is not valid in its encoding before the operator is asked', async () => { - // No approveAll and no TTY: reaching the approval step would fail as Rejected instead. - connector = createConnector({ approvalOptions: {} }); - const origIsTTY = process.stdin.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - try { - const err: any = await connector.handlers.signData({ data: '@@@not base64@@@', options: { encoding: 'base64', keyType: 'unshielded' } }, ctx()) - .catch((e: any) => e); - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toBe('data is not valid base64 (standard alphabet, padded)'); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - } - }); - - it('handles hex encoding', async () => { - const bundle = createBundleStub(); - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - const result = await connector.handlers.signData({ - data: 'cafebabe', - options: { encoding: 'hex', keyType: 'unshielded' }, - }, ctx()) as any; - - expect(result.data).toBe('cafebabe'); - expect((bundle.keystore as any).signDataAsync).toHaveBeenCalledWith( - signedMessageBytes(new Uint8Array([0xca, 0xfe, 0xba, 0xbe])) - ); - }); - - it('handles base64 encoding', async () => { - const bundle = createBundleStub(); - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - const b64Data = Buffer.from('hello world').toString('base64'); - const result = await connector.handlers.signData({ - data: b64Data, - options: { encoding: 'base64' }, - }, ctx()) as any; - - expect(result.data).toBe(b64Data); - expect((bundle.keystore as any).signDataAsync).toHaveBeenCalledWith( - signedMessageBytes(new Uint8Array(Buffer.from('hello world'))) - ); - }); - - it('handles text encoding', async () => { - const bundle = createBundleStub(); - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - const result = await connector.handlers.signData({ - data: 'sign me', - options: { encoding: 'text' }, - }, ctx()) as any; - - expect(result.data).toBe('sign me'); - expect((bundle.keystore as any).signDataAsync).toHaveBeenCalledWith( - signedMessageBytes(new Uint8Array(Buffer.from('sign me', 'utf-8'))) - ); - }); - - // The key that signs here also signs the wallet's unshielded spends, over a - // transaction's signature data. Signed as given, a dApp could send that - // signature data as its message and get back a valid spend signature. - it('signs the prefixed message, so a transaction\'s signature data sent as data gives no spend signature', async () => { - const keystore = createKeystore({ kind: 'schnorr', secret: new Uint8Array(32).fill(1) }, 'undeployed'); - const vk = keystore.getPublicKey(); - expect(vk).toEqual(WALLET_VK); - const intent = Intent.new(new Date(Date.UTC(2030, 0, 1))); - intent.guaranteedUnshieldedOffer = UnshieldedOffer.new([spend(WALLET_SK, 990n)], [pay(990n)], []); - const spendData = intent.signatureData(1); - const bundle = createBundleStub(); - (bundle as any).keystore = keystore; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const result = await connector.handlers.signData({ - data: Buffer.from(spendData).toString('hex'), options: { encoding: 'hex', keyType: 'unshielded' }, - }, ctx()) as any; - - const signature = { tag: 'schnorr', value: result.signature } as never; - expect(verifySignature(vk, spendData, signature)).toBe(false); - expect(verifySignature(vk, signedMessageBytes(spendData), signature)).toBe(true); - expect(result.data).toBe(Buffer.from(spendData).toString('hex')); - }); - - it('throws for unknown encoding', async () => { - connector = createConnector(); - await expect(connector.handlers.signData({ - data: 'test', - options: { encoding: 'binary' }, - }, ctx())).rejects.toThrow('Unknown encoding: binary'); - }); - - it('throws for unsupported keyType', async () => { - connector = createConnector(); - await expect(connector.handlers.signData({ - data: 'test', - options: { encoding: 'text', keyType: 'shielded' }, - }, ctx())).rejects.toThrow('Unsupported keyType'); - }); - - it('throws when data is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.signData({ - options: { encoding: 'hex' }, - }, ctx())).rejects.toThrow('data and options.encoding are required'); - }); - - it('throws when encoding is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.signData({ - data: 'test', - options: {}, - }, ctx())).rejects.toThrow('data and options.encoding are required'); - }); - - it('returns the hex values and the scheme, not the SDK\'s { tag, value } objects', async () => { - connector = createConnector(); - const result = await connector.handlers.signData({ - data: 'aabb', - options: { encoding: 'hex' }, - }, ctx()) as any; - expect(result).toEqual({ - data: 'aabb', - signature: 'abcd1234signature', - verifyingKey: '5678efghpubkey', - scheme: 'schnorr_bip340', - }); - }); - }); - - // ── Input validation on write methods ── - - describe('input validation', () => { - it('makeTransfer throws when desiredOutputs is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.makeTransfer({}, ctx())) - .rejects.toThrow('desiredOutputs must be a non-empty array'); - }); - - it('makeTransfer throws when desiredOutputs is empty', async () => { - connector = createConnector(); - await expect(connector.handlers.makeTransfer({ desiredOutputs: [] }, ctx())) - .rejects.toThrow('desiredOutputs must be a non-empty array'); - }); - - it('makeTransfer throws for invalid output kind', async () => { - connector = createConnector(); - await expect(connector.handlers.makeTransfer({ - desiredOutputs: [{ kind: 'public', type: '0000', value: '100', recipient: 'addr' }], - }, ctx())).rejects.toThrow('Invalid output kind: "public"'); - }); - - // A dApp's mistakes in what it asks for are InvalidRequest, refused before - // the operator is prompted and before the wallet builds anything. - const output = (o: Record) => ({ kind: 'unshielded', type: NIGHT, value: '5', recipient: UNSHIELDED_RECIPIENT, ...o }); - /** No approveAll and no TTY: reaching the approval step would fail as Rejected instead. */ - async function withoutOperator(run: () => Promise): Promise { - const origIsTTY = process.stdin.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - try { - return await run(); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - } - } - - it.each([ - ['a zero value', output({ value: '0' }), 'Invalid value: 0 — must be greater than 0'], - ['a negative value', output({ value: '-1' }), 'Invalid value: -1 — must be greater than 0'], - ['a fractional value', output({ value: '1.5' }), 'Invalid value: "1.5" — must be a whole number'], - ['a value that is not a number', output({ value: 'lots' }), 'Invalid value: "lots"'], - ['a boolean value, which BigInt would read as 1', output({ value: true }), 'Invalid value: "true"'], - ['a token type that is not 32 bytes of hex', output({ type: '0000' }), 'Invalid token type: "0000"'], - ['a recipient that is not an address', output({ recipient: 'bob' }), 'Invalid recipient: "bob" is not an unshielded address on Undeployed'], - ['a shielded address for an unshielded output', output({ recipient: SHIELDED_RECIPIENT }), 'is not an unshielded address on Undeployed'], - ['an unshielded address for a shielded output', output({ kind: 'shielded' }), 'is not a shielded address on Undeployed'], - ['an address for another network', output({ recipient: deriveUnshieldedAddress(RECIPIENT_SEED, 'preprod') }), 'is not an unshielded address on Undeployed'], - ])('makeTransfer refuses %s as InvalidRequest without prompting', async (_name, desired, message) => { - const transfer = vi.fn(); - const c = connector = createConnector({ bundleOverrides: { transferTransaction: transfer }, approvalOptions: {} }); - - const err: any = await withoutOperator(() => c.handlers.makeTransfer({ desiredOutputs: [desired] }, ctx()).catch((e: any) => e)); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain(message); - expect(transfer).not.toHaveBeenCalled(); - }); - - it('makeTransfer passes a valid output to the wallet as a decoded address and a bigint', async () => { - const transfer = vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }); - connector = createConnector({ bundleOverrides: { transferTransaction: transfer } }); - - await connector.handlers.makeTransfer({ desiredOutputs: [output({})] }, ctx()).catch(() => undefined); - - const [[combined]] = transfer.mock.calls; - expect(combined).toEqual([{ type: 'unshielded', outputs: [{ type: NIGHT, receiverAddress: expect.anything(), amount: 5n }] }]); - }); - - it.each([ - ['an input kind that is neither', { kind: 'public', type: NIGHT, value: '5' }, 'Invalid input kind: "public"'], - ['a zero input value', { kind: 'unshielded', type: NIGHT, value: '0' }, 'Invalid value: 0'], - ['an input token type that is not hex', { kind: 'unshielded', type: 'night', value: '5' }, 'Invalid token type: "night"'], - ])('makeIntent refuses %s as InvalidRequest without building a swap', async (_name, input, message) => { - const initSwap = vi.fn(); - const c = connector = createConnector({ bundleOverrides: { initSwap }, approvalOptions: {} }); - - const err: any = await withoutOperator(() => c.handlers.makeIntent({ - desiredInputs: [input], desiredOutputs: [], options: { intentId: 'random', payFees: true }, - }, ctx()).catch((e: any) => e)); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain(message); - expect(initSwap).not.toHaveBeenCalled(); - }); - - it('submitTransaction throws when tx is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.submitTransaction({}, ctx())) - .rejects.toThrow('tx is required'); - }); - - it('balanceUnsealedTransaction throws when tx is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.balanceUnsealedTransaction({}, ctx())) - .rejects.toThrow('tx is required'); - }); - - it('balanceSealedTransaction throws when tx is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.balanceSealedTransaction({}, ctx())) - .rejects.toThrow('tx is required'); - }); - - it('makeIntent throws when options is missing', async () => { - connector = createConnector(); - await expect(connector.handlers.makeIntent({ - desiredInputs: [], - desiredOutputs: [], - }, ctx())).rejects.toThrow('options is required for makeIntent'); - }); - }); - - // ── Reading the dApp's transaction (the fee-wallet seam) ── - - describe('transaction adoption', () => { - it.each([ - ['balanceUnsealedTransaction', 'Unbound', 'balanceUnboundTransaction'], - ['balanceSealedTransaction', 'Finalized', 'balanceFinalizedTransaction'], - ] as const)('%s reads the hex at stage %s and balances that handle', async (method, stage, sdkMethod) => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const bundle = createBundleStub({ [sdkMethod]: balance }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - const tx = stage === 'Unbound' ? AGENT_TX : SEALED_AGENT_TX; - - await connector.handlers[method]({ tx }, ctx()); - - expect(bundle.facade.adoptTransaction).toHaveBeenCalledWith(Uint8Array.from(Buffer.from(tx, 'hex')), stage); - expect(balance).toHaveBeenCalledWith({ stage, hex: tx }, expect.objectContaining({ ttl: expect.any(Date) })); - }); - - it('submitTransaction reads the hex as a finalized transaction and submits that handle', async () => { - const submit = vi.fn().mockResolvedValue('tx-id'); - const bundle = createBundleStub({ submitTransaction: submit }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const result = await connector.handlers.submitTransaction({ tx: 'beef' }, ctx()); - - expect(bundle.facade.adoptTransaction).toHaveBeenCalledWith(new Uint8Array([0xbe, 0xef]), 'Finalized'); - expect(submit).toHaveBeenCalledWith({ stage: 'Finalized', hex: 'beef' }); - expect(result).toEqual({ txHash: 'tx-id' }); - }); - - it("forwards the node's refusal when the wallet SDK's submit fails, not only its own wrapper's words", async () => { - // The wallet SDK runs its Effect submit with Effect.runPromise, which - // rejects with a FiberFailure: the SubmissionError it failed with, and - // the node's answer that error wraps, are under a symbol, not `cause`. - const nodeAnswer = new Error('1010: Invalid Transaction: Custom error: 139'); - const sdkFailure = Effect.runPromise(Effect.fail(new SubmissionError({ message: 'Transaction submission error', cause: nodeAnswer }))); - sdkFailure.catch(() => {}); - const bundle = createBundleStub({ submitTransaction: () => sdkFailure }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const err: any = await connector.handlers.submitTransaction({ tx: 'beef' }, ctx()).catch((e: any) => e); - - expect(err.message).toContain('Transaction submission error'); - expect(err.message).toContain('1010: Invalid Transaction: Custom error: 139'); - }); - - it('reports bytes the wallet cannot read as InvalidRequest, naming the stage, without balancing', async () => { - const balance = vi.fn(); - const bundle = createBundleStub({ balanceUnboundTransaction: balance }); - (bundle.facade as any).adoptTransaction = () => { throw new Error('unknown tag midnight:transaction[v99]'); }; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: 'aabb' }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain('stage Unbound'); - expect(err.message).toContain('unknown tag midnight:transaction[v99]'); - expect(balance).not.toHaveBeenCalled(); - }); - - it('rejects non-hex input before it reaches the SDK', async () => { - const bundle = createBundleStub(); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: 'not-hex' }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(bundle.facade.adoptTransaction).not.toHaveBeenCalled(); - }); - }); - - describe('signatureScheme', () => { - it('names BIP-340 Schnorr, and refuses any other tag rather than mislabel it', () => { - expect(signatureScheme('schnorr')).toBe('schnorr_bip340'); - expect(() => signatureScheme('ecdsa')).toThrow('mn signs with BIP-340 Schnorr only'); - }); - }); - - // ── Address methods ── - - describe('getUnshieldedAddress', () => { - it('returns bech32m-encoded unshielded address', async () => { - connector = createConnector(); - const result = await connector.handlers.getUnshieldedAddress({}, ctx()) as any; - expect(result.unshieldedAddress).toMatch(/^mn_addr_undeployed1/); - expect(MidnightBech32m.parse(result.unshieldedAddress).decode(UnshieldedAddress, 'undeployed').equals(WALLET_UNSHIELDED.hexString)).toBe(true); - }); - }); - - describe('getShieldedAddresses', () => { - it('returns shielded address and public keys', async () => { - connector = createConnector(); - const result = await connector.handlers.getShieldedAddresses({}, ctx()) as any; - expect(result.shieldedAddress).toBe(MidnightBech32m.encode('undeployed', WALLET_SHIELDED).asString()); - expect(result.shieldedAddress).toMatch(/^mn_shield-addr_undeployed1/); - expect(result.shieldedCoinPublicKey).toBe(WALLET_SHIELDED.coinPublicKeyString()); - expect(result.shieldedEncryptionPublicKey).toBe(WALLET_SHIELDED.encryptionPublicKeyString()); - }); - }); - - describe('getDustAddress', () => { - it('returns bech32m-encoded dust address', async () => { - connector = createConnector(); - const result = await connector.handlers.getDustAddress({}, ctx()) as any; - expect(result.dustAddress).toMatch(/^mn_dust_undeployed1/); - expect(MidnightBech32m.parse(result.dustAddress).decode(DustAddress, 'undeployed').data).toBe(7n); - }); - }); - - // ── processRecipe (tested via write methods) ── - - describe('processRecipe', () => { - it('rejects with timeout error when proof generation fails', async () => { - // Tests the error path through processRecipe — finalizeRecipe rejection - // propagates correctly through Promise.race and surfaces to the caller. - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - finalizeRecipe: () => Promise.reject(new Error('ZK proof generation timed out')), - }, - }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())) - .rejects.toThrow('ZK proof generation timed out'); - }); - - it('returns serialized tx when finalizeRecipe resolves', async () => { - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - finalizeRecipe: () => Promise.resolve(finalizedTx(0xfe, 0xed)), - }, - }); - - const result = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()) as any; - expect(result.tx).toBe('feed'); - }); - - it('propagates signRecipe errors', async () => { - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - signRecipe: () => Promise.reject(new Error('signing failed')), - }, - }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())) - .rejects.toThrow('signing failed'); - }); - - it('propagates finalizeRecipe errors', async () => { - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - finalizeRecipe: () => Promise.reject(new Error('proof generation failed')), - }, - }); - - await expect(connector.handlers.balanceSealedTransaction({ tx: SEALED_AGENT_TX }, ctx())) - .rejects.toThrow('proof generation failed'); - }); - }); - - // ── getProvingProvider ── - - describe('getProvingProvider', () => { - it('returns proof server URI', async () => { - connector = createConnector(); - const result = await connector.handlers.getProvingProvider({}, ctx()) as any; - expect(result.provingProvider).toBe('ready'); - expect(result.proverServerUri).toBe('http://localhost:6300'); - }); - }); - - // ── hintUsage ── - - describe('hintUsage', () => { - it('resolves without error', async () => { - process.stderr.write = (() => true) as any; - - connector = createConnector(); - const result = await connector.handlers.hintUsage({ - methodNames: ['getUnshieldedBalances', 'makeTransfer'], - }, ctx()); - expect(result).toBeUndefined(); - }); - - it('resolves for a method this wallet does not know, as the spec asks', async () => { - process.stderr.write = (() => true) as any; - connector = createConnector(); - await expect(connector.handlers.hintUsage({ methodNames: ['someFutureMethod'] }, ctx())).resolves.toBeUndefined(); - }); - - it.each([ - ['a string instead of an array', 'makeTransfer'], - ['a non-string entry', ['makeTransfer', 42]], - ['a name carrying terminal escape codes', ['\u001b[2Jcleared']], - ])('refuses %s as InvalidRequest without printing it', async (_name, methodNames) => { - const written: string[] = []; - process.stderr.write = ((chunk: string) => { written.push(chunk); return true; }) as any; - connector = createConnector(); - - const err: any = await connector.handlers.hintUsage({ methodNames }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toBe('methodNames must be an array of connector method names'); - expect(written.join('')).not.toContain('hints usage'); - }); - }); - - // ── Dust retry ── - - describe('withDustRetry', () => { - it('retries on "No dust tokens" error and succeeds', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - let callCount = 0; - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - balanceUnboundTransaction: () => { - callCount++; - if (callCount === 1) return Promise.reject(new Error('No dust tokens found in the wallet state')); - return Promise.resolve({ type: 'UNBOUND' }); - }, - }, - }); - - const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(3_100); - const result = await promise as any; - expect(result.tx).toBeDefined(); - expect(callCount).toBe(2); - vi.useRealTimers(); - }); - - it('retries on wallet-sdk 2.0\'s tagged dust shortage', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - const dustShortage = Object.assign(new Error('Insufficient Funds: could not balance dust'), { - _tag: 'Wallet.InsufficientFunds', tokenType: 'dust', - }); - let callCount = 0; - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - balanceUnboundTransaction: () => (++callCount === 1 ? Promise.reject(dustShortage) : Promise.resolve({ type: 'UNBOUND' })), - }, - }); - - const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(3_100); - await promise; - expect(callCount).toBe(2); - vi.useRealTimers(); - }); - - it('does not wait for dust when the wallet is short of NIGHT, which dust cannot fix', async () => { - process.stderr.write = (() => true) as any; - const nightShortage = Object.assign(new Error('Insufficient Funds: could not balance 00'), { - _tag: 'Wallet.InsufficientFunds', tokenType: '00', - }); - const balance = vi.fn().mockRejectedValue(nightShortage); - connector = createConnector({ approvalOptions: { approveAll: true }, bundleOverrides: { balanceUnboundTransaction: balance } }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toBe(nightShortage); - expect(balance).toHaveBeenCalledTimes(1); - }); - - it('does not retry on non-dust errors', async () => { - process.stderr.write = (() => true) as any; - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - balanceUnboundTransaction: () => Promise.reject(new Error('some other error')), - }, - }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())) - .rejects.toThrow('some other error'); - }); - - it('fails after max retry attempts', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - let callCount = 0; - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - balanceUnboundTransaction: () => { - callCount++; - return Promise.reject(new Error('No dust tokens found in the wallet state')); - }, - }, - }); - - const failure = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); - await vi.advanceTimersByTimeAsync(9 * 3_000); - const err: any = await failure; - expect(err.code).toBe('InternalError'); - // Nothing is reserved on this server, so the message doesn't send the caller waiting for a reservation to clear. - expect(err.message).toContain('The wallet has no Dust available that covers this transaction\'s fee (No dust tokens found in the wallet state)'); - expect(err.message).toContain('no balanced transaction is holding any back on this server'); - expect(err.message).not.toContain('Retry once they settle'); - expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); - expect(callCount).toBe(10); // DUST_RETRY_ATTEMPTS = 10 - vi.useRealTimers(); - }); - - describe('a shortage that says what the fee takes', () => { - // The wallet's own fee planner marks a shortage with the Dust the fee - // takes. This wallet holds 0.35 DUST and generates 0.0075 a second, as - // a 900 NIGHT wallet on a local ledger-9 chain does. - const SPECK = 1_000_000_000_000_000n; - const HAS = 350n * SPECK / 1000n; - const PER_SECOND = 75n * SPECK / 10_000n; - const shortOf = (needed: bigint, available = HAS) => withDustShortfall(Object.assign(new Error('Insufficient Funds: could not balance dust'), { - _tag: 'Wallet.InsufficientFunds', tokenType: 'dust', - }), { needed, available }); - /** A wallet state whose Dust grows from HAS at PER_SECOND, counted from when the test starts. */ - const growingFrom = (start: number) => () => rx.of({ - ...mockState(), - dust: { balance: (at: Date) => HAS + PER_SECOND * BigInt(Math.max(0, Math.floor((at.getTime() - start) / 1000))), availableCoins: [{}], address: 'dust' }, - }); - - it('waits the time the wallet takes to generate the rest, then pays', async () => { - vi.useFakeTimers(); - const written: string[] = []; - setNoticeSink((line) => written.push(line)); - // 1 DUST: 0.65 more and a little over, 89 seconds at this rate. - const balance = vi.fn().mockRejectedValueOnce(shortOf(SPECK)).mockResolvedValue({ type: 'UNBOUND' }); - connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); - - const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(88_000); - expect(balance).toHaveBeenCalledTimes(1); - await vi.advanceTimersByTimeAsync(1_500); - await paid; - expect(balance).toHaveBeenCalledTimes(2); - expect(written.join('')).toContain('Dust: 0.35 of the 1.00 DUST this fee takes; waiting about 2 minutes for the rest...'); - vi.useRealTimers(); - setNoticeSink(null); - }); - - it('refuses at once, with the time, when that is longer than a request waits', async () => { - process.stderr.write = (() => true) as any; - // 2 DUST: 1.65 more, close to four minutes, past the two a request waits. - const balance = vi.fn().mockRejectedValue(shortOf(2n * SPECK)); - connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); - expect(balance).toHaveBeenCalledTimes(1); - expect(err.code).toBe('InternalError'); - expect(err.message).toBe( - "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00. " - + 'Its registered NIGHT generates the rest in about 4 minutes: retry then, or register more NIGHT to get there sooner.'); - expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); - }); - - it('waits longer when the caller allows it', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - const balance = vi.fn().mockRejectedValueOnce(shortOf(2n * SPECK)).mockResolvedValue({ type: 'UNBOUND' }); - connector = createDAppConnector({ - bundle: createBundleStub({ stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance }), - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - dustWaitMs: 5 * 60_000, - }); - - const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(226_000); - await paid; - expect(balance).toHaveBeenCalledTimes(2); - vi.useRealTimers(); - }); - - it('says so when the wallet will not generate the fee within a day', async () => { - process.stderr.write = (() => true) as any; - const balance = vi.fn().mockRejectedValue(shortOf(1_000n * SPECK)); - connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); - expect(err.message).toContain("the wallet has 0.35 DUST and the fee takes 1000.00. Its registered NIGHT won't generate that within a day"); - expect(balance).toHaveBeenCalledTimes(1); - }); - - it('waits for what the wallet was short by on its own clock, which this machine\'s can run ahead of', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - // The wallet spends by the chain's clock, 28 seconds behind: its coin held 0.14 DUST when the balance here read 0.35. - const behind = HAS - 28n * PER_SECOND; - const balance = vi.fn().mockRejectedValueOnce(shortOf(SPECK, behind)).mockResolvedValue({ type: 'UNBOUND' }); - connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); - - const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(116_000); // 0.86 more and a little over: 117 seconds - expect(balance).toHaveBeenCalledTimes(1); - await vi.advanceTimersByTimeAsync(1_500); - await paid; - expect(balance).toHaveBeenCalledTimes(2); - vi.useRealTimers(); - }); - - it('stops waiting once the waits add up to more than a request waits', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - // The fee keeps moving ahead of the wallet: each wait fits, together they don't. - const start = Date.now(); - const balance = vi.fn().mockImplementation(() => Promise.reject(shortOf(HAS + 50n * PER_SECOND))); - connector = createConnector({ bundleOverrides: { stateFn: growingFrom(start), balanceUnboundTransaction: balance } }); - - const failure = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); - await vi.advanceTimersByTimeAsync(130_000); - const err: any = await failure; - expect(err.message).toContain("Not enough Dust available for this transaction's fee"); - expect(balance).toHaveBeenCalledTimes(3); // 51 s, 51 s, then a third 51 s would pass two minutes - vi.useRealTimers(); - }); - }); - - it('asks again at once when a coin comes free during the wait', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - const attemptedAt: number[] = []; - const started = Date.now(); - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - // No Dust coin is free until one second in, when a pending transaction lands and releases its coin. - stateFn: () => rx.concat(rx.of(mockState({ dustBalance: 0n })), rx.timer(1_000).pipe(rx.map(() => mockState({ dustBalance: 1000n })))), - balanceUnboundTransaction: () => { - attemptedAt.push(Date.now() - started); - return attemptedAt.length < 2 ? Promise.reject(new Error('No dust tokens found in the wallet state')) : Promise.resolve({ type: 'UNBOUND' }); - }, - }, - }); - - const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(1_100); - await promise; - expect(attemptedAt).toEqual([0, 1_000]); - vi.useRealTimers(); - }); - - // Found live: a coin that had just paid a fee was worth less than the - // next one. It showed as available, so all ten attempts ran in 40 ms and - // the request failed, though the coin would have covered it seconds later. - it('gives a coin that is there but too small the delay to grow before each new attempt', async () => { - vi.useFakeTimers(); - process.stderr.write = (() => true) as any; - const shortage = Object.assign(new Error('Insufficient Funds: could not balance dust'), { _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' }); - const attemptedAt: number[] = []; - const started = Date.now(); - connector = createConnector({ - approvalOptions: { approveAll: true }, - bundleOverrides: { - // The wallet state shows Dust throughout; the fourth attempt finds it has grown enough. - balanceUnboundTransaction: () => { - attemptedAt.push(Date.now() - started); - return attemptedAt.length < 4 ? Promise.reject(shortage) : Promise.resolve({ type: 'UNBOUND' }); - }, - }, - }); - - const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - await vi.advanceTimersByTimeAsync(2_900); - expect(attemptedAt).toEqual([0]); - await vi.advanceTimersByTimeAsync(6_200); - await promise; - expect(attemptedAt).toEqual([0, 3_000, 6_000, 9_000]); - vi.useRealTimers(); - }); - }); - - // ── Hex-based pending tx tracking ── - - // ── What the wallet balances, per mode ── - - describe('token kinds to balance', () => { - it.each([ - ['balanceUnsealedTransaction', 'balanceUnboundTransaction'], - ['balanceSealedTransaction', 'balanceFinalizedTransaction'], - ] as const)('%s balances every kind by default, and leaves the fee out when payFees is false', async (method, sdkMethod) => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - connector = createConnector({ bundleOverrides: { [sdkMethod]: balance } }); - - const tx = method === 'balanceUnsealedTransaction' ? AGENT_TX : SEALED_AGENT_TX; - await connector.handlers[method]({ tx }, ctx()); - await connector.handlers[method]({ tx, options: { payFees: true } }, ctx()); - await connector.handlers[method]({ tx, options: { payFees: false } }, ctx()); - - expect(balance.mock.calls.map(([, opts]) => opts)).toEqual([ - { ttl: expect.any(Date), tokenKindsToBalance: 'all' }, - { ttl: expect.any(Date), tokenKindsToBalance: 'all' }, - { ttl: expect.any(Date), tokenKindsToBalance: ['shielded', 'unshielded'] }, - ]); - }); - }); - - // ── Fee wallet: --approve-fees ── - - describe('fee wallet (approveFees)', () => { - let origIsTTY: boolean | undefined; - const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex'); - - beforeEach(() => { - origIsTTY = process.stdin.isTTY; - // An agent has no terminal: anything that is not fee-only must be rejected, not prompted. - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - process.stderr.write = (() => true) as any; - }); - - afterEach(() => { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - }); - - /** A connector in fee-wallet mode over a bundle whose unshielded key is WALLET_VK. */ - function feeWallet( - overrides?: Parameters[0], - approvalOptions: ApprovalOptions = { approveFees: true, autoApproveReads: true }, - feeLimits?: FeeLimits, - ) { - const bundle = createBundleStub(overrides); - (bundle.keystore as any).getPublicKey = () => WALLET_VK; - const feeConnector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions, feeLimits }); - connector = feeConnector; - return { bundle, connector: feeConnector }; - } - - describe('fee limits', () => { - const ONE_DUST = 1_000_000_000_000_000n; - - it('refuses a transaction whose estimated fee is over --max-fee, before balancing', async () => { - const balance = vi.fn(); - const estimate = vi.fn().mockResolvedValue(ONE_DUST + 1n); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, undefined, - { maxFeeSpecks: ONE_DUST, maxPending: 2 }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()) - .catch((e) => e); - - expect(err.code).toBe('Rejected'); - expect(err.message).toContain('over --max-fee 1.000000 DUST'); - expect(estimate).toHaveBeenCalledTimes(1); - expect(balance).not.toHaveBeenCalled(); - }); - - it('balances a transaction at the cap', async () => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: async () => ONE_DUST }, undefined, - { maxFeeSpecks: ONE_DUST, maxPending: 2 }); - - await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()); - expect(balance).toHaveBeenCalledTimes(1); - }); - - it('refuses a new balance while --max-pending unsubmitted transactions hold Dust, and frees a slot on submit', async () => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const finalizeRecipe = vi.fn() - .mockResolvedValueOnce(finalizedTx(0x01)) - .mockResolvedValueOnce(finalizedTx(0x02)) - .mockResolvedValueOnce(finalizedTx(0x03)); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, finalizeRecipe }, undefined, - { maxFeeSpecks: ONE_DUST, maxPending: 2 }); - const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; - - const first: any = await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')); - await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c2')); - const err: any = await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')).catch((e) => e); - expect(err.code).toBe('Rejected'); - expect(err.message).toContain('2 balanced transactions are still waiting to be submitted (--max-pending 2)'); - expect(balance).toHaveBeenCalledTimes(2); - - await connector.handlers.submitTransaction({ tx: first.tx }, ctx('c1')); - await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')); - expect(balance).toHaveBeenCalledTimes(3); - }); - - it('says a balanced transaction is holding the Dust when one is, and how many', async () => { - vi.useFakeTimers(); - const stderrWrite = process.stderr.write; - process.stderr.write = (() => true) as any; - try { - const balance = vi.fn() - .mockResolvedValueOnce({ type: 'RECIPE' }) - // The shape of the wallet SDK's own Dust shortage. - .mockRejectedValue(Object.assign(new Error('Insufficient Funds: could not balance dust'), { _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' })); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, finalizeRecipe: vi.fn().mockResolvedValue(finalizedTx(0x01)) }, undefined, - { maxFeeSpecks: ONE_DUST, maxPending: 2 }); - const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; - - await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')); - const failure = connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c2')).catch((e: any) => e); - await vi.advanceTimersByTimeAsync(9 * 2 * 3_000); - const err: any = await failure; - expect(err.message).toContain('No Dust is free to pay the fee ([Wallet.InsufficientFunds] Insufficient Funds: could not balance dust)'); - expect(err.message).toContain('1 balanced transaction(s) are waiting to be submitted on this server. Retry once they settle.'); - expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); - } finally { - process.stderr.write = stderrWrite; - vi.useRealTimers(); - } - }); - - it('counts balances still in flight: two at the same moment cannot both take the last slot', async () => { - let finishEstimate!: () => void; - const estimateGate = new Promise((r) => { finishEstimate = r; }); - const estimate = vi.fn(async () => { await estimateGate; return 1n; }); - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, undefined, - { maxFeeSpecks: ONE_DUST, maxPending: 1 }); - const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; - - const first = connector.handlers.balanceUnsealedTransaction(agentTx, ctx('a')); - const second = connector.handlers.balanceUnsealedTransaction(agentTx, ctx('b')).catch((e: any) => e); - finishEstimate(); - - await expect(first).resolves.toHaveProperty('tx'); - const err: any = await second; - expect(err.code).toBe('Rejected'); - expect(err.message).toContain('(--max-pending 1)'); - expect(balance).toHaveBeenCalledTimes(1); - }); - - it('gives the slot back when a balance fails, so the next one can use it', async () => { - const estimate = vi.fn().mockResolvedValueOnce(2n * ONE_DUST).mockResolvedValue(1n); - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, undefined, - { maxFeeSpecks: ONE_DUST, maxPending: 1 }); - const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; - - await expect(connector.handlers.balanceUnsealedTransaction(agentTx, ctx())).rejects.toMatchObject({ code: 'Rejected' }); - await expect(connector.handlers.balanceUnsealedTransaction(agentTx, ctx())).resolves.toHaveProperty('tx'); - }); - - it('does not apply outside fee-wallet mode', async () => { - const estimate = vi.fn().mockResolvedValue(10n * ONE_DUST); - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, - { approveAll: true }, { maxFeeSpecks: 1n, maxPending: 1 }); - - await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()); - expect(estimate).not.toHaveBeenCalled(); - expect(balance).toHaveBeenCalledTimes(1); - }); - }); - - it.each([ - ['balanceUnsealedTransaction', 'balanceUnboundTransaction', unsealedBytes], - ['balanceSealedTransaction', 'balanceFinalizedTransaction', sealedBytes], - ] as const)('%s balances Dust-only and is approved without a terminal', async (method, sdkMethod, toBytes) => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ [sdkMethod]: balance }); - - const result = await connector.handlers[method]({ tx: hex(await toBytes(agentPaysMerchant())) }, ctx()) as any; - - expect(balance).toHaveBeenCalledTimes(1); - expect(balance.mock.calls[0]![1]).toEqual({ ttl: expect.any(Date), tokenKindsToBalance: ['dust'] }); - expect(result).toEqual({ tx: 'abcd' }); - }); - - it('approves a fee-only balance as fee-only, not as a prep step, so it holds with --no-auto-approve-reads', async () => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ balanceUnboundTransaction: balance }, { approveFees: true, autoApproveReads: false }); - - const result = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()) as any; - - expect(balance).toHaveBeenCalledTimes(1); - expect(result).toEqual({ tx: 'abcd' }); - }); - - it('submits a transaction it balanced fee-only on the same connection, without a terminal', async () => { - const submit = vi.fn().mockResolvedValue('tx-id'); - const { connector } = feeWallet({ submitTransaction: submit }); - - const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx('agent')) as any; - const result = await connector.handlers.submitTransaction({ tx: balanced.tx }, ctx('agent')); - - expect(submit).toHaveBeenCalledWith({ stage: 'Finalized', hex: 'abcd' }); - expect(result).toEqual({ txHash: 'tx-id' }); - }); - - it('rejects submitting a transaction this server did not balance', async () => { - const submit = vi.fn(); - const { connector } = feeWallet({ submitTransaction: submit }); - - const err: any = await connector.handlers.submitTransaction({ tx: hex(await sealedBytes(agentPaysMerchant())) }, ctx('agent')).catch((e: any) => e); - - expect(err.code).toBe('Rejected'); - expect(submit).not.toHaveBeenCalled(); - }); - - it('rejects submitting a fee-only transaction from another connection', async () => { - const submit = vi.fn(); - const { connector } = feeWallet({ submitTransaction: submit }); - - const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx('agent')) as any; - const err: any = await connector.handlers.submitTransaction({ tx: balanced.tx }, ctx('someone-else')).catch((e: any) => e); - - expect(err.code).toBe('Rejected'); - expect(submit).not.toHaveBeenCalled(); - }); - - it('rejects submitting a transaction this server balanced, but not fee-only', async () => { - const submit = vi.fn(); - const opts: ApprovalOptions = { approveAll: true }; - const { connector } = feeWallet({ submitTransaction: submit }, opts); - - const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('agent')) as any; - delete opts.approveAll; - opts.approveFees = true; - const err: any = await connector.handlers.submitTransaction({ tx: balanced.tx }, ctx('agent')).catch((e: any) => e); - - expect(err.code).toBe('Rejected'); - // The agent learns why, not just that it was refused. - expect(err.message).toBe('User rejected the request: this fee wallet (--approve-fees) approves without the operator only ' - + "paying the Dust fee for an agent's own transaction and submitting a transaction it balanced that way on the same connection"); - expect(submit).not.toHaveBeenCalled(); - }); - - it.each([ - ['spends the wallet\'s own Night', - () => buildTx({ guaranteed: { inputs: [spend(WALLET_SK, 100n)], outputs: [pay(100n)], signers: [WALLET_SK] } }), - "intent 1 guaranteed unshielded input 0 spends this wallet's own funds"], - ['leaves an input for the wallet to sign', - () => buildTx({ guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(100n)], signers: [] } }), - 'intent 1 guaranteed unshielded input 0 is unsigned, so this wallet would sign it'], - ['leaves an output for the wallet to fund', - () => buildTx({ guaranteed: { inputs: [], outputs: [pay(100n)], signers: [] } }), - `segment 0 is short 100 of unshielded token ${NIGHT}, which a Dust-only balance can't fund`], - ])('refuses, with the reason, a transaction that %s, before balancing anything', async (_label, build, reason) => { - const balance = vi.fn(); - const { bundle, connector } = feeWallet({ balanceUnboundTransaction: balance }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(build())) }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('Rejected'); - expect(err.message).toContain('--approve-fees'); - expect(err.message).toContain(reason); - expect(balance).not.toHaveBeenCalled(); - expect(bundle.facade.adoptTransaction).not.toHaveBeenCalled(); - }); - - it('refuses payFees: false, which leaves a fee wallet nothing to do', async () => { - const balance = vi.fn(); - const { connector } = feeWallet({ balanceUnboundTransaction: balance }); - - const err: any = await connector.handlers.balanceUnsealedTransaction( - { tx: hex(await unsealedBytes(agentPaysMerchant())), options: { payFees: false } }, ctx(), - ).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain('payFees'); - expect(balance).not.toHaveBeenCalled(); - }); - - it('refuses bytes it cannot read as a ledger-9 transaction of that stage', async () => { - const balance = vi.fn(); - const { connector } = feeWallet({ balanceFinalizedTransaction: balance }); - - const err: any = await connector.handlers.balanceSealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain('sealed'); - expect(balance).not.toHaveBeenCalled(); - }); - - it('still needs a prompt for anything else, so an agent\'s makeTransfer is rejected', async () => { - const transfer = vi.fn(); - const { connector } = feeWallet({ transferTransaction: transfer }); - - const err: any = await connector.handlers.makeTransfer({ - desiredOutputs: [{ kind: 'unshielded', type: NIGHT, value: '1', recipient: UNSHIELDED_RECIPIENT }], - }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('Rejected'); - expect(transfer).not.toHaveBeenCalled(); - }); - }); - - describe('pending tx tracking (hex-based)', () => { - it('untrackPendingTx works via hex key (not object identity)', async () => { - // balanceUnsealedTransaction tracks a tx, then submitTransaction untracks by hex. - // If untracking fails, revertPendingTxs would call revertTransaction. - const revertFn = vi.fn().mockResolvedValue(undefined); - process.stderr.write = (() => true) as any; - - const bundle = createBundleStub({ - finalizeRecipe: () => Promise.resolve(finalizedTx(0x01)), - submitTransaction: () => Promise.resolve('hash-123'), - }); - (bundle.facade as any).revert = revertFn; - - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - const connId = 'conn_hex_test'; - - // Balance a tx — this tracks it - const balanceResult = await connector.handlers.balanceUnsealedTransaction( - { tx: AGENT_TX }, ctx(connId), - ) as any; - - // Submit using the hex from balance result — this untracks by hex - await connector.handlers.submitTransaction( - { tx: balanceResult.tx }, ctx(connId), - ); - - // revertPendingTxs should have nothing to revert - await connector.revertPendingTxs(connId); - expect(revertFn).not.toHaveBeenCalled(); - }); - - it('revertPendingTxs reverts tracked txs on disconnect', async () => { - const revertFn = vi.fn().mockResolvedValue(undefined); - process.stderr.write = (() => true) as any; - - const finalized = finalizedTx(0x02); - const bundle = createBundleStub({ - finalizeRecipe: () => Promise.resolve(finalized), - }); - (bundle.facade as any).revert = revertFn; - - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - const connId = 'conn_revert_test'; - await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx(connId)); - - // Disconnect reverts the FINALIZED transaction: that releases its coins in - // all three wallets and clears its pending entry (the recipe would not). - await connector.revertPendingTxs(connId); - expect(revertFn).toHaveBeenCalledTimes(1); - expect(revertFn).toHaveBeenCalledWith(finalized); - }); - - it('submitTransaction rejection reverts and untracks', async () => { - const revertFn = vi.fn().mockResolvedValue(undefined); - const origIsTTY = process.stdin.isTTY; - process.stderr.write = (() => true) as any; - - const finalized = finalizedTx(0x03); - const bundle = createBundleStub({ - finalizeRecipe: () => Promise.resolve(finalized), - }); - (bundle.facade as any).revert = revertFn; - - // Use a single connector — approvalOptions is a mutable object reference. - // Balance with approveAll, then remove it so submit rejects via non-TTY. - const opts: Record = { approveAll: true }; - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: opts, - }); - - const connId = 'conn_reject_test'; - - // Balance first (auto-approved via approveAll) — tracks the tx internally - const balanceResult = await connector.handlers.balanceUnsealedTransaction( - { tx: AGENT_TX }, ctx(connId), - ) as any; - - // Switch: remove approveAll + non-TTY → submit will be rejected - delete opts.approveAll; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - - // Submit on the SAME connector → rejection → reverts the finalized tx - await expect(connector.handlers.submitTransaction({ tx: balanceResult.tx }, ctx(connId))) - .rejects.toMatchObject({ code: 'Rejected' }); - - expect(revertFn).toHaveBeenCalledWith(finalized); - // Untracked: a later disconnect has nothing left to revert. - revertFn.mockClear(); - await connector.revertPendingTxs(connId); - expect(revertFn).not.toHaveBeenCalled(); - - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - }); - }); - - describe('a dApp transaction the wallet SDK cannot sign correctly', () => { - // wallet-sdk 2.0.0-rc.0 duplicates the signatures already on an offer it - // signs, so one with both signed and unsigned inputs can't be signed. - const partlySigned = async () => Buffer.from(await unsealedBytes(buildTx({ - guaranteed: { inputs: [spend(AGENT_SK, 60n, 0)], outputs: [pay(60n)], signers: [AGENT_SK] }, - fallible: { inputs: [spend(WALLET_SK, 40n, 1)], outputs: [pay(40n)], signers: [] }, - }))).toString('hex'); - - it('is refused as InvalidRequest before the operator is asked and before anything is balanced', async () => { - const balance = vi.fn(); - const bundle = createBundleStub({ balanceUnboundTransaction: balance }); - // No approveAll and no TTY: reaching the approval step would fail as Rejected instead. - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: {} }); - const origIsTTY = process.stdin.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - try { - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: await partlySigned() }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain('both signed and unsigned unshielded inputs'); - expect(balance).not.toHaveBeenCalled(); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - } - }); - - // Signed by the agent, 40 Night over: unshielded balancing would merge an - // output for it into the agent's intent, invalidating the agent's signature. - const signedWithSurplus = async () => Buffer.from(await unsealedBytes(buildTx({ - guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(60n)], signers: [AGENT_SK] }, - }))).toString('hex'); - - it.each([ - ['every token kind (the default)', undefined], - ['all but Dust (payFees: false)', { payFees: false }], - ])('a signed transaction that needs unshielded balancing is refused as InvalidRequest when balancing %s', async (_mode, options) => { - const balance = vi.fn(); - connector = createConnector({ bundleOverrides: { balanceUnboundTransaction: balance } }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: await signedWithSurplus(), options }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain('segment 0 is not balanced in unshielded value'); - expect(balance).not.toHaveBeenCalled(); - }); - - it('the same transaction goes on to a Dust-only balance on a fee wallet, which adds nothing to its intent', async () => { - const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const bundle = createBundleStub({ balanceUnboundTransaction: balance }); - (bundle.keystore as any).getPublicKey = () => WALLET_VK; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveFees: true, autoApproveReads: true } }); - - await connector.handlers.balanceUnsealedTransaction({ tx: await signedWithSurplus() }, ctx()); - - expect(balance).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ tokenKindsToBalance: ['dust'] })); - }); - - it('a partly signed transaction found only at signing is still InvalidRequest, with its recipe reverted', async () => { - const recipe = { type: 'RECIPE' }; - const revertFn = vi.fn().mockResolvedValue(undefined); - const bundle = createBundleStub({ - balanceUnboundTransaction: () => Promise.resolve(recipe), - signRecipe: () => Promise.reject(new PartlySignedTransactionError()), - }); - (bundle.facade as any).revert = revertFn; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toContain('both signed and unsigned unshielded inputs'); - expect(revertFn).toHaveBeenCalledWith(recipe); - }); - }); - - describe('balancing on a server started without --approve-all or --approve-fees', () => { - // Found live: a dApp asked plain `mn serve` (no terminal) to balance a spend - // of the wallet's own NIGHT and got back a sealed transaction carrying the - // wallet's valid signature, which it could submit through any node. - it.each([ - ['balanceUnsealedTransaction', unsealedBytes, 'balanceUnboundTransaction'], - ['balanceSealedTransaction', sealedBytes, 'balanceFinalizedTransaction'], - ] as const)('%s prompts, so with no terminal a spend of the wallet\'s own NIGHT is rejected before anything is balanced or signed', async (method, toBytes, balanceMethod) => { - const walletSpend = Buffer.from(await toBytes(buildTx({ - guaranteed: { inputs: [spend(WALLET_SK, 990n)], outputs: [pay(990n)], signers: [] }, - }))).toString('hex'); - const balance = vi.fn(); - const bundle = createBundleStub({ [balanceMethod]: balance }); - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { autoApproveReads: true } }); - const origIsTTY = process.stdin.isTTY; - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); - try { - const err: any = await connector.handlers[method]({ tx: walletSpend }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('Rejected'); - expect(balance).not.toHaveBeenCalled(); - expect(bundle.facade.signRecipe).not.toHaveBeenCalled(); - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); - } - }); - }); - - describe('an expired dApp transaction', () => { - it.each([ - ['balanceUnsealedTransaction', unsealedBytes, 'balanceUnboundTransaction'], - ['balanceSealedTransaction', sealedBytes, 'balanceFinalizedTransaction'], - ] as const)('%s refuses it as InvalidRequest, naming the intent and its TTL, before balancing', async (method, toBytes, sdkMethod) => { - // A whole second: the ledger keeps an intent's TTL to the second. - const ttl = new Date(Math.floor(Date.now() / 1000) * 1000 - 60_000); - const agentPaidAMinuteTooLate = buildTx({ guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(100n)], signers: [AGENT_SK] } }, ttl); - const expired = Buffer.from(await toBytes(agentPaidAMinuteTooLate)).toString('hex'); - const balance = vi.fn(); - connector = createConnector({ bundleOverrides: { [sdkMethod]: balance } }); - - const err: any = await (connector.handlers as any)[method]({ tx: expired }, ctx()).catch((e: any) => e); - - expect(err.code).toBe('InvalidRequest'); - expect(err.message).toBe(`The transaction has expired: intent 1's TTL (${ttl.toISOString()}) has passed. Build it again with a later TTL.`); - expect(balance).not.toHaveBeenCalled(); - }); - }); - - describe('failed signing', () => { - it('reverts the recipe so its coins are not held until the TTL', async () => { - const recipe = { type: 'RECIPE' }; - const revertFn = vi.fn().mockResolvedValue(undefined); - const bundle = createBundleStub({ - balanceUnboundTransaction: () => Promise.resolve(recipe), - signRecipe: () => Promise.reject(new Error('signer unavailable')), - }); - (bundle.facade as any).revert = revertFn; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toThrow('signer unavailable'); - expect(revertFn).toHaveBeenCalledWith(recipe); - expect(bundle.facade.finalizeRecipe).not.toHaveBeenCalled(); - }); - }); - - describe('failed proving', () => { - it('reverts the recipe so its coins are not held until the TTL', async () => { - const recipe = { type: 'RECIPE' }; - const revertFn = vi.fn().mockResolvedValue(undefined); - const bundle = createBundleStub({ - balanceUnboundTransaction: () => Promise.resolve(recipe), - finalizeRecipe: () => Promise.reject(new Error('proof server unreachable')), - }); - (bundle.facade as any).revert = revertFn; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toThrow('proof server unreachable'); - expect(revertFn).toHaveBeenCalledWith(recipe); - }); - - it('also reverts a proof that finishes after the timeout, so no stale pending tx is left', async () => { - vi.useFakeTimers(); - try { - const recipe = { type: 'RECIPE' }; - const late = finalizedTx(0x09); - let finishProof!: (tx: unknown) => void; - const revertFn = vi.fn().mockResolvedValue(undefined); - const bundle = createBundleStub({ - balanceUnboundTransaction: () => Promise.resolve(recipe), - finalizeRecipe: () => new Promise((resolve) => { finishProof = resolve; }), - }); - (bundle.facade as any).revert = revertFn; - connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); - - const call = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - const outcome = expect(call).rejects.toThrow('ZK proof generation timed out'); - await vi.advanceTimersByTimeAsync(PROOF_TIMEOUT_MS + 1); - await outcome; - expect(revertFn).toHaveBeenCalledWith(recipe); - - // The SDK registers the finalized tx as pending when the proof lands. - finishProof(late); - await vi.advanceTimersByTimeAsync(0); - expect(revertFn).toHaveBeenCalledWith(late); - } finally { - vi.useRealTimers(); - } - }); - }); - - // ── Abandon timer ── - - describe('abandon timer', () => { - it('auto-reverts after timeout', async () => { - vi.useFakeTimers(); - const revertFn = vi.fn().mockResolvedValue(undefined); - process.stderr.write = (() => true) as any; - - const bundle = createBundleStub({ - finalizeRecipe: () => Promise.resolve(finalizedTx(0x04)), - }); - (bundle.facade as any).revert = revertFn; - - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - const connId = 'conn_abandon'; - await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx(connId)); - - // Advance past ABANDONED_TX_TIMEOUT_MS (120_000ms) - await vi.advanceTimersByTimeAsync(121_000); - - // Timer fires and reverts the abandoned tx - expect(revertFn).toHaveBeenCalledTimes(1); - - vi.useRealTimers(); - }); - - it('dispose clears abandon timers', async () => { - vi.useFakeTimers(); - const revertFn = vi.fn().mockResolvedValue(undefined); - process.stderr.write = (() => true) as any; - - const bundle = createBundleStub({ - finalizeRecipe: () => Promise.resolve(finalizedTx(0x05)), - }); - (bundle.facade as any).revert = revertFn; - - connector = createDAppConnector({ - bundle, - networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, - }); - - await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('conn_dispose')); - - // Dispose before timeout fires - connector.dispose(); - connector = undefined; - - await vi.advanceTimersByTimeAsync(121_000); - expect(revertFn).not.toHaveBeenCalled(); - - vi.useRealTimers(); - }); - }); +import { connectorSuite } from './helpers/connector-suite.ts'; + +connectorSuite({ + set: 'rc', + createDAppConnector, + signatureScheme, + toHistoryEntry, + PartlySignedTransactionError, + deriveUnshieldedAddress, + deriveAllShieldedAddresses, + deriveShieldedAddress, + DustAddress, + UnshieldedAddress, + MidnightBech32m, + ledger, + createKeystore, + SubmissionError, + ledger9ProtocolVersion: FORK_SCHEDULE.v9, + // The rc SDK reads a dApp's transaction through adoptTransaction, which the stub answers with its stage and hex. + readsThroughFacade: true, + handleHex: (handle: { hex?: string; serialize?: () => Uint8Array }) => handle.hex ?? Buffer.from(handle.serialize!()).toString('hex'), }); diff --git a/src/__tests__/engine-beta-dapp-connector.test.ts b/src/__tests__/engine-beta-dapp-connector.test.ts new file mode 100644 index 00000000..3ee79f42 --- /dev/null +++ b/src/__tests__/engine-beta-dapp-connector.test.ts @@ -0,0 +1,43 @@ +// The DApp connector's tests over the beta engine (stagenet). The tests are +// the suite both engines run: helpers/connector-suite.ts. The SDK pieces come +// from the beta engine's own copies, as its connector resolves them; the +// repository's root holds the rc set's. + +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { createDAppConnector, signatureScheme, toHistoryEntry } from '@kuiralabs/midnight-engine-beta/dapp-connector'; +import { PartlySignedTransactionError } from '@kuiralabs/midnight-engine-beta/sign-recipe'; +import { deriveAllShieldedAddresses, deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-beta/derive-address'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { connectorSuite } from './helpers/connector-suite.ts'; + +const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +/** A module of a package as the beta engine resolves it. */ +const fromEngine = async (name: string, entry: string) => import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, name)!, entry)).href); + +const ledger = await fromEngine('@midnightntwrk/ledger-v9', 'midnight_ledger_wasm_v9_fs.js'); +const { DustAddress, MidnightBech32m, UnshieldedAddress } = await fromEngine('@midnightntwrk/wallet-sdk-address-format', 'dist/index.js'); +const { createKeystore } = await fromEngine('@midnightntwrk/wallet-sdk-unshielded-wallet', 'dist/index.js'); +const { SubmissionError } = await fromEngine('@midnightntwrk/wallet-sdk-capabilities', 'dist/submission/index.js'); + +connectorSuite({ + set: 'beta', + createDAppConnector, + signatureScheme, + toHistoryEntry, + PartlySignedTransactionError, + deriveUnshieldedAddress, + deriveAllShieldedAddresses, + deriveShieldedAddress, + DustAddress, + UnshieldedAddress, + MidnightBech32m, + ledger, + createKeystore, + SubmissionError, + // The beta facade takes the wallet's secret keys on every call that spends. + secretKeys: { shieldedSecretKeys: { tag: 'zswap' }, dustSecretKey: { tag: 'dust' } }, + // The beta engine reads a dApp's transaction with its ledger and hands the facade that. + readsThroughFacade: false, + handleHex: (handle: { serialize(): Uint8Array }) => Buffer.from(handle.serialize()).toString('hex'), +}); diff --git a/src/__tests__/helpers/connector-stub.ts b/src/__tests__/helpers/connector-stub.ts index cd5f43e5..e3280487 100644 --- a/src/__tests__/helpers/connector-stub.ts +++ b/src/__tests__/helpers/connector-stub.ts @@ -1,26 +1,38 @@ // The wallet SDK's facade, stubbed at the SDK boundary, and the DApp connector -// over it: shared by the connector's tests and the wallet session's. +// over it: shared by the connector's tests and the wallet session's. Built +// over an engine's own pieces (`connectorStub`), so it loads no engine itself: +// a test file loads one engine at most. import { vi } from 'vitest'; import * as rx from 'rxjs'; -import { createDAppConnector, type DAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; -import type { FacadeBundle } from '@kuiralabs/midnight-engine-rc/facade'; -import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { DustAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; +import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -/** The wallet's own addresses, as SDK address objects in its state. */ -export const WALLET_SHIELDED = deriveShieldedAddress(Buffer.from('00'.repeat(31) + '07', 'hex')); -export const WALLET_UNSHIELDED = new UnshieldedAddress(Buffer.alloc(32, 7)); -export const WALLET_DUST = new DustAddress(7n); +/** A DApp connector, as both engines make one. */ +export interface StubConnector { + handlers: Record Promise>; + dispose(): void; + revertPendingTxs(connectionId: string): Promise; +} + +/** What the stub takes from an engine. */ +export interface StubEngine { + createDAppConnector(options: any): StubConnector; + deriveShieldedAddress(seed: Buffer): any; + DustAddress: new (data: bigint) => any; + UnshieldedAddress: new (data: Buffer) => any; + /** The wallet's secret keys, on an engine whose facade takes them on every call that spends. */ + secretKeys?: unknown; + /** The protocol version each wallet reports once on ledger 9, on an engine whose state reports one. */ + ledger9ProtocolVersion?: bigint; + /** What finalizeRecipe gives back unless a test says otherwise. */ + finalized?: () => unknown; +} /** A finalized transaction handle as the SDK returns it: it serializes to these bytes. */ export const finalizedTx = (...bytes: number[]) => ({ serialize: () => new Uint8Array(bytes) }); - - export const TEST_NETWORK_CONFIG: NetworkConfig = { indexer: 'http://localhost:8088/api/v4/graphql', indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', @@ -29,35 +41,6 @@ export const TEST_NETWORK_CONFIG: NetworkConfig = { networkId: 'Undeployed', }; -/** Create a minimal mock FacadeState. */ -export function mockState(overrides?: { - unshieldedBalances?: Record; - shieldedBalances?: Record; - dustBalance?: bigint; - protocolVersion?: { shielded: bigint; unshielded: bigint; dust: bigint }; - isSynced?: boolean; -}) { - return { - isSynced: overrides?.isSynced ?? true, - // Each wallet's protocol version, as FacadeState reports it: on ledger 9 unless a test says otherwise. - protocolVersion: overrides?.protocolVersion ?? { shielded: FORK_SCHEDULE.v9, unshielded: FORK_SCHEDULE.v9, dust: FORK_SCHEDULE.v9 }, - unshielded: { - balances: overrides?.unshieldedBalances ?? { '0000000000000000000000000000000000000000000000000000000000000000': 5000000n }, - address: WALLET_UNSHIELDED, - progress: { appliedId: 1n, highestTransactionId: 1n }, - }, - shielded: { - balances: overrides?.shieldedBalances ?? {}, - address: WALLET_SHIELDED, - }, - dust: { - balance: (_time: Date) => overrides?.dustBalance ?? 1000n, - availableCoins: [], - address: WALLET_DUST, - }, - }; -} - /** Wallet history as the SDK records it: one finalized, one rejected, one pending. */ export const HISTORY = [ { hash: 'tx-hash-001', identifiers: [], status: 'SUCCESS', lifecycle: { status: 'finalized', finalizedBlock: { hash: 'b1', height: 1, timestamp: new Date(0) } } }, @@ -65,53 +48,98 @@ export const HISTORY = [ { hash: 'tx-hash-003', identifiers: [], lifecycle: { status: 'pending', submittedAt: new Date(0) } }, ]; -/** Create a minimal FacadeBundle stub. */ -export function createBundleStub(overrides?: { +export interface BundleOverrides { stateFn?: () => rx.Observable; - transferTransaction?: () => Promise; - signRecipe?: () => Promise; - finalizeRecipe?: () => Promise; - submitTransaction?: () => Promise; - balanceUnboundTransaction?: () => Promise; - balanceFinalizedTransaction?: () => Promise; - initSwap?: () => Promise; + transferTransaction?: (...args: any[]) => Promise; + signRecipe?: (...args: any[]) => Promise; + finalizeRecipe?: (...args: any[]) => Promise; + submitTransaction?: (...args: any[]) => Promise; + balanceUnboundTransaction?: (...args: any[]) => Promise; + balanceFinalizedTransaction?: (...args: any[]) => Promise; + initSwap?: (...args: any[]) => Promise; getAllFromTxHistory?: () => Promise; estimateTransactionFee?: (...args: any[]) => Promise; -}): FacadeBundle { - const defaultStateFn = () => rx.of(mockState()); - - return { - facade: { - state: overrides?.stateFn ?? defaultStateFn, - start: vi.fn().mockResolvedValue(undefined), - stop: vi.fn().mockResolvedValue(undefined), - transferTransaction: overrides?.transferTransaction ?? vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }), - signRecipe: overrides?.signRecipe ?? vi.fn().mockResolvedValue({ type: 'SIGNED' }), - finalizeRecipe: overrides?.finalizeRecipe ?? vi.fn().mockResolvedValue(finalizedTx(0xab, 0xcd)), - submitTransaction: overrides?.submitTransaction ?? vi.fn().mockResolvedValue('mock-tx-hash'), - balanceUnboundTransaction: overrides?.balanceUnboundTransaction ?? vi.fn().mockResolvedValue({ type: 'UNBOUND' }), - balanceFinalizedTransaction: overrides?.balanceFinalizedTransaction ?? vi.fn().mockResolvedValue({ type: 'FINALIZED' }), - initSwap: overrides?.initSwap ?? vi.fn().mockResolvedValue({ type: 'SWAP' }), - registerNightUtxosForDustGeneration: vi.fn(), - adoptTransaction: vi.fn((bytes: Uint8Array, stage: string) => ({ stage, hex: Buffer.from(bytes).toString('hex') })), - estimateTransactionFee: overrides?.estimateTransactionFee ?? vi.fn().mockResolvedValue(1_000n), - getAllFromTxHistory: overrides?.getAllFromTxHistory ?? vi.fn().mockResolvedValue(HISTORY), - }, - keystore: { - signDataAsync: vi.fn().mockResolvedValue({ tag: 'schnorr', value: 'abcd1234signature' }), - getPublicKey: vi.fn().mockReturnValue({ tag: 'schnorr', value: '5678efghpubkey' }), - }, - } as unknown as FacadeBundle; } -export function createConnector(overrides?: { - bundleOverrides?: Parameters[0]; - networkConfig?: NetworkConfig; - approvalOptions?: ApprovalOptions; -}): DAppConnector { - return createDAppConnector({ - bundle: createBundleStub(overrides?.bundleOverrides), - networkConfig: overrides?.networkConfig ?? TEST_NETWORK_CONFIG, - approvalOptions: overrides?.approvalOptions ?? { approveAll: true }, - }); +/** The facade stub and connector over `engine`'s pieces. */ +export function connectorStub(engine: StubEngine) { + /** The wallet's own addresses, as SDK address objects in its state. */ + const WALLET_SHIELDED = engine.deriveShieldedAddress(Buffer.from('00'.repeat(31) + '07', 'hex')); + const WALLET_UNSHIELDED = new engine.UnshieldedAddress(Buffer.alloc(32, 7)); + const WALLET_DUST = new engine.DustAddress(7n); + + /** Create a minimal mock FacadeState. */ + function mockState(overrides?: { + unshieldedBalances?: Record; + shieldedBalances?: Record; + dustBalance?: bigint; + protocolVersion?: { shielded: bigint; unshielded: bigint; dust: bigint }; + isSynced?: boolean; + }) { + const v9 = engine.ledger9ProtocolVersion; + return { + isSynced: overrides?.isSynced ?? true, + // Each wallet's protocol version, as the rc SDK's FacadeState reports it: on ledger 9 unless a test says otherwise. + ...(v9 !== undefined ? { protocolVersion: overrides?.protocolVersion ?? { shielded: v9, unshielded: v9, dust: v9 } } : {}), + unshielded: { + balances: overrides?.unshieldedBalances ?? { '0000000000000000000000000000000000000000000000000000000000000000': 5000000n }, + address: WALLET_UNSHIELDED, + progress: { appliedId: 1n, highestTransactionId: 1n }, + }, + shielded: { + balances: overrides?.shieldedBalances ?? {}, + address: WALLET_SHIELDED, + }, + dust: { + balance: (_time: Date) => overrides?.dustBalance ?? 1000n, + availableCoins: [], + address: WALLET_DUST, + }, + }; + } + + /** Create a minimal FacadeBundle stub. */ + function createBundleStub(overrides?: BundleOverrides): any { + const defaultStateFn = () => rx.of(mockState()); + const finalized = engine.finalized ?? (() => finalizedTx(0xab, 0xcd)); + + return { + facade: { + state: overrides?.stateFn ?? defaultStateFn, + start: vi.fn().mockResolvedValue(undefined), + stop: vi.fn().mockResolvedValue(undefined), + transferTransaction: overrides?.transferTransaction ?? vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }), + signRecipe: overrides?.signRecipe ?? vi.fn().mockResolvedValue({ type: 'SIGNED' }), + finalizeRecipe: overrides?.finalizeRecipe ?? vi.fn().mockImplementation(async () => finalized()), + submitTransaction: overrides?.submitTransaction ?? vi.fn().mockResolvedValue('mock-tx-hash'), + balanceUnboundTransaction: overrides?.balanceUnboundTransaction ?? vi.fn().mockResolvedValue({ type: 'UNBOUND' }), + balanceFinalizedTransaction: overrides?.balanceFinalizedTransaction ?? vi.fn().mockResolvedValue({ type: 'FINALIZED' }), + initSwap: overrides?.initSwap ?? vi.fn().mockResolvedValue({ type: 'SWAP' }), + registerNightUtxosForDustGeneration: vi.fn(), + // The rc SDK's reader; the beta engine reads with its ledger and never calls it. + adoptTransaction: vi.fn((bytes: Uint8Array, stage: string) => ({ stage, hex: Buffer.from(bytes).toString('hex') })), + estimateTransactionFee: overrides?.estimateTransactionFee ?? vi.fn().mockResolvedValue(1_000n), + getAllFromTxHistory: overrides?.getAllFromTxHistory ?? vi.fn().mockResolvedValue(HISTORY), + }, + keystore: { + signDataAsync: vi.fn().mockResolvedValue({ tag: 'schnorr', value: 'abcd1234signature' }), + getPublicKey: vi.fn().mockReturnValue({ tag: 'schnorr', value: '5678efghpubkey' }), + }, + ...(engine.secretKeys !== undefined ? { secretKeys: engine.secretKeys } : {}), + }; + } + + function createConnector(overrides?: { + bundleOverrides?: BundleOverrides; + networkConfig?: NetworkConfig; + approvalOptions?: ApprovalOptions; + }): StubConnector { + return engine.createDAppConnector({ + bundle: createBundleStub(overrides?.bundleOverrides), + networkConfig: overrides?.networkConfig ?? TEST_NETWORK_CONFIG, + approvalOptions: overrides?.approvalOptions ?? { approveAll: true }, + }); + } + + return { WALLET_SHIELDED, WALLET_UNSHIELDED, WALLET_DUST, mockState, createBundleStub, createConnector }; } diff --git a/src/__tests__/helpers/connector-suite.ts b/src/__tests__/helpers/connector-suite.ts new file mode 100644 index 00000000..87b5c61d --- /dev/null +++ b/src/__tests__/helpers/connector-suite.ts @@ -0,0 +1,1938 @@ +// The DApp connector's tests, over either SDK engine: each engine has its own +// copy of the connector, and both must behave the same way to a dApp. The +// facade is stubbed at the SDK boundary (per CLAUDE.md: no mocks of our own +// code); the dApp's transactions are real ledger-9 transactions built with the +// engine's own copy of the ledger, and so are the finalized transactions the +// stub facade gives back. Where the engines differ (the rc SDK reads a dApp's +// transaction through its facade and waits for the ledger-9 fork; the beta +// engine reads it with its ledger and passes the wallet's secret keys), the +// tests say which. +// +// This file loads no engine: each test file that runs it passes one. + +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import * as rx from 'rxjs'; +// The wallet SDK's copy of Effect (both engines' SDKs share it): its submit runs on it. +import { Effect } from 'effect'; +import { HISTORY, TEST_NETWORK_CONFIG, connectorStub, type BundleOverrides, type StubConnector, type StubEngine } from './connector-stub.ts'; +import { startLocalIndexer, type LocalIndexer } from './local-indexer.ts'; +import { ledgerTx, type Ledger } from './ledger-tx.ts'; +import type { SignatureVerifyingKey } from '@midnightntwrk/ledger-v9'; +import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; +import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; +import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; + +/** What the suite takes from an engine. */ +export interface ConnectorEngine extends StubEngine { + /** The SDK set, as the suite's title names it. */ + set: string; + signatureScheme(tag: string): string; + toHistoryEntry(entry: any, segments?: readonly any[]): unknown; + PartlySignedTransactionError: new () => Error; + deriveUnshieldedAddress(seed: Buffer, network: NetworkName): string; + deriveAllShieldedAddresses(seed: Buffer): Record; + MidnightBech32m: { parse(address: string): { decode(type: any, network: string): any }; encode(network: string, address: any): { asString(): string } }; + /** The engine's own copy of ledger-v9. */ + ledger: Ledger; + createKeystore(secret: { kind: 'schnorr'; secret: Uint8Array }, network: string): { getPublicKey(): SignatureVerifyingKey; signDataAsync(data: Uint8Array): Promise }; + SubmissionError: new (args: { message: string; cause?: unknown }) => Error; + /** Whether the engine reads a dApp's transaction through the facade's adoptTransaction (the rc SDK's reader) rather than with its ledger. */ + readsThroughFacade: boolean; + /** The hex of a transaction handle the engine passed to the facade. */ + handleHex(handle: any): string; +} + +/** The connector's tests over `engine`. */ +export function connectorSuite(engine: ConnectorEngine): void { + const { NIGHT, WALLET_SK, AGENT_SK, WALLET_VK, spend, pay, buildTx, agentPaysMerchant, unsealedBytes, sealedBytes } = ledgerTx(engine.ledger); + + /** Sealed transactions to pay `n` Night, as bytes: what the stub facade finalizes, one per test that needs them told apart. */ + const SEALED = new Map(); + /** A finalized transaction handle as the SDK returns it, read with the engine's ledger. */ + const sealedTx = (n: number) => engine.ledger.Transaction.deserialize('signature', 'proof', 'binding', SEALED.get(n)!); + const sealedHex = (n: number) => Buffer.from(SEALED.get(n)!).toString('hex'); + /** What the stub facade finalizes unless a test says otherwise: not the dApp's own transaction (100 Night), so the two are never confused. */ + const FINALIZED = 7; + let FINALIZED_HEX: string; + + const { WALLET_SHIELDED, WALLET_UNSHIELDED, mockState, createBundleStub, createConnector } = connectorStub({ ...engine, finalized: () => sealedTx(FINALIZED) }); + + /** Real undeployed addresses for a fixed seed, so outputs decode as they would from a dApp. */ + const RECIPIENT_SEED = Buffer.from('00'.repeat(31) + '42', 'hex'); + const UNSHIELDED_RECIPIENT = engine.deriveUnshieldedAddress(RECIPIENT_SEED, 'undeployed'); + const SHIELDED_RECIPIENT = engine.deriveAllShieldedAddresses(RECIPIENT_SEED).undeployed; + + + /** Mock handler context with no-op notify */ + const ctx = (connectionId = 'conn_test'): RpcHandlerContext => ({ notify: vi.fn(), connectionId, requestId: 1, metadata: {} }); + + // ── Tests ──────────────────────────────────────────────────────────── + + /** A real unsealed ledger-9 dApp transaction (the agent pays from its own signed input), as hex. */ + let AGENT_TX: string; + /** The same payment sealed (bound), as balanceSealedTransaction takes it. */ + let SEALED_AGENT_TX: string; + + beforeAll(async () => { + AGENT_TX = Buffer.from(await unsealedBytes(agentPaysMerchant())).toString('hex'); + SEALED_AGENT_TX = Buffer.from(await sealedBytes(agentPaysMerchant())).toString('hex'); + for (const n of [1, 2, 3, 4, 5, 6, 9, FINALIZED]) SEALED.set(n, await sealedBytes(agentPaysMerchant(BigInt(n)))); + FINALIZED_HEX = sealedHex(FINALIZED); + }); + + describe(`dapp-connector (${engine.set} engine)`, () => { + let connector: StubConnector | undefined; + let origStderrWrite: typeof process.stderr.write; + + beforeEach(() => { + origStderrWrite = process.stderr.write; + }); + + afterEach(() => { + // Always restore stderr first, even if dispose throws + process.stderr.write = origStderrWrite; + connector?.dispose(); + connector = undefined; + }); + + describe('createDAppConnector', () => { + it('throws for unknown networkId', () => { + expect(() => createConnector({ + networkConfig: { ...TEST_NETWORK_CONFIG, networkId: 'Mainnet' }, + })).toThrow('Unknown networkId: Mainnet'); + }); + + it('returns all 18 handler methods', () => { + connector = createConnector(); + const methods = Object.keys(connector.handlers); + expect(methods).toContain('connect'); + expect(methods).toContain('getUnshieldedBalances'); + expect(methods).toContain('getShieldedBalances'); + expect(methods).toContain('getDustBalance'); + expect(methods).toContain('getUnshieldedAddress'); + expect(methods).toContain('getShieldedAddresses'); + expect(methods).toContain('getDustAddress'); + expect(methods).toContain('getTxHistory'); + expect(methods).toContain('getConfiguration'); + expect(methods).toContain('getConnectionStatus'); + expect(methods).toContain('makeTransfer'); + expect(methods).toContain('submitTransaction'); + expect(methods).toContain('balanceUnsealedTransaction'); + expect(methods).toContain('balanceSealedTransaction'); + expect(methods).toContain('makeIntent'); + expect(methods).toContain('signData'); + expect(methods).toContain('getProvingProvider'); + expect(methods).toContain('hintUsage'); + expect(methods.length).toBe(18); + }); + + it('dispose() unsubscribes from state', () => { + const subject = new rx.BehaviorSubject(mockState()); + connector = createConnector({ + bundleOverrides: { stateFn: () => subject.asObservable() }, + }); + expect(subject.observed).toBe(true); + connector.dispose(); + expect(subject.observed).toBe(false); + connector = undefined; // Already disposed + }); + }); + + // ── Handshake ── + + describe('connect', () => { + it('returns networkId on match', async () => { + connector = createConnector(); + const result = await connector.handlers.connect({ networkId: 'Undeployed' }, ctx()); + expect(result).toEqual({ networkId: 'Undeployed' }); + }); + + it('matches case-insensitively', async () => { + connector = createConnector(); + const result = await connector.handlers.connect({ networkId: 'undeployed' }, ctx()); + expect(result).toEqual({ networkId: 'Undeployed' }); + }); + + it('throws InvalidRequest on network mismatch', async () => { + connector = createConnector(); + await expect(connector.handlers.connect({ networkId: 'PreProd' }, ctx())) + .rejects.toThrow('Network mismatch'); + }); + + it('throws InvalidRequest when networkId is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.connect({}, ctx())) + .rejects.toThrow('Network mismatch'); + }); + }); + + // ── Read-Only Methods ── + + describe('getUnshieldedBalances', () => { + it('returns balances from state', async () => { + const balances = { 'token-a': 100n, 'token-b': 200n }; + connector = createConnector({ + bundleOverrides: { stateFn: () => rx.of(mockState({ unshieldedBalances: balances })) }, + }); + const result = await connector.handlers.getUnshieldedBalances({}, ctx()); + expect(result).toEqual(balances); + }); + }); + + describe('getShieldedBalances', () => { + it('returns balances from state', async () => { + const balances = { 'shielded-token': 999n }; + connector = createConnector({ + bundleOverrides: { stateFn: () => rx.of(mockState({ shieldedBalances: balances })) }, + }); + const result = await connector.handlers.getShieldedBalances({}, ctx()); + expect(result).toEqual(balances); + }); + }); + + describe('getDustBalance', () => { + it('returns { cap, balance } with balance from state.dust.balance()', async () => { + connector = createConnector({ + bundleOverrides: { stateFn: () => rx.of(mockState({ dustBalance: 42000n })) }, + }); + const result = await connector.handlers.getDustBalance({}, ctx()) as any; + expect(result.balance).toBe(42000n); + expect(result.cap).toBe(42000n); + }); + }); + + describe('getTxHistory', () => { + it('returns entries with correct TxStatus object shape', async () => { + connector = createConnector(); + const result = await connector.handlers.getTxHistory({ pageNumber: 0, pageSize: 10 }, ctx()) as any[]; + expect(result).toEqual([ + { txHash: 'tx-hash-001', txStatus: { status: 'finalized', executionStatus: { 0: 'Success' } } }, + { txHash: 'tx-hash-002', txStatus: { status: 'discarded' } }, + { txHash: 'tx-hash-003', txStatus: { status: 'pending' } }, + ]); + }); + + it('paginates correctly', async () => { + connector = createConnector(); + const result = await connector.handlers.getTxHistory({ pageNumber: 0, pageSize: 1 }, ctx()) as any[]; + expect(result).toHaveLength(1); + expect(result[0].txHash).toBe('tx-hash-001'); + }); + + it('returns page 2', async () => { + connector = createConnector(); + const result = await connector.handlers.getTxHistory({ pageNumber: 1, pageSize: 1 }, ctx()) as any[]; + expect(result).toHaveLength(1); + expect(result[0].txHash).toBe('tx-hash-002'); + }); + + it.each([ + [{ pageNumber: -1 }, 'Invalid pageNumber: -1'], + [{ pageNumber: 1.5 }, 'Invalid pageNumber: 1.5'], + [{ pageNumber: '1' }, 'Invalid pageNumber: "1"'], + [{ pageSize: 0 }, 'Invalid pageSize: 0'], + [{ pageSize: -5 }, 'Invalid pageSize: -5'], + [{ pageSize: 'all' }, 'Invalid pageSize: "all"'], + ])('refuses paging %o as InvalidRequest before reading the history', async (paging, message) => { + const history = vi.fn().mockResolvedValue(HISTORY); + connector = createConnector({ bundleOverrides: { getAllFromTxHistory: history } }); + + const err: any = await connector.handlers.getTxHistory(paging, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain(message); + expect(history).not.toHaveBeenCalled(); + }); + + it('returns an empty page past the end of the history', async () => { + connector = createConnector(); + const result = await connector.handlers.getTxHistory({ pageNumber: 5, pageSize: 1 }, ctx()); + expect(result).toEqual([]); + }); + + describe('execution status of finalized transactions', () => { + const finalized = (hash: string, status?: string) => ({ + hash, identifiers: [], ...(status ? { status } : {}), + lifecycle: { status: 'finalized', finalizedBlock: { hash: 'b', height: 1, timestamp: new Date(0) } }, + }); + let indexer: LocalIndexer | undefined; + afterEach(async () => { await indexer?.close(); indexer = undefined; }); + + function connectorWith(history: unknown[], indexerUrl = TEST_NETWORK_CONFIG.indexer): StubConnector { + return engine.createDAppConnector({ + bundle: createBundleStub({ getAllFromTxHistory: () => Promise.resolve(history as any[]) }), + networkConfig: { ...TEST_NETWORK_CONFIG, indexer: indexerUrl }, + approvalOptions: { approveAll: true }, + }); + } + + it('reports a success as segment 0 succeeding and a failure as segment 0 failing, without asking the indexer', async () => { + indexer = await startLocalIndexer(() => '{}'); + connector = connectorWith([finalized('ok', 'SUCCESS'), finalized('bad', 'FAILURE'), finalized('unknown')], indexer.url); + + const result = await connector.handlers.getTxHistory({}, ctx()); + + expect(result).toEqual([ + { txHash: 'ok', txStatus: { status: 'finalized', executionStatus: { 0: 'Success' } } }, + { txHash: 'bad', txStatus: { status: 'finalized', executionStatus: { 0: 'Failure' } } }, + // No recorded outcome: none is claimed. + { txHash: 'unknown', txStatus: { status: 'finalized', executionStatus: {} } }, + ]); + expect(indexer.requests).toEqual([]); + }); + + it('reads a partial success\'s segments from the indexer, by the entry\'s hash', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ data: { transactions: [{ + __typename: 'RegularTransaction', + transactionResult: { status: 'PARTIAL_SUCCESS', segments: [{ id: 0, success: true }, { id: 1, success: true }, { id: 2, success: false }] }, + }] } })); + connector = connectorWith([finalized('ok', 'SUCCESS'), finalized('partly', 'PARTIAL_SUCCESS')], indexer.url); + + const result = await connector.handlers.getTxHistory({}, ctx()); + + expect(result).toEqual([ + { txHash: 'ok', txStatus: { status: 'finalized', executionStatus: { 0: 'Success' } } }, + { txHash: 'partly', txStatus: { status: 'finalized', executionStatus: { 0: 'Success', 1: 'Success', 2: 'Failure' } } }, + ]); + expect(indexer.requests.map((r) => r.variables)).toEqual([{ hash: 'partly' }]); + }); + + it('fails as InternalError, naming the transaction, when the indexer cannot give a partial success\'s segments', async () => { + connector = connectorWith([finalized('partly', 'PARTIAL_SUCCESS')], 'http://127.0.0.1:9/api/v4/graphql'); + + const err: any = await connector.handlers.getTxHistory({}, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InternalError'); + expect(err.message).toContain('segment results of transaction partly'); + }); + + it('toHistoryEntry refuses a partial success without its segments rather than report it as anything else', () => { + expect(() => engine.toHistoryEntry(finalized('partly', 'PARTIAL_SUCCESS') as any)).toThrow('segment results are missing'); + expect(() => engine.toHistoryEntry(finalized('partly', 'PARTIAL_SUCCESS') as any, [])).toThrow('segment results are missing'); + }); + }); + + it('defaults to pageNumber 0 and pageSize 20', async () => { + const many = Array.from({ length: 25 }, (_, i) => ({ ...HISTORY[2], hash: `h${i}` })); + connector = createConnector({ bundleOverrides: { getAllFromTxHistory: () => Promise.resolve(many) } }); + const result = await connector.handlers.getTxHistory({}, ctx()) as any[]; + expect(result.map((e) => e.txHash)).toEqual(many.slice(0, 20).map((e) => e.hash)); + }); + }); + + describe('getConfiguration', () => { + it('maps NetworkConfig fields to Configuration shape', async () => { + connector = createConnector(); + const result = await connector.handlers.getConfiguration({}, ctx()) as any; + expect(result).toEqual({ + indexerUri: 'http://localhost:8088/api/v4/graphql', + indexerWsUri: 'ws://localhost:8088/api/v4/graphql/ws', + proverServerUri: 'http://localhost:6300', + substrateNodeUri: 'ws://localhost:9944', + networkId: 'Undeployed', + }); + }); + }); + + describe('getConnectionStatus', () => { + it('returns connected status with the lowercase abstractions networkId', async () => { + // Bech32m HRPs are lowercase and addresses are encoded with the lowercase + // abstractions form ('undeployed'). getConnectionStatus must report the + // same lowercase form so dApps that round-trip the value back into + // setNetworkId() before decoding addresses don't see a case-mismatch. + connector = createConnector(); + const result = await connector.handlers.getConnectionStatus({}, ctx()); + expect(result).toEqual({ status: 'connected', networkId: 'undeployed' }); + }); + }); + + // ── Guard on transaction methods ── + + describe('transaction methods wait for the wallet', () => { + const calls = (txHex: () => string) => [ + ['balanceUnsealedTransaction', () => ({ tx: txHex() })], + ['balanceSealedTransaction', () => ({ tx: txHex() })], + ['submitTransaction', () => ({ tx: txHex() })], + ['makeTransfer', () => ({ desiredOutputs: [{ kind: 'unshielded', type: '00'.repeat(32), value: '1', recipient: 'x' }] })], + ['makeIntent', () => ({ options: { intentId: 'random', payFees: true } })], + ] as const; + const expectFacadeUntouched = (bundle: any) => { + expect(bundle.facade.adoptTransaction).not.toHaveBeenCalled(); + expect(bundle.facade.balanceUnboundTransaction).not.toHaveBeenCalled(); + expect(bundle.facade.transferTransaction).not.toHaveBeenCalled(); + expect(bundle.facade.initSwap).not.toHaveBeenCalled(); + }; + + const v9 = engine.ledger9ProtocolVersion; + if (v9 !== undefined) { + // The rc SDK's facade reads a dApp's transaction at the lowest of the + // three wallets' versions, so one wallet behind the fork would make it + // read ledger-9 bytes as ledger 8. + const DUST_BEHIND = { shielded: v9, unshielded: v9, dust: 1000300n }; + + it.each(calls(() => AGENT_TX))('%s refuses as Disconnected, naming the wallet behind the ledger-9 fork, before touching the facade', async (method, params) => { + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ protocolVersion: DUST_BEHIND })) }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err: any = await (connector.handlers as any)[method](params(), ctx()).catch((e: any) => e); + + expect(err.code).toBe('Disconnected'); + expect(err.message).toContain('still behind: dust at 1000300'); + expectFacadeUntouched(bundle); + }); + + it('accepts transactions once the lagging wallet crosses the fork', async () => { + const states = new rx.BehaviorSubject(mockState({ protocolVersion: DUST_BEHIND })); + const bundle = createBundleStub({ stateFn: () => states }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toMatchObject({ code: 'Disconnected' }); + + states.next(mockState()); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).resolves.toHaveProperty('tx'); + }); + } else { + // The beta SDK has one ledger: there is no fork to wait for, only the wallet's first state. + it.each(calls(() => AGENT_TX))('%s refuses as Disconnected before the wallet\'s first state, before touching the facade', async (method, params) => { + const bundle = createBundleStub({ stateFn: () => rx.NEVER }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err: any = await (connector.handlers as any)[method](params(), ctx()).catch((e: any) => e); + + expect(err.code).toBe('Disconnected'); + expect(err.message).toBe('Wallet not synced yet'); + expectFacadeUntouched(bundle); + }); + + it('accepts transactions once the first state comes', async () => { + const states = new rx.Subject(); + const bundle = createBundleStub({ stateFn: () => states.asObservable() }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toMatchObject({ code: 'Disconnected' }); + + states.next(mockState()); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).resolves.toHaveProperty('tx'); + }); + } + + it('does not require a strictly synced state, which an idle chain\'s dust wallet never reports', async () => { + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ isSynced: false })) }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).resolves.toHaveProperty('tx'); + }); + }); + + // ── State guard ── + + describe('state guard', () => { + it('throws Disconnected when wallet not synced', async () => { + const neverSynced = new rx.Subject(); + connector = createConnector({ + bundleOverrides: { stateFn: () => neverSynced.asObservable() }, + }); + await expect(connector.handlers.getUnshieldedBalances({}, ctx())) + .rejects.toThrow('Wallet not synced yet'); + }); + + // On preprod through Blockfrost a server that said "ready" refused reads + // for about 40 s: the wallet's next state the SDK calls synced came that late. + it('answers at once from the state the caller\'s sync ended on', async () => { + const quiet = new rx.Subject(); + const synced = { unshielded: { balances: { ['00'.repeat(32)]: 5n } } }; + connector = engine.createDAppConnector({ + bundle: createBundleStub({ stateFn: () => quiet.asObservable() }), + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + initialState: synced as any, + }); + expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 5n }); + }); + + it('moves on to each later state that is current by the caller\'s rule, not only by the SDK\'s', async () => { + const states = new rx.Subject(); + connector = engine.createDAppConnector({ + bundle: createBundleStub({ stateFn: () => states.asObservable() }), + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + initialState: { unshielded: { balances: {} } } as any, + isCurrent: (state: any) => state.caughtUp === true, + }); + // Not synced by the SDK's rule (a wallet the caller didn't sync is behind), current by the caller's. + states.next({ isSynced: false, caughtUp: true, unshielded: { balances: { ['00'.repeat(32)]: 7n } } }); + expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 7n }); + // Behind by the caller's rule: reads keep the last current state. + states.next({ isSynced: false, caughtUp: false, unshielded: { balances: { ['00'.repeat(32)]: 9n } } }); + expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 7n }); + }); + + it('throws Disconnected with correct error code', async () => { + const neverSynced = new rx.Subject(); + connector = createConnector({ + bundleOverrides: { stateFn: () => neverSynced.asObservable() }, + }); + try { + await connector.handlers.getUnshieldedBalances({}, ctx()); + expect.unreachable('should have thrown'); + } catch (err: any) { + expect(err.code).toBe('Disconnected'); + expect(err.type).toBe('DAppConnectorAPIError'); + } + }); + }); + + // ── Write method approval gating ── + + describe('write method approval', () => { + it('proceeds when approveAll is true', async () => { + connector = createConnector({ approvalOptions: { approveAll: true } }); + const result = await connector.handlers.signData({ + data: 'deadbeef', + options: { encoding: 'hex', keyType: 'unshielded' }, + }, ctx()) as any; + expect(result.data).toBe('deadbeef'); + expect(result.signature).toBe('abcd1234signature'); + expect(result.verifyingKey).toBe('5678efghpubkey'); + }); + + it('rejects when stdin is not TTY and no approveAll', async () => { + const origIsTTY = process.stdin.isTTY; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + process.stderr.write = (() => true) as any; + + try { + connector = createConnector({ approvalOptions: {} }); + await expect(connector.handlers.signData({ + data: 'deadbeef', + options: { encoding: 'hex', keyType: 'unshielded' }, + }, ctx())).rejects.toThrow('User rejected the request'); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + + it('rejects with Rejected error code', async () => { + const origIsTTY = process.stdin.isTTY; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + process.stderr.write = (() => true) as any; + + try { + connector = createConnector({ approvalOptions: {} }); + try { + await connector.handlers.submitTransaction({ tx: 'aabb' }, ctx()); + expect.unreachable('should have thrown'); + } catch (err: any) { + expect(err.code).toBe('Rejected'); + expect(err.type).toBe('DAppConnectorAPIError'); + } + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + }); + + // ── signData ── + + describe('signData', () => { + it('refuses data that is not valid in its encoding before the operator is asked', async () => { + // No approveAll and no TTY: reaching the approval step would fail as Rejected instead. + connector = createConnector({ approvalOptions: {} }); + const origIsTTY = process.stdin.isTTY; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + try { + const err: any = await connector.handlers.signData({ data: '@@@not base64@@@', options: { encoding: 'base64', keyType: 'unshielded' } }, ctx()) + .catch((e: any) => e); + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toBe('data is not valid base64 (standard alphabet, padded)'); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + + it('handles hex encoding', async () => { + const bundle = createBundleStub(); + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + const result = await connector.handlers.signData({ + data: 'cafebabe', + options: { encoding: 'hex', keyType: 'unshielded' }, + }, ctx()) as any; + + expect(result.data).toBe('cafebabe'); + expect((bundle.keystore as any).signDataAsync).toHaveBeenCalledWith( + signedMessageBytes(new Uint8Array([0xca, 0xfe, 0xba, 0xbe])) + ); + }); + + it('handles base64 encoding', async () => { + const bundle = createBundleStub(); + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + const b64Data = Buffer.from('hello world').toString('base64'); + const result = await connector.handlers.signData({ + data: b64Data, + options: { encoding: 'base64' }, + }, ctx()) as any; + + expect(result.data).toBe(b64Data); + expect((bundle.keystore as any).signDataAsync).toHaveBeenCalledWith( + signedMessageBytes(new Uint8Array(Buffer.from('hello world'))) + ); + }); + + it('handles text encoding', async () => { + const bundle = createBundleStub(); + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + const result = await connector.handlers.signData({ + data: 'sign me', + options: { encoding: 'text' }, + }, ctx()) as any; + + expect(result.data).toBe('sign me'); + expect((bundle.keystore as any).signDataAsync).toHaveBeenCalledWith( + signedMessageBytes(new Uint8Array(Buffer.from('sign me', 'utf-8'))) + ); + }); + + // The key that signs here also signs the wallet's unshielded spends, over a + // transaction's signature data. Signed as given, a dApp could send that + // signature data as its message and get back a valid spend signature. + it('signs the prefixed message, so a transaction\'s signature data sent as data gives no spend signature', async () => { + const keystore = engine.createKeystore({ kind: 'schnorr', secret: new Uint8Array(32).fill(1) }, 'undeployed'); + const vk = keystore.getPublicKey(); + expect(vk).toEqual(WALLET_VK); + const intent = engine.ledger.Intent.new(new Date(Date.UTC(2030, 0, 1))); + intent.guaranteedUnshieldedOffer = engine.ledger.UnshieldedOffer.new([spend(WALLET_SK, 990n)], [pay(990n)], []); + const spendData = intent.signatureData(1); + const bundle = createBundleStub(); + (bundle as any).keystore = keystore; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const result = await connector.handlers.signData({ + data: Buffer.from(spendData).toString('hex'), options: { encoding: 'hex', keyType: 'unshielded' }, + }, ctx()) as any; + + const signature = { tag: 'schnorr', value: result.signature } as never; + expect(engine.ledger.verifySignature(vk, spendData, signature)).toBe(false); + expect(engine.ledger.verifySignature(vk, signedMessageBytes(spendData), signature)).toBe(true); + expect(result.data).toBe(Buffer.from(spendData).toString('hex')); + }); + + it('throws for unknown encoding', async () => { + connector = createConnector(); + await expect(connector.handlers.signData({ + data: 'test', + options: { encoding: 'binary' }, + }, ctx())).rejects.toThrow('Unknown encoding: binary'); + }); + + it('throws for unsupported keyType', async () => { + connector = createConnector(); + await expect(connector.handlers.signData({ + data: 'test', + options: { encoding: 'text', keyType: 'shielded' }, + }, ctx())).rejects.toThrow('Unsupported keyType'); + }); + + it('throws when data is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.signData({ + options: { encoding: 'hex' }, + }, ctx())).rejects.toThrow('data and options.encoding are required'); + }); + + it('throws when encoding is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.signData({ + data: 'test', + options: {}, + }, ctx())).rejects.toThrow('data and options.encoding are required'); + }); + + it('returns the hex values and the scheme, not the SDK\'s { tag, value } objects', async () => { + connector = createConnector(); + const result = await connector.handlers.signData({ + data: 'aabb', + options: { encoding: 'hex' }, + }, ctx()) as any; + expect(result).toEqual({ + data: 'aabb', + signature: 'abcd1234signature', + verifyingKey: '5678efghpubkey', + scheme: 'schnorr_bip340', + }); + }); + }); + + // ── Input validation on write methods ── + + describe('input validation', () => { + it('makeTransfer throws when desiredOutputs is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.makeTransfer({}, ctx())) + .rejects.toThrow('desiredOutputs must be a non-empty array'); + }); + + it('makeTransfer throws when desiredOutputs is empty', async () => { + connector = createConnector(); + await expect(connector.handlers.makeTransfer({ desiredOutputs: [] }, ctx())) + .rejects.toThrow('desiredOutputs must be a non-empty array'); + }); + + it('makeTransfer throws for invalid output kind', async () => { + connector = createConnector(); + await expect(connector.handlers.makeTransfer({ + desiredOutputs: [{ kind: 'public', type: '0000', value: '100', recipient: 'addr' }], + }, ctx())).rejects.toThrow('Invalid output kind: "public"'); + }); + + // A dApp's mistakes in what it asks for are InvalidRequest, refused before + // the operator is prompted and before the wallet builds anything. + const output = (o: Record) => ({ kind: 'unshielded', type: NIGHT, value: '5', recipient: UNSHIELDED_RECIPIENT, ...o }); + /** No approveAll and no TTY: reaching the approval step would fail as Rejected instead. */ + async function withoutOperator(run: () => Promise): Promise { + const origIsTTY = process.stdin.isTTY; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + try { + return await run(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + } + + it.each([ + ['a zero value', output({ value: '0' }), 'Invalid value: 0 — must be greater than 0'], + ['a negative value', output({ value: '-1' }), 'Invalid value: -1 — must be greater than 0'], + ['a fractional value', output({ value: '1.5' }), 'Invalid value: "1.5" — must be a whole number'], + ['a value that is not a number', output({ value: 'lots' }), 'Invalid value: "lots"'], + ['a boolean value, which BigInt would read as 1', output({ value: true }), 'Invalid value: "true"'], + ['a token type that is not 32 bytes of hex', output({ type: '0000' }), 'Invalid token type: "0000"'], + ['a recipient that is not an address', output({ recipient: 'bob' }), 'Invalid recipient: "bob" is not an unshielded address on Undeployed'], + ['a shielded address for an unshielded output', output({ recipient: SHIELDED_RECIPIENT }), 'is not an unshielded address on Undeployed'], + ['an unshielded address for a shielded output', output({ kind: 'shielded' }), 'is not a shielded address on Undeployed'], + ['an address for another network', output({ recipient: engine.deriveUnshieldedAddress(RECIPIENT_SEED, 'preprod') }), 'is not an unshielded address on Undeployed'], + ])('makeTransfer refuses %s as InvalidRequest without prompting', async (_name, desired, message) => { + const transfer = vi.fn(); + const c = connector = createConnector({ bundleOverrides: { transferTransaction: transfer }, approvalOptions: {} }); + + const err: any = await withoutOperator(() => c.handlers.makeTransfer({ desiredOutputs: [desired] }, ctx()).catch((e: any) => e)); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain(message); + expect(transfer).not.toHaveBeenCalled(); + }); + + it('makeTransfer passes a valid output to the wallet as a decoded address and a bigint', async () => { + const transfer = vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }); + connector = createConnector({ bundleOverrides: { transferTransaction: transfer } }); + + await connector.handlers.makeTransfer({ desiredOutputs: [output({})] }, ctx()).catch(() => undefined); + + const [[combined]] = transfer.mock.calls; + expect(combined).toEqual([{ type: 'unshielded', outputs: [{ type: NIGHT, receiverAddress: expect.anything(), amount: 5n }] }]); + }); + + it.each([ + ['an input kind that is neither', { kind: 'public', type: NIGHT, value: '5' }, 'Invalid input kind: "public"'], + ['a zero input value', { kind: 'unshielded', type: NIGHT, value: '0' }, 'Invalid value: 0'], + ['an input token type that is not hex', { kind: 'unshielded', type: 'night', value: '5' }, 'Invalid token type: "night"'], + ])('makeIntent refuses %s as InvalidRequest without building a swap', async (_name, input, message) => { + const initSwap = vi.fn(); + const c = connector = createConnector({ bundleOverrides: { initSwap }, approvalOptions: {} }); + + const err: any = await withoutOperator(() => c.handlers.makeIntent({ + desiredInputs: [input], desiredOutputs: [], options: { intentId: 'random', payFees: true }, + }, ctx()).catch((e: any) => e)); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain(message); + expect(initSwap).not.toHaveBeenCalled(); + }); + + it('submitTransaction throws when tx is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.submitTransaction({}, ctx())) + .rejects.toThrow('tx is required'); + }); + + it('balanceUnsealedTransaction throws when tx is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.balanceUnsealedTransaction({}, ctx())) + .rejects.toThrow('tx is required'); + }); + + it('balanceSealedTransaction throws when tx is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.balanceSealedTransaction({}, ctx())) + .rejects.toThrow('tx is required'); + }); + + it('makeIntent throws when options is missing', async () => { + connector = createConnector(); + await expect(connector.handlers.makeIntent({ + desiredInputs: [], + desiredOutputs: [], + }, ctx())).rejects.toThrow('options is required for makeIntent'); + }); + }); + + // ── Reading the dApp's transaction (the fee-wallet seam) ── + + describe('transaction adoption', () => { + it.each([ + ['balanceUnsealedTransaction', 'Unbound', 'balanceUnboundTransaction'], + ['balanceSealedTransaction', 'Finalized', 'balanceFinalizedTransaction'], + ] as const)('%s reads the hex at stage %s and balances that handle', async (method, stage, sdkMethod) => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const bundle = createBundleStub({ [sdkMethod]: balance }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + const tx = stage === 'Unbound' ? AGENT_TX : SEALED_AGENT_TX; + + await connector.handlers[method]({ tx }, ctx()); + + if (engine.readsThroughFacade) expect(bundle.facade.adoptTransaction).toHaveBeenCalledWith(Uint8Array.from(Buffer.from(tx, 'hex')), stage); + const [call] = balance.mock.calls; + expect(engine.handleHex(call![0])).toBe(tx); + // The beta facade takes the wallet's secret keys before the options. + if (engine.secretKeys !== undefined) expect(call![1]).toBe(engine.secretKeys); + expect(call!.at(-1)).toMatchObject({ ttl: expect.any(Date) }); + }); + + it('submitTransaction reads the hex as a finalized transaction and submits that handle', async () => { + const submit = vi.fn().mockResolvedValue('tx-id'); + const bundle = createBundleStub({ submitTransaction: submit }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const result = await connector.handlers.submitTransaction({ tx: SEALED_AGENT_TX }, ctx()); + + if (engine.readsThroughFacade) expect(bundle.facade.adoptTransaction).toHaveBeenCalledWith(Uint8Array.from(Buffer.from(SEALED_AGENT_TX, 'hex')), 'Finalized'); + expect(submit).toHaveBeenCalledTimes(1); + expect(engine.handleHex(submit.mock.calls[0]![0])).toBe(SEALED_AGENT_TX); + expect(result).toEqual({ txHash: 'tx-id' }); + }); + + it("forwards the node's refusal when the wallet SDK's submit fails, not only its own wrapper's words", async () => { + // The wallet SDK runs its Effect submit with Effect.runPromise, which + // rejects with a FiberFailure: the SubmissionError it failed with, and + // the node's answer that error wraps, are under a symbol, not `cause`. + const nodeAnswer = new Error('1010: Invalid Transaction: Custom error: 139'); + const sdkFailure = Effect.runPromise(Effect.fail(new engine.SubmissionError({ message: 'Transaction submission error', cause: nodeAnswer }))); + sdkFailure.catch(() => {}); + const bundle = createBundleStub({ submitTransaction: () => sdkFailure }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err: any = await connector.handlers.submitTransaction({ tx: SEALED_AGENT_TX }, ctx()).catch((e: any) => e); + + expect(err.message).toContain('Transaction submission error'); + expect(err.message).toContain('1010: Invalid Transaction: Custom error: 139'); + }); + + it('reports bytes the wallet cannot read as InvalidRequest, naming the stage, without balancing', async () => { + const balance = vi.fn(); + const bundle = createBundleStub({ balanceUnboundTransaction: balance }); + // The rc SDK's reader, as it refuses another ledger version's bytes; the beta engine's ledger refuses these on its own. + if (engine.readsThroughFacade) (bundle.facade as any).adoptTransaction = () => { throw new Error('unknown tag midnight:transaction[v99]'); }; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: 'aabb' }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain('stage Unbound'); + if (engine.readsThroughFacade) expect(err.message).toContain('unknown tag midnight:transaction[v99]'); + expect(balance).not.toHaveBeenCalled(); + }); + + it('rejects non-hex input before it reaches the SDK', async () => { + const bundle = createBundleStub(); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: 'not-hex' }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(bundle.facade.adoptTransaction).not.toHaveBeenCalled(); + }); + }); + + describe('signatureScheme', () => { + it('names BIP-340 Schnorr, and refuses any other tag rather than mislabel it', () => { + expect(engine.signatureScheme('schnorr')).toBe('schnorr_bip340'); + expect(() => engine.signatureScheme('ecdsa')).toThrow('mn signs with BIP-340 Schnorr only'); + }); + }); + + // ── Address methods ── + + describe('getUnshieldedAddress', () => { + it('returns bech32m-encoded unshielded address', async () => { + connector = createConnector(); + const result = await connector.handlers.getUnshieldedAddress({}, ctx()) as any; + expect(result.unshieldedAddress).toMatch(/^mn_addr_undeployed1/); + expect(engine.MidnightBech32m.parse(result.unshieldedAddress).decode(engine.UnshieldedAddress, 'undeployed').equals(WALLET_UNSHIELDED.hexString)).toBe(true); + }); + }); + + describe('getShieldedAddresses', () => { + it('returns shielded address and public keys', async () => { + connector = createConnector(); + const result = await connector.handlers.getShieldedAddresses({}, ctx()) as any; + expect(result.shieldedAddress).toBe(engine.MidnightBech32m.encode('undeployed', WALLET_SHIELDED).asString()); + expect(result.shieldedAddress).toMatch(/^mn_shield-addr_undeployed1/); + expect(result.shieldedCoinPublicKey).toBe(WALLET_SHIELDED.coinPublicKeyString()); + expect(result.shieldedEncryptionPublicKey).toBe(WALLET_SHIELDED.encryptionPublicKeyString()); + }); + }); + + describe('getDustAddress', () => { + it('returns bech32m-encoded dust address', async () => { + connector = createConnector(); + const result = await connector.handlers.getDustAddress({}, ctx()) as any; + expect(result.dustAddress).toMatch(/^mn_dust_undeployed1/); + expect(engine.MidnightBech32m.parse(result.dustAddress).decode(engine.DustAddress, 'undeployed').data).toBe(7n); + }); + }); + + // ── processRecipe (tested via write methods) ── + + describe('processRecipe', () => { + it('rejects with timeout error when proof generation fails', async () => { + // Tests the error path through processRecipe — finalizeRecipe rejection + // propagates correctly through Promise.race and surfaces to the caller. + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + finalizeRecipe: () => Promise.reject(new Error('ZK proof generation timed out')), + }, + }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())) + .rejects.toThrow('ZK proof generation timed out'); + }); + + it('returns serialized tx when finalizeRecipe resolves', async () => { + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + finalizeRecipe: () => Promise.resolve(sealedTx(6)), + }, + }); + + const result = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()) as any; + expect(result.tx).toBe(sealedHex(6)); + }); + + it('propagates signRecipe errors', async () => { + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + signRecipe: () => Promise.reject(new Error('signing failed')), + }, + }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())) + .rejects.toThrow('signing failed'); + }); + + it('propagates finalizeRecipe errors', async () => { + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + finalizeRecipe: () => Promise.reject(new Error('proof generation failed')), + }, + }); + + await expect(connector.handlers.balanceSealedTransaction({ tx: SEALED_AGENT_TX }, ctx())) + .rejects.toThrow('proof generation failed'); + }); + }); + + // ── getProvingProvider ── + + describe('getProvingProvider', () => { + it('returns proof server URI', async () => { + connector = createConnector(); + const result = await connector.handlers.getProvingProvider({}, ctx()) as any; + expect(result.provingProvider).toBe('ready'); + expect(result.proverServerUri).toBe('http://localhost:6300'); + }); + }); + + // ── hintUsage ── + + describe('hintUsage', () => { + it('resolves without error', async () => { + process.stderr.write = (() => true) as any; + + connector = createConnector(); + const result = await connector.handlers.hintUsage({ + methodNames: ['getUnshieldedBalances', 'makeTransfer'], + }, ctx()); + expect(result).toBeUndefined(); + }); + + it('resolves for a method this wallet does not know, as the spec asks', async () => { + process.stderr.write = (() => true) as any; + connector = createConnector(); + await expect(connector.handlers.hintUsage({ methodNames: ['someFutureMethod'] }, ctx())).resolves.toBeUndefined(); + }); + + it.each([ + ['a string instead of an array', 'makeTransfer'], + ['a non-string entry', ['makeTransfer', 42]], + ['a name carrying terminal escape codes', ['\u001b[2Jcleared']], + ])('refuses %s as InvalidRequest without printing it', async (_name, methodNames) => { + const written: string[] = []; + process.stderr.write = ((chunk: string) => { written.push(chunk); return true; }) as any; + connector = createConnector(); + + const err: any = await connector.handlers.hintUsage({ methodNames }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toBe('methodNames must be an array of connector method names'); + expect(written.join('')).not.toContain('hints usage'); + }); + }); + + // ── Dust retry ── + + describe('withDustRetry', () => { + it('retries on "No dust tokens" error and succeeds', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + let callCount = 0; + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + balanceUnboundTransaction: () => { + callCount++; + if (callCount === 1) return Promise.reject(new Error('No dust tokens found in the wallet state')); + return Promise.resolve({ type: 'UNBOUND' }); + }, + }, + }); + + const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(3_100); + const result = await promise as any; + expect(result.tx).toBeDefined(); + expect(callCount).toBe(2); + vi.useRealTimers(); + }); + + it('retries on wallet-sdk 2.0\'s tagged dust shortage', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + const dustShortage = Object.assign(new Error('Insufficient Funds: could not balance dust'), { + _tag: 'Wallet.InsufficientFunds', tokenType: 'dust', + }); + let callCount = 0; + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + balanceUnboundTransaction: () => (++callCount === 1 ? Promise.reject(dustShortage) : Promise.resolve({ type: 'UNBOUND' })), + }, + }); + + const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(3_100); + await promise; + expect(callCount).toBe(2); + vi.useRealTimers(); + }); + + it('does not wait for dust when the wallet is short of NIGHT, which dust cannot fix', async () => { + process.stderr.write = (() => true) as any; + const nightShortage = Object.assign(new Error('Insufficient Funds: could not balance 00'), { + _tag: 'Wallet.InsufficientFunds', tokenType: '00', + }); + const balance = vi.fn().mockRejectedValue(nightShortage); + connector = createConnector({ approvalOptions: { approveAll: true }, bundleOverrides: { balanceUnboundTransaction: balance } }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toBe(nightShortage); + expect(balance).toHaveBeenCalledTimes(1); + }); + + it('does not retry on non-dust errors', async () => { + process.stderr.write = (() => true) as any; + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + balanceUnboundTransaction: () => Promise.reject(new Error('some other error')), + }, + }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())) + .rejects.toThrow('some other error'); + }); + + it('fails after max retry attempts', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + let callCount = 0; + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + balanceUnboundTransaction: () => { + callCount++; + return Promise.reject(new Error('No dust tokens found in the wallet state')); + }, + }, + }); + + const failure = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); + await vi.advanceTimersByTimeAsync(9 * 3_000); + const err: any = await failure; + expect(err.code).toBe('InternalError'); + // Nothing is reserved on this server, so the message doesn't send the caller waiting for a reservation to clear. + expect(err.message).toContain('The wallet has no Dust available that covers this transaction\'s fee (No dust tokens found in the wallet state)'); + expect(err.message).toContain('no balanced transaction is holding any back on this server'); + expect(err.message).not.toContain('Retry once they settle'); + expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(callCount).toBe(10); // DUST_RETRY_ATTEMPTS = 10 + vi.useRealTimers(); + }); + + describe('a shortage that says what the fee takes', () => { + // The wallet's own fee planner marks a shortage with the Dust the fee + // takes. This wallet holds 0.35 DUST and generates 0.0075 a second, as + // a 900 NIGHT wallet on a local ledger-9 chain does. + const SPECK = 1_000_000_000_000_000n; + const HAS = 350n * SPECK / 1000n; + const PER_SECOND = 75n * SPECK / 10_000n; + const shortOf = (needed: bigint, available = HAS) => withDustShortfall(Object.assign(new Error('Insufficient Funds: could not balance dust'), { + _tag: 'Wallet.InsufficientFunds', tokenType: 'dust', + }), { needed, available }); + /** A wallet state whose Dust grows from HAS at PER_SECOND, counted from when the test starts. */ + const growingFrom = (start: number) => () => rx.of({ + ...mockState(), + dust: { balance: (at: Date) => HAS + PER_SECOND * BigInt(Math.max(0, Math.floor((at.getTime() - start) / 1000))), availableCoins: [{}], address: 'dust' }, + }); + + it('waits the time the wallet takes to generate the rest, then pays', async () => { + vi.useFakeTimers(); + const written: string[] = []; + setNoticeSink((line) => written.push(line)); + // 1 DUST: 0.65 more and a little over, 89 seconds at this rate. + const balance = vi.fn().mockRejectedValueOnce(shortOf(SPECK)).mockResolvedValue({ type: 'UNBOUND' }); + connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); + + const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(88_000); + expect(balance).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1_500); + await paid; + expect(balance).toHaveBeenCalledTimes(2); + expect(written.join('')).toContain('Dust: 0.35 of the 1.00 DUST this fee takes; waiting about 2 minutes for the rest...'); + vi.useRealTimers(); + setNoticeSink(null); + }); + + it('refuses at once, with the time, when that is longer than a request waits', async () => { + process.stderr.write = (() => true) as any; + // 2 DUST: 1.65 more, close to four minutes, past the two a request waits. + const balance = vi.fn().mockRejectedValue(shortOf(2n * SPECK)); + connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); + expect(balance).toHaveBeenCalledTimes(1); + expect(err.code).toBe('InternalError'); + expect(err.message).toBe( + "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00. " + + 'Its registered NIGHT generates the rest in about 4 minutes: retry then, or register more NIGHT to get there sooner.'); + expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + }); + + it('waits longer when the caller allows it', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + const balance = vi.fn().mockRejectedValueOnce(shortOf(2n * SPECK)).mockResolvedValue({ type: 'UNBOUND' }); + connector = engine.createDAppConnector({ + bundle: createBundleStub({ stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance }), + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + dustWaitMs: 5 * 60_000, + }); + + const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(226_000); + await paid; + expect(balance).toHaveBeenCalledTimes(2); + vi.useRealTimers(); + }); + + it('says so when the wallet will not generate the fee within a day', async () => { + process.stderr.write = (() => true) as any; + const balance = vi.fn().mockRejectedValue(shortOf(1_000n * SPECK)); + connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); + expect(err.message).toContain("the wallet has 0.35 DUST and the fee takes 1000.00. Its registered NIGHT won't generate that within a day"); + expect(balance).toHaveBeenCalledTimes(1); + }); + + it('waits for what the wallet was short by on its own clock, which this machine\'s can run ahead of', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + // The wallet spends by the chain's clock, 28 seconds behind: its coin held 0.14 DUST when the balance here read 0.35. + const behind = HAS - 28n * PER_SECOND; + const balance = vi.fn().mockRejectedValueOnce(shortOf(SPECK, behind)).mockResolvedValue({ type: 'UNBOUND' }); + connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); + + const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(116_000); // 0.86 more and a little over: 117 seconds + expect(balance).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1_500); + await paid; + expect(balance).toHaveBeenCalledTimes(2); + vi.useRealTimers(); + }); + + it('stops waiting once the waits add up to more than a request waits', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + // The fee keeps moving ahead of the wallet: each wait fits, together they don't. + const start = Date.now(); + const balance = vi.fn().mockImplementation(() => Promise.reject(shortOf(HAS + 50n * PER_SECOND))); + connector = createConnector({ bundleOverrides: { stateFn: growingFrom(start), balanceUnboundTransaction: balance } }); + + const failure = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); + await vi.advanceTimersByTimeAsync(130_000); + const err: any = await failure; + expect(err.message).toContain("Not enough Dust available for this transaction's fee"); + expect(balance).toHaveBeenCalledTimes(3); // 51 s, 51 s, then a third 51 s would pass two minutes + vi.useRealTimers(); + }); + }); + + it('asks again at once when a coin comes free during the wait', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + const attemptedAt: number[] = []; + const started = Date.now(); + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + // No Dust coin is free until one second in, when a pending transaction lands and releases its coin. + stateFn: () => rx.concat(rx.of(mockState({ dustBalance: 0n })), rx.timer(1_000).pipe(rx.map(() => mockState({ dustBalance: 1000n })))), + balanceUnboundTransaction: () => { + attemptedAt.push(Date.now() - started); + return attemptedAt.length < 2 ? Promise.reject(new Error('No dust tokens found in the wallet state')) : Promise.resolve({ type: 'UNBOUND' }); + }, + }, + }); + + const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(1_100); + await promise; + expect(attemptedAt).toEqual([0, 1_000]); + vi.useRealTimers(); + }); + + // Found live: a coin that had just paid a fee was worth less than the + // next one. It showed as available, so all ten attempts ran in 40 ms and + // the request failed, though the coin would have covered it seconds later. + it('gives a coin that is there but too small the delay to grow before each new attempt', async () => { + vi.useFakeTimers(); + process.stderr.write = (() => true) as any; + const shortage = Object.assign(new Error('Insufficient Funds: could not balance dust'), { _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' }); + const attemptedAt: number[] = []; + const started = Date.now(); + connector = createConnector({ + approvalOptions: { approveAll: true }, + bundleOverrides: { + // The wallet state shows Dust throughout; the fourth attempt finds it has grown enough. + balanceUnboundTransaction: () => { + attemptedAt.push(Date.now() - started); + return attemptedAt.length < 4 ? Promise.reject(shortage) : Promise.resolve({ type: 'UNBOUND' }); + }, + }, + }); + + const promise = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + await vi.advanceTimersByTimeAsync(2_900); + expect(attemptedAt).toEqual([0]); + await vi.advanceTimersByTimeAsync(6_200); + await promise; + expect(attemptedAt).toEqual([0, 3_000, 6_000, 9_000]); + vi.useRealTimers(); + }); + }); + + // ── Hex-based pending tx tracking ── + + // ── What the wallet balances, per mode ── + + describe('token kinds to balance', () => { + it.each([ + ['balanceUnsealedTransaction', 'balanceUnboundTransaction'], + ['balanceSealedTransaction', 'balanceFinalizedTransaction'], + ] as const)('%s balances every kind by default, and leaves the fee out when payFees is false', async (method, sdkMethod) => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + connector = createConnector({ bundleOverrides: { [sdkMethod]: balance } }); + + const tx = method === 'balanceUnsealedTransaction' ? AGENT_TX : SEALED_AGENT_TX; + await connector.handlers[method]({ tx }, ctx()); + await connector.handlers[method]({ tx, options: { payFees: true } }, ctx()); + await connector.handlers[method]({ tx, options: { payFees: false } }, ctx()); + + expect(balance.mock.calls.map((call) => call.at(-1))).toEqual([ + { ttl: expect.any(Date), tokenKindsToBalance: 'all' }, + { ttl: expect.any(Date), tokenKindsToBalance: 'all' }, + { ttl: expect.any(Date), tokenKindsToBalance: ['shielded', 'unshielded'] }, + ]); + }); + }); + + // ── Fee wallet: --approve-fees ── + + describe('fee wallet (approveFees)', () => { + let origIsTTY: boolean | undefined; + const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex'); + + beforeEach(() => { + origIsTTY = process.stdin.isTTY; + // An agent has no terminal: anything that is not fee-only must be rejected, not prompted. + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + process.stderr.write = (() => true) as any; + }); + + afterEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + }); + + /** A connector in fee-wallet mode over a bundle whose unshielded key is WALLET_VK. */ + function feeWallet( + overrides?: BundleOverrides, + approvalOptions: ApprovalOptions = { approveFees: true, autoApproveReads: true }, + feeLimits?: FeeLimits, + ) { + const bundle = createBundleStub(overrides); + (bundle.keystore as any).getPublicKey = () => WALLET_VK; + const feeConnector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions, feeLimits }); + connector = feeConnector; + return { bundle, connector: feeConnector }; + } + + describe('fee limits', () => { + const ONE_DUST = 1_000_000_000_000_000n; + + it('refuses a transaction whose estimated fee is over --max-fee, before balancing', async () => { + const balance = vi.fn(); + const estimate = vi.fn().mockResolvedValue(ONE_DUST + 1n); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, undefined, + { maxFeeSpecks: ONE_DUST, maxPending: 2 }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()) + .catch((e) => e); + + expect(err.code).toBe('Rejected'); + expect(err.message).toContain('over --max-fee 1.000000 DUST'); + expect(estimate).toHaveBeenCalledTimes(1); + expect(balance).not.toHaveBeenCalled(); + }); + + it('balances a transaction at the cap', async () => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: async () => ONE_DUST }, undefined, + { maxFeeSpecks: ONE_DUST, maxPending: 2 }); + + await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()); + expect(balance).toHaveBeenCalledTimes(1); + }); + + it('refuses a new balance while --max-pending unsubmitted transactions hold Dust, and frees a slot on submit', async () => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const finalizeRecipe = vi.fn() + .mockResolvedValueOnce(sealedTx(1)) + .mockResolvedValueOnce(sealedTx(2)) + .mockResolvedValueOnce(sealedTx(3)); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, finalizeRecipe }, undefined, + { maxFeeSpecks: ONE_DUST, maxPending: 2 }); + const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; + + const first: any = await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')); + await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c2')); + const err: any = await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')).catch((e) => e); + expect(err.code).toBe('Rejected'); + expect(err.message).toContain('2 balanced transactions are still waiting to be submitted (--max-pending 2)'); + expect(balance).toHaveBeenCalledTimes(2); + + await connector.handlers.submitTransaction({ tx: first.tx }, ctx('c1')); + await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')); + expect(balance).toHaveBeenCalledTimes(3); + }); + + it('says a balanced transaction is holding the Dust when one is, and how many', async () => { + vi.useFakeTimers(); + const stderrWrite = process.stderr.write; + process.stderr.write = (() => true) as any; + try { + const balance = vi.fn() + .mockResolvedValueOnce({ type: 'RECIPE' }) + // The shape of the wallet SDK's own Dust shortage. + .mockRejectedValue(Object.assign(new Error('Insufficient Funds: could not balance dust'), { _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' })); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, finalizeRecipe: vi.fn().mockResolvedValue(sealedTx(1)) }, undefined, + { maxFeeSpecks: ONE_DUST, maxPending: 2 }); + const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; + + await connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c1')); + const failure = connector.handlers.balanceUnsealedTransaction(agentTx, ctx('c2')).catch((e: any) => e); + await vi.advanceTimersByTimeAsync(9 * 2 * 3_000); + const err: any = await failure; + expect(err.message).toContain('No Dust is free to pay the fee ([Wallet.InsufficientFunds] Insufficient Funds: could not balance dust)'); + expect(err.message).toContain('1 balanced transaction(s) are waiting to be submitted on this server. Retry once they settle.'); + expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + } finally { + process.stderr.write = stderrWrite; + vi.useRealTimers(); + } + }); + + it('counts balances still in flight: two at the same moment cannot both take the last slot', async () => { + let finishEstimate!: () => void; + const estimateGate = new Promise((r) => { finishEstimate = r; }); + const estimate = vi.fn(async () => { await estimateGate; return 1n; }); + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, undefined, + { maxFeeSpecks: ONE_DUST, maxPending: 1 }); + const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; + + const first = connector.handlers.balanceUnsealedTransaction(agentTx, ctx('a')); + const second = connector.handlers.balanceUnsealedTransaction(agentTx, ctx('b')).catch((e: any) => e); + finishEstimate(); + + await expect(first).resolves.toHaveProperty('tx'); + const err: any = await second; + expect(err.code).toBe('Rejected'); + expect(err.message).toContain('(--max-pending 1)'); + expect(balance).toHaveBeenCalledTimes(1); + }); + + it('gives the slot back when a balance fails, so the next one can use it', async () => { + const estimate = vi.fn().mockResolvedValueOnce(2n * ONE_DUST).mockResolvedValue(1n); + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, undefined, + { maxFeeSpecks: ONE_DUST, maxPending: 1 }); + const agentTx = { tx: hex(await unsealedBytes(agentPaysMerchant())) }; + + await expect(connector.handlers.balanceUnsealedTransaction(agentTx, ctx())).rejects.toMatchObject({ code: 'Rejected' }); + await expect(connector.handlers.balanceUnsealedTransaction(agentTx, ctx())).resolves.toHaveProperty('tx'); + }); + + it('does not apply outside fee-wallet mode', async () => { + const estimate = vi.fn().mockResolvedValue(10n * ONE_DUST); + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, + { approveAll: true }, { maxFeeSpecks: 1n, maxPending: 1 }); + + await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()); + expect(estimate).not.toHaveBeenCalled(); + expect(balance).toHaveBeenCalledTimes(1); + }); + }); + + it.each([ + ['balanceUnsealedTransaction', 'balanceUnboundTransaction', unsealedBytes], + ['balanceSealedTransaction', 'balanceFinalizedTransaction', sealedBytes], + ] as const)('%s balances Dust-only and is approved without a terminal', async (method, sdkMethod, toBytes) => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const { connector } = feeWallet({ [sdkMethod]: balance }); + + const result = await connector.handlers[method]({ tx: hex(await toBytes(agentPaysMerchant())) }, ctx()) as any; + + expect(balance).toHaveBeenCalledTimes(1); + expect(balance.mock.calls[0]!.at(-1)).toEqual({ ttl: expect.any(Date), tokenKindsToBalance: ['dust'] }); + expect(result).toEqual({ tx: FINALIZED_HEX }); + }); + + it('approves a fee-only balance as fee-only, not as a prep step, so it holds with --no-auto-approve-reads', async () => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const { connector } = feeWallet({ balanceUnboundTransaction: balance }, { approveFees: true, autoApproveReads: false }); + + const result = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()) as any; + + expect(balance).toHaveBeenCalledTimes(1); + expect(result).toEqual({ tx: FINALIZED_HEX }); + }); + + it('submits a transaction it balanced fee-only on the same connection, without a terminal', async () => { + const submit = vi.fn().mockResolvedValue('tx-id'); + const { connector } = feeWallet({ submitTransaction: submit }); + + const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx('agent')) as any; + const result = await connector.handlers.submitTransaction({ tx: balanced.tx }, ctx('agent')); + + expect(engine.handleHex(submit.mock.calls[0]![0])).toBe(FINALIZED_HEX); + expect(result).toEqual({ txHash: 'tx-id' }); + }); + + it('rejects submitting a transaction this server did not balance', async () => { + const submit = vi.fn(); + const { connector } = feeWallet({ submitTransaction: submit }); + + const err: any = await connector.handlers.submitTransaction({ tx: hex(await sealedBytes(agentPaysMerchant())) }, ctx('agent')).catch((e: any) => e); + + expect(err.code).toBe('Rejected'); + expect(submit).not.toHaveBeenCalled(); + }); + + it('rejects submitting a fee-only transaction from another connection', async () => { + const submit = vi.fn(); + const { connector } = feeWallet({ submitTransaction: submit }); + + const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx('agent')) as any; + const err: any = await connector.handlers.submitTransaction({ tx: balanced.tx }, ctx('someone-else')).catch((e: any) => e); + + expect(err.code).toBe('Rejected'); + expect(submit).not.toHaveBeenCalled(); + }); + + it('rejects submitting a transaction this server balanced, but not fee-only', async () => { + const submit = vi.fn(); + const opts: ApprovalOptions = { approveAll: true }; + const { connector } = feeWallet({ submitTransaction: submit }, opts); + + const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('agent')) as any; + delete opts.approveAll; + opts.approveFees = true; + const err: any = await connector.handlers.submitTransaction({ tx: balanced.tx }, ctx('agent')).catch((e: any) => e); + + expect(err.code).toBe('Rejected'); + // The agent learns why, not just that it was refused. + expect(err.message).toBe('User rejected the request: this fee wallet (--approve-fees) approves without the operator only ' + + "paying the Dust fee for an agent's own transaction and submitting a transaction it balanced that way on the same connection"); + expect(submit).not.toHaveBeenCalled(); + }); + + it.each([ + ['spends the wallet\'s own Night', + () => buildTx({ guaranteed: { inputs: [spend(WALLET_SK, 100n)], outputs: [pay(100n)], signers: [WALLET_SK] } }), + "intent 1 guaranteed unshielded input 0 spends this wallet's own funds"], + ['leaves an input for the wallet to sign', + () => buildTx({ guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(100n)], signers: [] } }), + 'intent 1 guaranteed unshielded input 0 is unsigned, so this wallet would sign it'], + ['leaves an output for the wallet to fund', + () => buildTx({ guaranteed: { inputs: [], outputs: [pay(100n)], signers: [] } }), + `segment 0 is short 100 of unshielded token ${NIGHT}, which a Dust-only balance can't fund`], + ])('refuses, with the reason, a transaction that %s, before balancing anything', async (_label, build, reason) => { + const balance = vi.fn(); + const { bundle, connector } = feeWallet({ balanceUnboundTransaction: balance }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(build())) }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('Rejected'); + expect(err.message).toContain('--approve-fees'); + expect(err.message).toContain(reason); + expect(balance).not.toHaveBeenCalled(); + expect(bundle.facade.adoptTransaction).not.toHaveBeenCalled(); + }); + + it('refuses payFees: false, which leaves a fee wallet nothing to do', async () => { + const balance = vi.fn(); + const { connector } = feeWallet({ balanceUnboundTransaction: balance }); + + const err: any = await connector.handlers.balanceUnsealedTransaction( + { tx: hex(await unsealedBytes(agentPaysMerchant())), options: { payFees: false } }, ctx(), + ).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain('payFees'); + expect(balance).not.toHaveBeenCalled(); + }); + + it('refuses bytes it cannot read as a ledger-9 transaction of that stage', async () => { + const balance = vi.fn(); + const { connector } = feeWallet({ balanceFinalizedTransaction: balance }); + + const err: any = await connector.handlers.balanceSealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain('sealed'); + expect(balance).not.toHaveBeenCalled(); + }); + + it('still needs a prompt for anything else, so an agent\'s makeTransfer is rejected', async () => { + const transfer = vi.fn(); + const { connector } = feeWallet({ transferTransaction: transfer }); + + const err: any = await connector.handlers.makeTransfer({ + desiredOutputs: [{ kind: 'unshielded', type: NIGHT, value: '1', recipient: UNSHIELDED_RECIPIENT }], + }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('Rejected'); + expect(transfer).not.toHaveBeenCalled(); + }); + }); + + describe('pending tx tracking (hex-based)', () => { + it('untrackPendingTx works via hex key (not object identity)', async () => { + // balanceUnsealedTransaction tracks a tx, then submitTransaction untracks by hex. + // If untracking fails, revertPendingTxs would call revertTransaction. + const revertFn = vi.fn().mockResolvedValue(undefined); + process.stderr.write = (() => true) as any; + + const bundle = createBundleStub({ + finalizeRecipe: () => Promise.resolve(sealedTx(1)), + submitTransaction: () => Promise.resolve('hash-123'), + }); + (bundle.facade as any).revert = revertFn; + + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + const connId = 'conn_hex_test'; + + // Balance a tx — this tracks it + const balanceResult = await connector.handlers.balanceUnsealedTransaction( + { tx: AGENT_TX }, ctx(connId), + ) as any; + + // Submit using the hex from balance result — this untracks by hex + await connector.handlers.submitTransaction( + { tx: balanceResult.tx }, ctx(connId), + ); + + // revertPendingTxs should have nothing to revert + await connector.revertPendingTxs(connId); + expect(revertFn).not.toHaveBeenCalled(); + }); + + it('revertPendingTxs reverts tracked txs on disconnect', async () => { + const revertFn = vi.fn().mockResolvedValue(undefined); + process.stderr.write = (() => true) as any; + + const finalized = sealedTx(2); + const bundle = createBundleStub({ + finalizeRecipe: () => Promise.resolve(finalized), + }); + (bundle.facade as any).revert = revertFn; + + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + const connId = 'conn_revert_test'; + await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx(connId)); + + // Disconnect reverts the FINALIZED transaction: that releases its coins in + // all three wallets and clears its pending entry (the recipe would not). + await connector.revertPendingTxs(connId); + expect(revertFn).toHaveBeenCalledTimes(1); + expect(revertFn).toHaveBeenCalledWith(finalized); + }); + + it('submitTransaction rejection reverts and untracks', async () => { + const revertFn = vi.fn().mockResolvedValue(undefined); + const origIsTTY = process.stdin.isTTY; + process.stderr.write = (() => true) as any; + + const finalized = sealedTx(3); + const bundle = createBundleStub({ + finalizeRecipe: () => Promise.resolve(finalized), + }); + (bundle.facade as any).revert = revertFn; + + // Use a single connector — approvalOptions is a mutable object reference. + // Balance with approveAll, then remove it so submit rejects via non-TTY. + const opts: Record = { approveAll: true }; + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: opts, + }); + + const connId = 'conn_reject_test'; + + // Balance first (auto-approved via approveAll) — tracks the tx internally + const balanceResult = await connector.handlers.balanceUnsealedTransaction( + { tx: AGENT_TX }, ctx(connId), + ) as any; + + // Switch: remove approveAll + non-TTY → submit will be rejected + delete opts.approveAll; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + + // Submit on the SAME connector → rejection → reverts the finalized tx + await expect(connector.handlers.submitTransaction({ tx: balanceResult.tx }, ctx(connId))) + .rejects.toMatchObject({ code: 'Rejected' }); + + expect(revertFn).toHaveBeenCalledWith(finalized); + // Untracked: a later disconnect has nothing left to revert. + revertFn.mockClear(); + await connector.revertPendingTxs(connId); + expect(revertFn).not.toHaveBeenCalled(); + + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + }); + }); + + describe('a dApp transaction the wallet SDK cannot sign correctly', () => { + // wallet-sdk 2.0.0-rc.0 duplicates the signatures already on an offer it + // signs, so one with both signed and unsigned inputs can't be signed. + const partlySigned = async () => Buffer.from(await unsealedBytes(buildTx({ + guaranteed: { inputs: [spend(AGENT_SK, 60n, 0)], outputs: [pay(60n)], signers: [AGENT_SK] }, + fallible: { inputs: [spend(WALLET_SK, 40n, 1)], outputs: [pay(40n)], signers: [] }, + }))).toString('hex'); + + it('is refused as InvalidRequest before the operator is asked and before anything is balanced', async () => { + const balance = vi.fn(); + const bundle = createBundleStub({ balanceUnboundTransaction: balance }); + // No approveAll and no TTY: reaching the approval step would fail as Rejected instead. + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: {} }); + const origIsTTY = process.stdin.isTTY; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + try { + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: await partlySigned() }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain('both signed and unsigned unshielded inputs'); + expect(balance).not.toHaveBeenCalled(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + + // Signed by the agent, 40 Night over: unshielded balancing would merge an + // output for it into the agent's intent, invalidating the agent's signature. + const signedWithSurplus = async () => Buffer.from(await unsealedBytes(buildTx({ + guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(60n)], signers: [AGENT_SK] }, + }))).toString('hex'); + + it.each([ + ['every token kind (the default)', undefined], + ['all but Dust (payFees: false)', { payFees: false }], + ])('a signed transaction that needs unshielded balancing is refused as InvalidRequest when balancing %s', async (_mode, options) => { + const balance = vi.fn(); + connector = createConnector({ bundleOverrides: { balanceUnboundTransaction: balance } }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: await signedWithSurplus(), options }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain('segment 0 is not balanced in unshielded value'); + expect(balance).not.toHaveBeenCalled(); + }); + + it('the same transaction goes on to a Dust-only balance on a fee wallet, which adds nothing to its intent', async () => { + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); + const bundle = createBundleStub({ balanceUnboundTransaction: balance }); + (bundle.keystore as any).getPublicKey = () => WALLET_VK; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveFees: true, autoApproveReads: true } }); + + await connector.handlers.balanceUnsealedTransaction({ tx: await signedWithSurplus() }, ctx()); + + expect(balance.mock.calls[0]!.at(-1)).toMatchObject({ tokenKindsToBalance: ['dust'] }); + }); + + it('a partly signed transaction found only at signing is still InvalidRequest, with its recipe reverted', async () => { + const recipe = { type: 'RECIPE' }; + const revertFn = vi.fn().mockResolvedValue(undefined); + const bundle = createBundleStub({ + balanceUnboundTransaction: () => Promise.resolve(recipe), + signRecipe: () => Promise.reject(new engine.PartlySignedTransactionError()), + }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toContain('both signed and unsigned unshielded inputs'); + expect(revertFn).toHaveBeenCalledWith(recipe); + }); + }); + + describe('balancing on a server started without --approve-all or --approve-fees', () => { + // Found live: a dApp asked plain `mn serve` (no terminal) to balance a spend + // of the wallet's own NIGHT and got back a sealed transaction carrying the + // wallet's valid signature, which it could submit through any node. + it.each([ + ['balanceUnsealedTransaction', unsealedBytes, 'balanceUnboundTransaction'], + ['balanceSealedTransaction', sealedBytes, 'balanceFinalizedTransaction'], + ] as const)('%s prompts, so with no terminal a spend of the wallet\'s own NIGHT is rejected before anything is balanced or signed', async (method, toBytes, balanceMethod) => { + const walletSpend = Buffer.from(await toBytes(buildTx({ + guaranteed: { inputs: [spend(WALLET_SK, 990n)], outputs: [pay(990n)], signers: [] }, + }))).toString('hex'); + const balance = vi.fn(); + const bundle = createBundleStub({ [balanceMethod]: balance }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { autoApproveReads: true } }); + const origIsTTY = process.stdin.isTTY; + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + try { + const err: any = await connector.handlers[method]({ tx: walletSpend }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('Rejected'); + expect(balance).not.toHaveBeenCalled(); + expect(bundle.facade.signRecipe).not.toHaveBeenCalled(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + }); + + describe('an expired dApp transaction', () => { + it.each([ + ['balanceUnsealedTransaction', unsealedBytes, 'balanceUnboundTransaction'], + ['balanceSealedTransaction', sealedBytes, 'balanceFinalizedTransaction'], + ] as const)('%s refuses it as InvalidRequest, naming the intent and its TTL, before balancing', async (method, toBytes, sdkMethod) => { + // A whole second: the ledger keeps an intent's TTL to the second. + const ttl = new Date(Math.floor(Date.now() / 1000) * 1000 - 60_000); + const agentPaidAMinuteTooLate = buildTx({ guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(100n)], signers: [AGENT_SK] } }, ttl); + const expired = Buffer.from(await toBytes(agentPaidAMinuteTooLate)).toString('hex'); + const balance = vi.fn(); + connector = createConnector({ bundleOverrides: { [sdkMethod]: balance } }); + + const err: any = await (connector.handlers as any)[method]({ tx: expired }, ctx()).catch((e: any) => e); + + expect(err.code).toBe('InvalidRequest'); + expect(err.message).toBe(`The transaction has expired: intent 1's TTL (${ttl.toISOString()}) has passed. Build it again with a later TTL.`); + expect(balance).not.toHaveBeenCalled(); + }); + }); + + describe('failed signing', () => { + it('reverts the recipe so its coins are not held until the TTL', async () => { + const recipe = { type: 'RECIPE' }; + const revertFn = vi.fn().mockResolvedValue(undefined); + const bundle = createBundleStub({ + balanceUnboundTransaction: () => Promise.resolve(recipe), + signRecipe: () => Promise.reject(new Error('signer unavailable')), + }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toThrow('signer unavailable'); + expect(revertFn).toHaveBeenCalledWith(recipe); + expect(bundle.facade.finalizeRecipe).not.toHaveBeenCalled(); + }); + }); + + describe('failed proving', () => { + it('reverts the recipe so its coins are not held until the TTL', async () => { + const recipe = { type: 'RECIPE' }; + const revertFn = vi.fn().mockResolvedValue(undefined); + const bundle = createBundleStub({ + balanceUnboundTransaction: () => Promise.resolve(recipe), + finalizeRecipe: () => Promise.reject(new Error('proof server unreachable')), + }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toThrow('proof server unreachable'); + expect(revertFn).toHaveBeenCalledWith(recipe); + }); + + it('also reverts a proof that finishes after the timeout, so no stale pending tx is left', async () => { + vi.useFakeTimers(); + try { + const recipe = { type: 'RECIPE' }; + const late = sealedTx(9); + let finishProof!: (tx: unknown) => void; + const revertFn = vi.fn().mockResolvedValue(undefined); + const bundle = createBundleStub({ + balanceUnboundTransaction: () => Promise.resolve(recipe), + finalizeRecipe: () => new Promise((resolve) => { finishProof = resolve; }), + }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const call = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); + const outcome = expect(call).rejects.toThrow('ZK proof generation timed out'); + await vi.advanceTimersByTimeAsync(PROOF_TIMEOUT_MS + 1); + await outcome; + expect(revertFn).toHaveBeenCalledWith(recipe); + + // The SDK registers the finalized tx as pending when the proof lands. + finishProof(late); + await vi.advanceTimersByTimeAsync(0); + expect(revertFn).toHaveBeenCalledWith(late); + } finally { + vi.useRealTimers(); + } + }); + }); + + // ── Abandon timer ── + + describe('abandon timer', () => { + it('auto-reverts after timeout', async () => { + vi.useFakeTimers(); + const revertFn = vi.fn().mockResolvedValue(undefined); + process.stderr.write = (() => true) as any; + + const bundle = createBundleStub({ + finalizeRecipe: () => Promise.resolve(sealedTx(4)), + }); + (bundle.facade as any).revert = revertFn; + + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + const connId = 'conn_abandon'; + await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx(connId)); + + // Advance past ABANDONED_TX_TIMEOUT_MS (120_000ms) + await vi.advanceTimersByTimeAsync(121_000); + + // Timer fires and reverts the abandoned tx + expect(revertFn).toHaveBeenCalledTimes(1); + + vi.useRealTimers(); + }); + + it('dispose clears abandon timers', async () => { + vi.useFakeTimers(); + const revertFn = vi.fn().mockResolvedValue(undefined); + process.stderr.write = (() => true) as any; + + const bundle = createBundleStub({ + finalizeRecipe: () => Promise.resolve(sealedTx(5)), + }); + (bundle.facade as any).revert = revertFn; + + connector = engine.createDAppConnector({ + bundle, + networkConfig: TEST_NETWORK_CONFIG, + approvalOptions: { approveAll: true }, + }); + + await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('conn_dispose')); + + // Dispose before timeout fires + connector.dispose(); + connector = undefined; + + await vi.advanceTimersByTimeAsync(121_000); + expect(revertFn).not.toHaveBeenCalled(); + + vi.useRealTimers(); + }); + }); + }); +} diff --git a/src/__tests__/helpers/ledger-tx.ts b/src/__tests__/helpers/ledger-tx.ts index bc54fb42..ed47aa7d 100644 --- a/src/__tests__/helpers/ledger-tx.ts +++ b/src/__tests__/helpers/ledger-tx.ts @@ -2,36 +2,25 @@ // connector: one intent at segment 1 with unshielded offers, signed over the // intent's real signature data, proven (there is nothing to prove) and // serialized at the stage the dApp sends. +// +// Built over a given copy of the ledger (`ledgerTx`), since each SDK engine +// reads transactions with its own; the exports below are over the rc +// engine's, the copy at the root. -import { - CostModel, - Intent, - SignatureEnabled, - Transaction, - UnshieldedOffer, - addressFromKey, - signData, - signatureVerifyingKey, - signingKeyFromBip340, - unshieldedToken, - type ProvingProvider, - type SigningKey, - type UnprovenTransaction, - type UtxoOutput, - type UtxoSpend, +import * as rcLedger from '@midnightntwrk/ledger-v9'; +import type { + ProvingProvider, + SigningKey, + UnprovenTransaction, + UtxoOutput, + UtxoSpend, } from '@midnightntwrk/ledger-v9'; +/** A copy of ledger-v9, as an engine loads it. */ +export type Ledger = typeof rcLedger; + export const NETWORK = 'undeployed'; export const TTL = new Date(Date.UTC(2030, 0, 1)); -export const NIGHT = unshieldedToken().raw; - -/** The wallet `mn serve` runs (the fee wallet). */ -export const WALLET_SK = signingKeyFromBip340(new Uint8Array(32).fill(1)); -/** The agent: holds its own value, never the wallet's. */ -export const AGENT_SK = signingKeyFromBip340(new Uint8Array(32).fill(2)); -export const WALLET_VK = signatureVerifyingKey(WALLET_SK); -export const AGENT_VK = signatureVerifyingKey(AGENT_SK); -export const MERCHANT = addressFromKey(signatureVerifyingKey(signingKeyFromBip340(new Uint8Array(32).fill(3)))); /** These transactions hold no zswap or contract parts, so proving them has nothing to prove. */ const NOTHING_TO_PROVE: ProvingProvider = { @@ -40,11 +29,6 @@ const NOTHING_TO_PROVE: ProvingProvider = { lookupKey: () => { throw new Error('unexpected key lookup'); }, }; -export const spend = (owner: SigningKey, value: bigint, outputNo = 0): UtxoSpend => ({ - value, owner: signatureVerifyingKey(owner), type: NIGHT, intentHash: 'ab'.repeat(32), outputNo, -}); -export const pay = (value: bigint): UtxoOutput => ({ value, owner: MERCHANT, type: NIGHT }); - export interface OfferSpec { inputs: UtxoSpend[]; outputs: UtxoOutput[]; @@ -52,30 +36,57 @@ export interface OfferSpec { signers: SigningKey[]; } -export function buildTx(offers: { guaranteed?: OfferSpec; fallible?: OfferSpec }, ttl: Date = TTL): UnprovenTransaction { - const intent = Intent.new(ttl); - if (offers.guaranteed) intent.guaranteedUnshieldedOffer = UnshieldedOffer.new(offers.guaranteed.inputs, offers.guaranteed.outputs, []); - if (offers.fallible) intent.fallibleUnshieldedOffer = UnshieldedOffer.new(offers.fallible.inputs, offers.fallible.outputs, []); - const data = intent.signatureData(1); - const sign = (spec: OfferSpec) => spec.signers.map((sk) => new SignatureEnabled(signData(sk, data))); - if (offers.guaranteed && offers.guaranteed.signers.length > 0) { - intent.guaranteedUnshieldedOffer = intent.guaranteedUnshieldedOffer!.addSignatures(sign(offers.guaranteed)); +/** The keys, builders and serializers, over `ledger`. */ +export function ledgerTx(ledger: Ledger) { + const { + CostModel, Intent, SignatureEnabled, Transaction, UnshieldedOffer, + addressFromKey, signData, signatureVerifyingKey, signingKeyFromBip340, unshieldedToken, + } = ledger; + const NIGHT = unshieldedToken().raw; + /** The wallet `mn serve` runs (the fee wallet). */ + const WALLET_SK = signingKeyFromBip340(new Uint8Array(32).fill(1)); + /** The agent: holds its own value, never the wallet's. */ + const AGENT_SK = signingKeyFromBip340(new Uint8Array(32).fill(2)); + const WALLET_VK = signatureVerifyingKey(WALLET_SK); + const AGENT_VK = signatureVerifyingKey(AGENT_SK); + const MERCHANT = addressFromKey(signatureVerifyingKey(signingKeyFromBip340(new Uint8Array(32).fill(3)))); + + const spend = (owner: SigningKey, value: bigint, outputNo = 0): UtxoSpend => ({ + value, owner: signatureVerifyingKey(owner), type: NIGHT, intentHash: 'ab'.repeat(32), outputNo, + }); + const pay = (value: bigint): UtxoOutput => ({ value, owner: MERCHANT, type: NIGHT }); + + function buildTx(offers: { guaranteed?: OfferSpec; fallible?: OfferSpec }, ttl: Date = TTL): UnprovenTransaction { + const intent = Intent.new(ttl); + if (offers.guaranteed) intent.guaranteedUnshieldedOffer = UnshieldedOffer.new(offers.guaranteed.inputs, offers.guaranteed.outputs, []); + if (offers.fallible) intent.fallibleUnshieldedOffer = UnshieldedOffer.new(offers.fallible.inputs, offers.fallible.outputs, []); + const data = intent.signatureData(1); + const sign = (spec: OfferSpec) => spec.signers.map((sk) => new SignatureEnabled(signData(sk, data))); + if (offers.guaranteed && offers.guaranteed.signers.length > 0) { + intent.guaranteedUnshieldedOffer = intent.guaranteedUnshieldedOffer!.addSignatures(sign(offers.guaranteed)); + } + if (offers.fallible && offers.fallible.signers.length > 0) { + intent.fallibleUnshieldedOffer = intent.fallibleUnshieldedOffer!.addSignatures(sign(offers.fallible)); + } + return Transaction.fromParts(NETWORK, undefined, undefined, intent); } - if (offers.fallible && offers.fallible.signers.length > 0) { - intent.fallibleUnshieldedOffer = intent.fallibleUnshieldedOffer!.addSignatures(sign(offers.fallible)); + + /** The agent pays the merchant `value` Night from its own signed input: nothing left for the wallet but the fee. */ + const agentPaysMerchant = (value = 100n) => buildTx({ guaranteed: { inputs: [spend(AGENT_SK, value)], outputs: [pay(value)], signers: [AGENT_SK] } }); + + /** The bytes a dApp sends to balanceUnsealedTransaction. */ + async function unsealedBytes(tx: UnprovenTransaction): Promise { + return (await tx.prove(NOTHING_TO_PROVE, CostModel.initialCostModel())).serialize(); } - return Transaction.fromParts(NETWORK, undefined, undefined, intent); -} -/** The agent pays the merchant 100 Night from its own signed input: nothing left for the wallet but the fee. */ -export const agentPaysMerchant = () => buildTx({ guaranteed: { inputs: [spend(AGENT_SK, 100n)], outputs: [pay(100n)], signers: [AGENT_SK] } }); + /** The bytes a dApp sends to balanceSealedTransaction. */ + async function sealedBytes(tx: UnprovenTransaction): Promise { + return (await tx.prove(NOTHING_TO_PROVE, CostModel.initialCostModel())).bind().serialize(); + } -/** The bytes a dApp sends to balanceUnsealedTransaction. */ -export async function unsealedBytes(tx: UnprovenTransaction): Promise { - return (await tx.prove(NOTHING_TO_PROVE, CostModel.initialCostModel())).serialize(); + return { NIGHT, WALLET_SK, AGENT_SK, WALLET_VK, AGENT_VK, MERCHANT, spend, pay, buildTx, agentPaysMerchant, unsealedBytes, sealedBytes }; } -/** The bytes a dApp sends to balanceSealedTransaction. */ -export async function sealedBytes(tx: UnprovenTransaction): Promise { - return (await tx.prove(NOTHING_TO_PROVE, CostModel.initialCostModel())).bind().serialize(); -} +export const { + NIGHT, WALLET_SK, AGENT_SK, WALLET_VK, AGENT_VK, MERCHANT, spend, pay, buildTx, agentPaysMerchant, unsealedBytes, sealedBytes, +} = ledgerTx(rcLedger); diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts index 3ab94f9e..9faef07b 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/src/__tests__/wallet-session.test.ts @@ -4,14 +4,19 @@ import { describe, it, expect, vi, beforeAll } from 'vitest'; import * as rx from 'rxjs'; -import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; +import { DustAddress, MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { sessionOver, type WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { TEST_NETWORK_CONFIG, WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, mockState } from './helpers/connector-stub.ts'; +import { deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; +import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; +const { WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, mockState } = connectorStub({ + createDAppConnector, deriveShieldedAddress, DustAddress, UnshieldedAddress, ledger9ProtocolVersion: FORK_SCHEDULE.v9, +}); + const NIGHT_RAW = '0000000000000000000000000000000000000000000000000000000000000000'; const OTHER_TOKEN = '02' + '00'.repeat(31); const RECIPIENT = deriveUnshieldedAddress(Buffer.from('00'.repeat(31) + '42', 'hex'), 'undeployed'); From e8cb4524bb3305b2c8bb69acf5b7ad688d2126c0 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 11:06:07 -0800 Subject: [PATCH 44/88] pack-release.mjs: the release packed for a local registry, reusable The clean-install check packed the workspace packages and mn with its shrinkwrap inline. The release gate needs the same packing to install mn in a clean runner as npm would install it from the registry, so it moves into scripts/pack-release.mjs, which the check now calls. It takes the local registry's port, so a folder packed on one machine can be served on the same port wherever it is installed. The check also shows each resolved copy's path from the real install folder (it was cut at the wrong place under a symlinked tmp folder). --- scripts/fresh-install-check.mjs | 34 +++++------------- scripts/local-registry.mjs | 8 ++--- scripts/pack-release.mjs | 61 +++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 29 deletions(-) create mode 100644 scripts/pack-release.mjs diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 8743ade1..ad391166 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -16,11 +16,10 @@ // node scripts/fresh-install-check.mjs (after `npm run build`) import { execFileSync, spawn } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; -import { startLocalRegistryProcess } from './local-registry.mjs'; -import { makeShrinkwrap, registryDist } from './make-shrinkwrap.mjs'; +import { packRelease } from './pack-release.mjs'; const repo = new URL('..', import.meta.url).pathname; const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); @@ -126,29 +125,14 @@ const check = (what, ok, detail = '') => { }; const work = mkdtempSync(join(tmpdir(), 'mn-fresh-install-')); -const shrinkwrapPath = join(repo, 'npm-shrinkwrap.json'); let registry; try { - // The workspace packages mn depends on, packed from this checkout (until they - // are published, a consumer's npm finds them nowhere else), served with mn by - // a local registry, as npm installs a published package: npm honours mn's - // shrinkwrap only when its registry says the package has one. - const tarballs = join(work, 'registry'); - mkdirSync(tarballs); - const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); - const workspaces = manifest.workspaces - .map((dir) => ({ dir, name: JSON.parse(readFileSync(join(repo, dir, 'package.json'), 'utf-8')).name })) - .filter(({ name }) => manifest.dependencies[name] !== undefined); - for (const { dir } of workspaces) run('npm', ['pack', '--pack-destination', tarballs], join(repo, dir)); - registry = await startLocalRegistryProcess(tarballs); - - // mn, packed with the shrinkwrap the release job writes. - makeShrinkwrap({ dist: registryDist(registry.url), out: shrinkwrapPath }); - try { - run('npm', ['pack', '--pack-destination', tarballs], repo); - } finally { - rmSync(shrinkwrapPath, { force: true }); - } + // mn and the workspace packages it depends on, as a release publishes them, + // served by a local registry as npm installs a published package. + const packed = await packRelease(join(work, 'registry')); + registry = packed.registry; + const { workspaces } = packed; + const manifest = { name: packed.name, version: packed.version }; const version = manifest.version; const prefix = join(work, 'prefix'); @@ -168,7 +152,7 @@ try { const engine = join(installed, 'node_modules', name); for (const sdk of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { const copies = resolvedCopies(engine, sdk); - check(`${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(installed.length)}`).join(', ')); + check(`${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(installed).length)}`).join(', ')); } } diff --git a/scripts/local-registry.mjs b/scripts/local-registry.mjs index e2c6034c..659e5146 100644 --- a/scripts/local-registry.mjs +++ b/scripts/local-registry.mjs @@ -91,12 +91,12 @@ export function startLocalRegistry(dir, port = 0) { /** * The same registry in a process of its own, for a caller that runs npm - * synchronously (and so can't answer npm's requests itself); resolves to its - * URL and a close function. + * synchronously (and so can't answer npm's requests itself), on `port` (0: any + * free one); resolves to its URL and a close function. */ -export function startLocalRegistryProcess(dir) { +export function startLocalRegistryProcess(dir, port = 0) { return new Promise((resolve, reject) => { - const child = spawn(process.execPath, [fileURLToPath(import.meta.url), dir, '0'], { stdio: ['ignore', 'pipe', 'inherit'] }); + const child = spawn(process.execPath, [fileURLToPath(import.meta.url), dir, String(port)], { stdio: ['ignore', 'pipe', 'inherit'] }); child.on('error', reject); child.on('exit', (code) => reject(new Error(`the local registry exited (${code}) before it was ready`))); child.stdout.on('data', (chunk) => { diff --git a/scripts/pack-release.mjs b/scripts/pack-release.mjs new file mode 100644 index 00000000..be325123 --- /dev/null +++ b/scripts/pack-release.mjs @@ -0,0 +1,61 @@ +// mn as a release publishes it, packed into a folder: the workspace packages +// mn depends on, and mn with the shrinkwrap the release job writes, its +// workspace packages' tarballs and integrity as a local registry on `port` +// serves them (scripts/local-registry.mjs). Until those packages are on npm, a +// consumer's npm finds them nowhere else, and npm honours mn's shrinkwrap only +// when its registry says the package has one; so the folder is installed +// through a local registry on the same port, wherever that runs: +// +// node scripts/local-registry.mjs +// npm install -g --registry http://127.0.0.1: midnight-wallet-cli@ +// +// node scripts/pack-release.mjs [--port ] (after `npm run build`) + +import { execFileSync } from 'node:child_process'; +import { mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { startLocalRegistryProcess } from './local-registry.mjs'; +import { makeShrinkwrap, registryDist } from './make-shrinkwrap.mjs'; + +const repo = fileURLToPath(new URL('..', import.meta.url)); +const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); + +/** + * Packs the release into `dir` for a registry on `port` (0: any free one), + * leaving that registry running; resolves to it, mn's name and version, and + * the workspace packages packed. + */ +export async function packRelease(dir, port = 0) { + mkdirSync(dir, { recursive: true }); + const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); + const workspaces = manifest.workspaces + .map((folder) => ({ folder, name: JSON.parse(readFileSync(join(repo, folder, 'package.json'), 'utf-8')).name })) + .filter(({ name }) => manifest.dependencies[name] !== undefined); + for (const { folder } of workspaces) run('npm', ['pack', '--pack-destination', dir], join(repo, folder)); + const registry = await startLocalRegistryProcess(dir, port); + + const shrinkwrapPath = join(repo, 'npm-shrinkwrap.json'); + try { + makeShrinkwrap({ dist: registryDist(registry.url), out: shrinkwrapPath }); + run('npm', ['pack', '--pack-destination', dir], repo); + } catch (error) { + await registry.close(); + throw error; + } finally { + rmSync(shrinkwrapPath, { force: true }); + } + return { registry, name: manifest.name, version: manifest.version, workspaces }; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const dir = process.argv[2]; + const at = process.argv.indexOf('--port'); + if (!dir) { + console.error('usage: node scripts/pack-release.mjs [--port ]'); + process.exit(2); + } + const { registry, name, version } = await packRelease(resolve(dir), at === -1 ? 0 : Number(process.argv[at + 1])); + await registry.close(); + console.log(`packed ${name}@${version} into ${resolve(dir)}, for a registry on ${registry.url}`); +} From 21d38df3fb93e6d8c6319ba4242ea3fb0a94d011 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 11:29:56 -0800 Subject: [PATCH 45/88] Each engine ships a shrinkwrap of the SDK set the tests ran on A program that installed the engine packages without mn got a fresh resolution: two ledger copies and the beta engine's old node client, and both engines refused to load. Only mn shipped a shrinkwrap. make-shrinkwrap.mjs now also writes one for a workspace package (--package packages/engine-*). The engine's tree spans its own folder and the root's in the lockfile, so it is laid out afresh as Node resolves it, nesting a package beside the one that needs it when another version sits above. It leaves out the workspace packages the engine depends on (core and chain): the program installs those itself, so the process holds one copy of each. mn's own shrinkwrap is unchanged, byte for byte. The release job writes each engine's shrinkwrap before publishing it, the engines' files lists include it, and pack-release.mjs packs the engines with theirs. The clean-install check now also installs core, chain and both engines into a program outside mn and checks one copy of each SDK runtime per engine, one core and one chain, and that each engine loads. --- .github/workflows/release-sidecar.yml | 2 + .gitignore | 1 + packages/engine-beta/package.json | 3 +- packages/engine-rc/package.json | 3 +- scripts/fresh-install-check.mjs | 32 ++++++- scripts/make-shrinkwrap.mjs | 115 ++++++++++++++++++-------- scripts/pack-release.mjs | 22 +++-- 7 files changed, 137 insertions(+), 41 deletions(-) diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index 1aa80978..ca863cfc 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -174,6 +174,8 @@ jobs: if npm view "$name@$version" version >/dev/null 2>&1; then echo "$name@$version is published already" else + # An engine ships the SDK set the tests ran on, for a program that installs it without mn. + case "$name" in @kuiralabs/midnight-engine-*) node scripts/make-shrinkwrap.mjs --package "$dir" ;; esac ( cd "$dir" && npm publish --access public ${{ env.PRERELEASE == 'true' && '--tag next' || '' }} ) fi done diff --git a/.gitignore b/.gitignore index 0025cc47..521c888e 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,4 @@ packages/dust-sync-*/dust-sync.exe # Written by the release job just before publishing (scripts/make-shrinkwrap.mjs), never kept. /npm-shrinkwrap.json +/packages/*/npm-shrinkwrap.json diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index cf5dd69d..0c394f23 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -29,7 +29,8 @@ } }, "files": [ - "dist" + "dist", + "npm-shrinkwrap.json" ], "scripts": { "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index 7d75c2ff..11747a11 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -29,7 +29,8 @@ } }, "files": [ - "dist" + "dist", + "npm-shrinkwrap.json" ], "scripts": { "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index ad391166..0c6afcbe 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -16,7 +16,7 @@ // node scripts/fresh-install-check.mjs (after `npm run build`) import { execFileSync, spawn } from 'node:child_process'; -import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { packRelease } from './pack-release.mjs'; @@ -216,6 +216,36 @@ try { const unknown = named.filter((name) => !tools.includes(name)); check(`${uri} names only tools the server has`, unknown.length === 0, unknown.length > 0 ? `not a tool: ${unknown.join(', ')}` : `${named.length} of ${tools.length} tools named`); } + + // A program that loads an engine without mn: it installs core, chain and the + // engines from the registry, each engine with the shrinkwrap it ships, and + // gets each engine's SDK set once beside one core and one chain it shares. + const outside = join(work, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'package.json'), JSON.stringify({ name: 'outside', private: true, type: 'module' })); + run('npm', ['install', '--cache', join(work, 'npm-cache'), '--registry', registry.url, '--no-audit', '--no-fund', ...workspaces.map(({ name, version }) => `${name}@${version}`)], outside); + for (const { name } of workspaces.filter(({ name }) => !name.startsWith('@kuiralabs/midnight-engine-'))) { + const copies = copiesOf(outside, name); + check(`a program outside mn: one copy of ${name}`, copies.length === 1, copies.join(', ')); + } + for (const { name } of workspaces.filter(({ name }) => name.startsWith('@kuiralabs/midnight-engine-'))) { + const engine = join(outside, 'node_modules', name); + for (const sdk of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { + const copies = resolvedCopies(engine, sdk); + check(`a program outside mn: ${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(outside).length)}`).join(', ')); + } + } + writeFileSync(join(outside, 'load.mjs'), ` + import { engineFor, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; + import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; + setHostPathsSource(() => ({ stateRoot: ${JSON.stringify(join(outside, 'state'))}, home: ${JSON.stringify(outside)} })); + setEngineLoader(async (set) => set === 'beta' ? (await import('@kuiralabs/midnight-engine-beta')).betaEngine : (await import('@kuiralabs/midnight-engine-rc')).rcEngine); + try { console.log((await engineFor(process.argv[2])).set); } catch (error) { console.log(error.code ?? error.message); } + `); + for (const [network, set] of [['undeployed', 'rc'], ['stagenet', 'beta']]) { + const loaded = run(process.execPath, ['load.mjs', network], outside).trim(); + check(`a program outside mn loads the ${set} engine for ${network}`, loaded === set, loaded); + } } catch (error) { check('the fresh install and its checks ran', false, String(error.stderr || error.message).trim().split('\n').slice(-3).join(' | ')); } finally { diff --git a/scripts/make-shrinkwrap.mjs b/scripts/make-shrinkwrap.mjs index 1bef0c49..eef258ff 100644 --- a/scripts/make-shrinkwrap.mjs +++ b/scripts/make-shrinkwrap.mjs @@ -12,11 +12,18 @@ // shrinkwrap each is the published package, with its own nested entries moved // under it, and its tarball and integrity from `dist`. // -// The release job writes it beside package.json just before publishing (npm -// packs npm-shrinkwrap.json with the package); the workspace never keeps one, -// since npm ci would then install from it instead of package-lock.json. +// Each SDK engine ships one too (`--package packages/engine-*`), so a program +// that installs an engine without mn gets the set the tests ran on. It leaves +// out the workspace packages the engine depends on (core and chain): those +// are shared with the program that loads the engine, which installs them +// itself, so the process holds one copy of each. // -// node scripts/make-shrinkwrap.mjs [--registry ] [--out ] +// The release job writes them beside each package.json just before +// publishing (npm packs npm-shrinkwrap.json with the package, as each `files` +// list says); the workspace never keeps one, since npm ci would then install +// from it instead of package-lock.json. +// +// node scripts/make-shrinkwrap.mjs [--package ] [--registry ] [--out ] import { execFileSync } from 'node:child_process'; import { readFileSync, writeFileSync } from 'node:fs'; @@ -50,11 +57,21 @@ function parentOf(path) { } /** - * mn's shrinkwrap from `lock` (package-lock.json) and `manifest` - * (package.json); `dist(name, version)` gives a workspace package's published - * tarball and integrity. + * The shrinkwrap of the package at `at` in the workspace (mn, at the root, by + * default) from `lock` (package-lock.json) and `manifest` (its package.json); + * `dist(name, version)` gives a workspace package's published tarball and + * integrity. The dependencies in `leaveOut` are not in it: a consumer resolves + * them itself, so one copy serves the consumer and the package alike. + * + * mn's tree is laid out as the lockfile lays it out: the lockfile is already + * an install of mn. A workspace package's tree spans its own folder and the + * root's, so it is laid out afresh, as Node resolves it: each dependency the + * lockfile resolves goes as high as it can without hiding another version a + * package above already resolves, else beside the package that needs it. An + * engine's own SDK set then sits at its top while the shared packages it also + * reaches keep their versions. */ -export function shrinkwrapFrom(lock, manifest, dist) { +export function shrinkwrapFrom(lock, manifest, dist, { at = '', leaveOut = [] } = {}) { const packages = lock.packages; // The workspace packages, by their folder: what mn's links point at. const workspaces = new Map( @@ -62,39 +79,62 @@ export function shrinkwrapFrom(lock, manifest, dist) { .filter(([path, entry]) => path.startsWith('node_modules/') && entry.link === true) .map(([path, entry]) => [entry.resolved, path.slice('node_modules/'.length)]), ); - // Where each lockfile path lands in an install of mn. - const placed = (path) => { + const depsOf = (entry) => [ + ...Object.keys(entry.dependencies ?? {}).map((name) => [name, false]), + ...Object.keys(entry.optionalDependencies ?? {}).map((name) => [name, true]), + ...Object.keys(entry.peerDependencies ?? {}).map((name) => [name, entry.peerDependenciesMeta?.[name]?.optional === true]), + ]; + + // The layout: each place in the install (a node_modules path under the + // package, '' for the package itself) and the lockfile path installed there. + const layout = new Map([['', at]]); + /** Where the lockfile itself puts a path in an install of mn. */ + const lockPlace = (path) => { for (const [dir, name] of workspaces) { if (path === dir) return `node_modules/${name}`; if (path.startsWith(dir + '/node_modules/')) return `node_modules/${name}${path.slice(dir.length)}`; } return path; }; - - const reached = new Set(); - const visit = (from, deps) => { + /** Where Node finds `name` from the package at `place`, or undefined. */ + const found = (place, name) => { + for (let dir = place; ; dir = dir.lastIndexOf('/node_modules/') === -1 ? '' : dir.slice(0, dir.lastIndexOf('/node_modules/'))) { + const candidate = dir === '' ? `node_modules/${name}` : `${dir}/node_modules/${name}`; + if (layout.has(candidate)) return candidate; + if (dir === '') return undefined; + } + }; + const queue = [['', depsOf(manifest).filter(([name]) => !leaveOut.includes(name))]]; + while (queue.length > 0) { + const [place, deps] = queue.shift(); for (const [name, optional] of deps) { - let path = resolveIn(packages, from, name); + let path = resolveIn(packages, layout.get(place), name); if (path === undefined) { if (optional) continue; - throw new Error(`package-lock.json resolves no ${name} for ${from || 'mn'}`); + throw new Error(`package-lock.json resolves no ${name} for ${layout.get(place) || 'mn'}`); } if (packages[path].link === true) path = packages[path].resolved; - if (reached.has(path)) continue; - reached.add(path); - visit(path, depsOf(packages[path])); + if (at === '') { + const to = lockPlace(path); + if (!layout.has(to)) { + layout.set(to, path); + queue.push([to, depsOf(packages[path])]); + } + continue; + } + const there = found(place, name); + if (there !== undefined && layout.get(there) === path) continue; + // Nothing by that name above: at the top. Another version above: beside the package that needs this one. + const to = there === undefined ? `node_modules/${name}` : place === '' ? `node_modules/${name}` : `${place}/node_modules/${name}`; + if (layout.has(to)) throw new Error(`${path} and ${layout.get(to)} both land at ${to} in ${manifest.name}'s shrinkwrap`); + layout.set(to, path); + queue.push([to, depsOf(packages[path])]); } - }; - const depsOf = (entry) => [ - ...Object.keys(entry.dependencies ?? {}).map((name) => [name, false]), - ...Object.keys(entry.optionalDependencies ?? {}).map((name) => [name, true]), - ...Object.keys(entry.peerDependencies ?? {}).map((name) => [name, entry.peerDependenciesMeta?.[name]?.optional === true]), - ]; - visit('', depsOf(manifest)); + } const { name, version, license, bin, engines, dependencies, optionalDependencies } = manifest; const out = { '': { name, version, license, dependencies, optionalDependencies, bin, engines } }; - for (const path of [...reached].sort()) { + for (const [place, path] of [...layout].filter(([place]) => place !== '').sort(([a], [b]) => a.localeCompare(b))) { const entry = { ...packages[path] }; delete entry.dev; delete entry.devOptional; @@ -102,16 +142,24 @@ export function shrinkwrapFrom(lock, manifest, dist) { Object.assign(entry, dist(workspaces.get(path), entry.version)); delete entry.name; } - out[placed(path)] = entry; + out[place] = entry; } return { name, version, lockfileVersion: 3, requires: true, packages: out }; } -/** Writes mn's shrinkwrap to `out`; returns its packages. */ -export function makeShrinkwrap({ dist = registryDist('https://registry.npmjs.org'), out = join(repo, 'npm-shrinkwrap.json') } = {}) { +/** + * Writes the shrinkwrap of the package in `dir` (mn, the repository's root, + * by default) to `out` (beside its package.json by default); returns its + * packages. A workspace package's shrinkwrap leaves out the workspace + * packages it depends on. + */ +export function makeShrinkwrap({ dir = '', dist = registryDist('https://registry.npmjs.org'), out = join(repo, dir, 'npm-shrinkwrap.json') } = {}) { const lock = JSON.parse(readFileSync(join(repo, 'package-lock.json'), 'utf-8')); - const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); - const shrinkwrap = shrinkwrapFrom(lock, manifest, dist); + const manifest = JSON.parse(readFileSync(join(repo, dir, 'package.json'), 'utf-8')); + const workspaceNames = (JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')).workspaces ?? []) + .map((folder) => JSON.parse(readFileSync(join(repo, folder, 'package.json'), 'utf-8')).name); + const leaveOut = dir === '' ? [] : Object.keys(manifest.dependencies ?? {}).filter((name) => workspaceNames.includes(name)); + const shrinkwrap = shrinkwrapFrom(lock, manifest, dist, { at: dir, leaveOut }); writeFileSync(out, JSON.stringify(shrinkwrap, null, 2) + '\n'); return shrinkwrap.packages; } @@ -128,8 +176,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { const at = process.argv.indexOf(name); return at === -1 ? undefined : process.argv[at + 1]; }; - const out = flag('--out') ?? join(repo, 'npm-shrinkwrap.json'); - const packages = makeShrinkwrap({ dist: registryDist(flag('--registry') ?? 'https://registry.npmjs.org'), out }); + const dir = (flag('--package') ?? '').replace(/\/$/, ''); + const out = flag('--out') ?? join(repo, dir, 'npm-shrinkwrap.json'); + const packages = makeShrinkwrap({ dir, dist: registryDist(flag('--registry') ?? 'https://registry.npmjs.org'), out }); for (const copy of copiesInShrinkwrap(packages, '@midnightntwrk/ledger-v9')) console.log(`ledger-v9 ${copy.version} ${copy.path}`); console.log(`wrote ${out}`); } diff --git a/scripts/pack-release.mjs b/scripts/pack-release.mjs index be325123..a1bc6ed8 100644 --- a/scripts/pack-release.mjs +++ b/scripts/pack-release.mjs @@ -1,7 +1,7 @@ // mn as a release publishes it, packed into a folder: the workspace packages -// mn depends on, and mn with the shrinkwrap the release job writes, its -// workspace packages' tarballs and integrity as a local registry on `port` -// serves them (scripts/local-registry.mjs). Until those packages are on npm, a +// mn depends on (each engine with its shrinkwrap), and mn with the shrinkwrap +// the release job writes, its workspace packages' tarballs and integrity as a +// local registry on `port` serves them (scripts/local-registry.mjs). Until those packages are on npm, a // consumer's npm finds them nowhere else, and npm honours mn's shrinkwrap only // when its registry says the package has one; so the folder is installed // through a local registry on the same port, wherever that runs: @@ -30,9 +30,21 @@ export async function packRelease(dir, port = 0) { mkdirSync(dir, { recursive: true }); const manifest = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf-8')); const workspaces = manifest.workspaces - .map((folder) => ({ folder, name: JSON.parse(readFileSync(join(repo, folder, 'package.json'), 'utf-8')).name })) + .map((folder) => { + const { name, version } = JSON.parse(readFileSync(join(repo, folder, 'package.json'), 'utf-8')); + return { folder, name, version }; + }) .filter(({ name }) => manifest.dependencies[name] !== undefined); - for (const { folder } of workspaces) run('npm', ['pack', '--pack-destination', dir], join(repo, folder)); + // Each engine with the shrinkwrap the release job writes for it. + for (const { folder, name } of workspaces) { + const engine = name.startsWith('@kuiralabs/midnight-engine-'); + if (engine) makeShrinkwrap({ dir: folder }); + try { + run('npm', ['pack', '--pack-destination', dir], join(repo, folder)); + } finally { + if (engine) rmSync(join(repo, folder, 'npm-shrinkwrap.json'), { force: true }); + } + } const registry = await startLocalRegistryProcess(dir, port); const shrinkwrapPath = join(repo, 'npm-shrinkwrap.json'); From 7b1b1ef6d64aafa1dc2152a391d347e3f8292e32 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 12:08:15 -0800 Subject: [PATCH 46/88] The wallet session meets the SDK's cold-start race Just after a wallet opens, the SDK can refuse for lack of NIGHT the wallet has: its coin index isn't built yet. The CLI's own writes retry that by restarting the wallet; the session did not, and a program that swapped straight after a Dust registration got the raw refusal (seen in the gate, on the scratch chain). Until it has built its first transaction, a session now meets that refusal by stopping the wallet, waiting 5 s and reopening it, up to five attempts in all, as the CLI does. It never reopens once it has built a transaction (reopening would revert it under the caller), nor for a Dust shortage, which only waiting fixes. openWalletSession and the CLI's in-process session (connectWallet) both pass the reopening. --- packages/cli-core/src/lib/wallet-session.ts | 62 +++++++++++++++--- src/__tests__/wallet-session.test.ts | 69 +++++++++++++++++++++ src/lib/serve-payer.ts | 4 +- 3 files changed, 123 insertions(+), 12 deletions(-) diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index b27bb355..ebfbebe9 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -5,15 +5,25 @@ // everything (the program is the operator), so its rules hold here too: a // transaction balanced or built but never submitted is reverted on close, and // one the chain refuses is reverted at once. Transactions travel as hex. +// +// Just after a wallet opens, the SDK can refuse for lack of NIGHT the wallet +// has (its coin index isn't built yet: the cold-start race the CLI's own +// writes retry). Until the session has built its first transaction, it meets +// that by reopening the wallet and asking again, a few times. import { engineFor, type DAppConnector, type OpenedConnector, type TransactionDetail } from './engine.ts'; import type { NetworkConfig, NetworkName } from './network.ts'; import { resolveNetwork } from './resolve-network.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; import { throwIfCancelled } from './errors.ts'; +import { isColdStartRace } from './sdk-errors.ts'; /** The calls a session makes, under one connection name for the connector's pending transactions. */ const SESSION_CONNECTION = 'wallet-session'; +/** How many times a session asks for its first transaction through the cold-start race, in all. */ +const COLD_START_ATTEMPTS = 5; +/** The wait before reopening the wallet, which gives the indexer time to settle. */ +const COLD_START_DELAY_MS = 5_000; /** A wallet's addresses on the session's network, bech32m, and its shielded keys, hex. */ export interface WalletAddresses { @@ -70,20 +80,53 @@ export interface WalletSession { close(): Promise; } -/** The session over a connector opened in this process; closing it stops the connector. */ +export interface SessionReopening { + /** Opens the same wallet again, as it was first opened. */ + reopen: () => Promise; + /** What the session is doing, for a progress line. */ + onMessage?: (message: string) => void; + /** The wait before each reopening, in milliseconds. */ + delayMs?: number; +} + +/** + * The session over a connector opened in this process; closing it stops the + * connector. With `reopening`, the session meets the cold-start race before + * its first transaction by reopening the wallet. + */ export function sessionOver( network: NetworkName, opened: OpenedConnector, readTransaction: (tx: string, stage: 'unsealed' | 'sealed') => TransactionDetail[], + reopening?: SessionReopening, ): WalletSession { - const { connector } = opened; + let current = opened; let requestId = 0; let closed = false; + // Once a transaction is built, reopening would revert it under the caller. + let built = false; const call = async (method: string, params: Record): Promise => { if (closed) throw new Error('The wallet session is closed'); - const handler = handlerOf(connector, method); + const handler = handlerOf(current.connector, method); return handler(params, { notify: () => {}, connectionId: SESSION_CONNECTION, requestId: ++requestId, metadata: {} }); }; + /** Builds a transaction, through the cold-start race while it is the session's first. */ + const build = async (method: string, params: Record): Promise => { + for (let attempt = 1; ; attempt++) { + try { + const { tx } = (await call(method, params)) as { tx: string }; + built = true; + return tx; + } catch (err) { + if (built || reopening === undefined || attempt >= COLD_START_ATTEMPTS || !isColdStartRace(err)) throw err; + reopening.onMessage?.(`Refreshing wallet state (attempt ${attempt + 1}/${COLD_START_ATTEMPTS})...`); + await current.stop(); + await new Promise((resolve) => setTimeout(resolve, reopening.delayMs ?? COLD_START_DELAY_MS)); + if (closed) throw new Error('The wallet session is closed'); + current = await reopening.reopen(); + } + } + }; return { network, @@ -106,15 +149,14 @@ export function sessionOver( return { unshielded: { ...unshielded }, shielded: { ...shielded }, dust: balance }; }, async balanceTransaction(tx) { - return ((await call('balanceUnsealedTransaction', { tx })) as { tx: string }).tx; + return build('balanceUnsealedTransaction', { tx }); }, async swap(give, take) { - const result = await call('makeIntent', { + return build('makeIntent', { desiredInputs: give.map(({ kind, type, value }) => ({ kind, type, value })), desiredOutputs: take.map(({ kind, type, value, recipient }) => ({ kind, type, value, recipient })), options: { payFees: true }, }); - return (result as { tx: string }).tx; }, async sign(data, encoding) { return (await call('signData', { data, options: { encoding, keyType: 'unshielded' } })) as SignedData; @@ -129,8 +171,8 @@ export function sessionOver( async close() { if (closed) return; closed = true; - await connector.revertPendingTxs(SESSION_CONNECTION).catch(() => { /* best-effort: the wallet is stopping */ }); - await opened.stop(); + await current.connector.revertPendingTxs(SESSION_CONNECTION).catch(() => { /* best-effort: the wallet is stopping */ }); + await current.stop(); }, }; } @@ -168,7 +210,7 @@ export async function openWalletSession(options: OpenWalletSessionOptions): Prom const networkConfig = options.networkConfig ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } } }).config; const engine = await engineFor(network); - const opened = await engine.wallet.openConnector({ + const open = () => engine.wallet.openConnector({ seed, network, networkConfig, @@ -178,5 +220,5 @@ export async function openWalletSession(options: OpenWalletSessionOptions): Prom signal, onMessage: options.onMessage ?? (() => {}), }); - return sessionOver(network, opened, (tx, stage) => engine.ledger.readTransaction(tx, stage)); + return sessionOver(network, await open(), (tx, stage) => engine.ledger.readTransaction(tx, stage), { reopen: open, onMessage: options.onMessage }); } diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts index 9faef07b..d606503a 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/src/__tests__/wallet-session.test.ts @@ -117,4 +117,73 @@ describe('wallet session', () => { await expect(session.balances()).rejects.toThrow('The wallet session is closed'); await expect(session.readTransaction('beef', 'sealed')).rejects.toThrow('The wallet session is closed'); }); + + describe('the cold-start race before its first transaction', () => { + // The SDK's refusal when its coin index isn't built yet, as the session met it live just after a Dust registration. + const coldStart = () => Object.assign(new Error('Insufficient funds'), { _tag: 'Wallet.InsufficientFunds', tokenType: NIGHT_RAW, amount: 0n }); + const dustShortage = () => Object.assign(new Error('Insufficient Funds: could not balance dust'), { _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' }); + const give = [{ kind: 'unshielded' as const, type: NIGHT_RAW, value: 5n }]; + const take = [{ kind: 'unshielded' as const, type: OTHER_TOKEN, value: 9n, recipient: RECIPIENT }]; + + /** A wallet opened in this process whose swaps answer as `initSwap` says, and its stop. */ + function openedWith(initSwap: () => Promise) { + const bundle = createBundleStub({ initSwap }); + const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + return { connector, stop: vi.fn(async () => { connector.dispose(); }) }; + } + + it('reopens the wallet and asks again, until the swap is built', async () => { + const first = openedWith(() => Promise.reject(coldStart())); + const second = openedWith(() => Promise.reject(coldStart())); + const third = openedWith(() => Promise.resolve({ type: 'SWAP' })); + const reopen = vi.fn().mockResolvedValueOnce(second).mockResolvedValueOnce(third); + const messages: string[] = []; + const session = sessionOver('undeployed', first, () => [], { reopen, onMessage: (m) => messages.push(m), delayMs: 0 }); + + expect(await session.swap(give, take)).toBe('abcd'); + expect(reopen).toHaveBeenCalledTimes(2); + expect(first.stop).toHaveBeenCalledOnce(); + expect(second.stop).toHaveBeenCalledOnce(); + expect(messages).toEqual(['Refreshing wallet state (attempt 2/5)...', 'Refreshing wallet state (attempt 3/5)...']); + await session.close(); + expect(third.stop).toHaveBeenCalledOnce(); + }); + + it('gives up after five attempts with the SDK\'s refusal', async () => { + const reopen = vi.fn(async () => openedWith(() => Promise.reject(coldStart()))); + const session = sessionOver('undeployed', openedWith(() => Promise.reject(coldStart())), () => [], { reopen, delayMs: 0 }); + + await expect(session.swap(give, take)).rejects.toMatchObject({ _tag: 'Wallet.InsufficientFunds' }); + expect(reopen).toHaveBeenCalledTimes(4); + await session.close(); + }); + + it('does not reopen once it has built a transaction, which reopening would revert under the caller', async () => { + const initSwap = vi.fn().mockResolvedValueOnce({ type: 'SWAP' }).mockRejectedValue(coldStart()); + const reopen = vi.fn(); + const session = sessionOver('undeployed', openedWith(initSwap), () => [], { reopen, delayMs: 0 }); + + await session.swap(give, take); + await expect(session.swap(give, take)).rejects.toMatchObject({ _tag: 'Wallet.InsufficientFunds' }); + expect(reopen).not.toHaveBeenCalled(); + await session.close(); + }); + + it('does not reopen for a Dust shortage, which only waiting fixes', async () => { + vi.useFakeTimers(); + try { + const reopen = vi.fn(); + const session = sessionOver('undeployed', openedWith(() => Promise.reject(dustShortage())), () => [], { reopen, delayMs: 0 }); + + // The connector waits for Dust between its own attempts; none comes. + const failure = session.swap(give, take).catch((e: unknown) => e); + await vi.advanceTimersByTimeAsync(60_000); + expect(await failure).toBeInstanceOf(Error); + expect(reopen).not.toHaveBeenCalled(); + await session.close(); + } finally { + vi.useRealTimers(); + } + }); + }); }); diff --git a/src/lib/serve-payer.ts b/src/lib/serve-payer.ts index 8c52c1b8..2ae48f43 100644 --- a/src/lib/serve-payer.ts +++ b/src/lib/serve-payer.ts @@ -44,8 +44,8 @@ async function serveWallet(port: number, { network, endpoints }: PayingTarget, w async function connectWallet({ network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { openConnector } = await import('./serve-manager.ts'); const engine = await engineFor(network); - const opened = await openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, signal }); - return sessionOver(network, opened, (tx, stage) => engine.ledger.readTransaction(tx, stage)); + const open = () => openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, signal }); + return sessionOver(network, await open(), (tx, stage) => engine.ledger.readTransaction(tx, stage), { reopen: open, onMessage: (msg) => progress.update(msg) }); } /** The payer whose served wallet is the mn serve on `port`. */ From a494daec06f3f74db68b10b8e40f43b7679e3c90 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 12:21:25 -0800 Subject: [PATCH 47/88] The chain package asks whether a swap offer's coins are spent (SC) A taker must know an offer is still live before it builds or proves anything: the ledger refuses a dead offer only after the taker's proof. spendsOf asks the indexer for the shielded spends of the offer's nullifiers, from block 0 to the chain's current tip, keeping only exact matches (the query matches by prefix). When the indexer can't finish the check it says it can't tell (LivenessUnknownError) rather than calling the offer live. The shared subscription driver now finishes when the server completes a subscription: a bounded query such as a block range ends that way, and the driver used to wait for its idle timer instead. --- .../chain/src/lib/graphql-ws-subscription.ts | 8 ++ packages/chain/src/lib/offer-liveness.ts | 68 +++++++++++++++ scripts/check-layering.mjs | 2 +- src/__tests__/offer-liveness.test.ts | 83 +++++++++++++++++++ 4 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 packages/chain/src/lib/offer-liveness.ts create mode 100644 src/__tests__/offer-liveness.test.ts diff --git a/packages/chain/src/lib/graphql-ws-subscription.ts b/packages/chain/src/lib/graphql-ws-subscription.ts index 170e38b8..2d0022ad 100644 --- a/packages/chain/src/lib/graphql-ws-subscription.ts +++ b/packages/chain/src/lib/graphql-ws-subscription.ts @@ -9,6 +9,7 @@ // // Settle semantics (uniform across readers): // - onNext returns true (caught up to tip) → resolve, partial=false +// - the server completes the subscription → resolve, partial=false (a bounded query's end) // - idle window elapses → resolve, partial=false // - initial-silence elapses (resume only) → resolve, partial=false // - the stream closes with no events → resolve, partial=false @@ -24,6 +25,7 @@ import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/mid /** Why the subscription settled. `timeout`/`closed-early` are the partial cases. */ export type WsFinishReason = | 'caught-up' + | 'complete' | 'idle' | 'initial-silence' | 'graceful-close' @@ -150,6 +152,12 @@ export function subscribeGraphqlWs( return; } + // A bounded query (one with an end, such as a block range) ends with complete. + if (msg.type === 'complete') { + finishOk('complete', false); + return; + } + if (msg.type !== 'next') return; if (msg.payload?.errors) { diff --git a/packages/chain/src/lib/offer-liveness.ts b/packages/chain/src/lib/offer-liveness.ts new file mode 100644 index 00000000..89f6a9e6 --- /dev/null +++ b/packages/chain/src/lib/offer-liveness.ts @@ -0,0 +1,68 @@ +// Whether a swap offer can still be taken: none of the coins it spends may be +// spent already. Asked of the indexer before the taker builds or proves +// anything, because the ledger refuses a dead offer only after the taker's +// proof is done. + +import { queryIndexer } from './indexer-graphql.ts'; +import { subscribeGraphqlWs } from './graphql-ws-subscription.ts'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; + +const SPENT_NULLIFIERS = `subscription Spent($prefixes: [HexEncoded!]!, $fromBlock: Int, $toBlock: Int) { + shieldedNullifierTransactions(nullifierPrefixes: $prefixes, fromBlock: $fromBlock, toBlock: $toBlock) { + nullifier + transactionHash + blockHeight + } +}`; + +/** How long the indexer may take to answer, and to finish the spend check, before it fails rather than hangs. */ +const ANSWER_TIMEOUT_MS = 60_000; +/** Silence between two spends after which the check counts as finished. */ +const SPEND_IDLE_MS = 15_000; + +/** One of an offer's coins, spent on chain. */ +export interface CoinSpend { + nullifier: string; + transactionHash: string; + blockHeight: number; +} + +/** The indexer did not finish the spend check, so whether the offer is live is unknown. */ +export class LivenessUnknownError extends Error { + constructor(reason: string) { + super(`Can't tell whether the offer is still live: ${reason}`); + this.name = 'LivenessUnknownError'; + } +} + +/** + * The spends of the coins with these nullifiers (hex), from `fromBlock` to the + * chain's current tip; empty while none is spent. + */ +export async function spendsOf( + indexer: { indexer: string; indexerWS: string }, + nullifiers: readonly string[], + options: { fromBlock?: number; signal?: AbortSignal } = {}, +): Promise { + throwIfCancelled(options.signal); + const { block } = await queryIndexer<{ block: { height: number } | null }>(indexer.indexer, '{ block { height } }', undefined, ANSWER_TIMEOUT_MS, options.signal); + if (block === null) throw new LivenessUnknownError('the indexer has no blocks yet'); + const wanted = new Set(nullifiers.map((n) => n.toLowerCase())); + const spends: CoinSpend[] = []; + const finished = await subscribeGraphqlWs(indexer.indexerWS, { + query: SPENT_NULLIFIERS, + variables: { prefixes: nullifiers, fromBlock: options.fromBlock ?? 0, toBlock: block.height }, + onNext: (data) => { + const spend = (data as { shieldedNullifierTransactions?: CoinSpend }).shieldedNullifierTransactions; + // Prefixes match more than the exact nullifier; only an exact one is a spend of the offer's coin. + if (spend !== undefined && wanted.has(spend.nullifier.toLowerCase())) spends.push(spend); + return false; + }, + buildResult: (partial) => !partial, + timeoutMs: ANSWER_TIMEOUT_MS, + idleMs: SPEND_IDLE_MS, + signal: options.signal, + }); + if (!finished) throw new LivenessUnknownError(`the indexer didn't finish the spend check in ${ANSWER_TIMEOUT_MS / 1000} s`); + return spends; +} diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 09115e9d..0f85eb24 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -47,7 +47,7 @@ const HOMES = [ ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], ['chain', /^commands\/status(\.definition)?\.ts$/], - ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription|tx-segments)\.ts$/], + ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription|tx-segments|offer-liveness)\.ts$/], ['wallet', /^commands\/(wallet|generate|address|genesis-address|info|balance|transfer|airdrop|dust|cache)(\.definition)?\.ts$/], ['wallet', /^lib\/(derivation|derive-address|wallet-config|seed-resolver|passphrase|facade|wallet-data-repository|transfer|transfer-request|sync-eta|wallet-can-pay|wallet-create|airdrop|wallet-protector|chain-caches|wallet-paths|fork-schedule)\.ts$/], diff --git a/src/__tests__/offer-liveness.test.ts b/src/__tests__/offer-liveness.test.ts new file mode 100644 index 00000000..a6424236 --- /dev/null +++ b/src/__tests__/offer-liveness.test.ts @@ -0,0 +1,83 @@ +// Whether a swap offer's coins are spent, asked of the indexer before a taker +// builds anything. A real in-process HTTP server answers the tip query and a +// real WebSocket server speaks graphql-transport-ws as the indexer does, +// ending the bounded subscription with complete. + +import { afterEach, describe, expect, it } from 'vitest'; +import { WebSocketServer } from 'ws'; +import { spendsOf, LivenessUnknownError } from '@kuiralabs/midnight-chain/lib/offer-liveness'; +import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; + +const N1 = 'aa'.repeat(32); +const N2 = 'bb'.repeat(32); + +let servers: WebSocketServer[] = []; +let http: LocalIndexer | undefined; +afterEach(async () => { for (const s of servers) s.close(); servers = []; await http?.close(); http = undefined; }); + +/** The indexer's subscription side: on subscribe, sends `spends` as next payloads, then complete unless told not to. */ +async function subscriptions(spends: unknown[], complete = true): Promise<{ url: string; subscribed: Array<{ query: string; variables: Record }> }> { + const subscribed: Array<{ query: string; variables: Record }> = []; + const wss = new WebSocketServer({ host: '127.0.0.1', port: 0 }); + servers.push(wss); + wss.on('connection', (ws) => { + ws.on('message', (raw) => { + const msg = JSON.parse(raw.toString()); + if (msg.type === 'connection_init') ws.send(JSON.stringify({ type: 'connection_ack' })); + else if (msg.type === 'subscribe') { + subscribed.push(msg.payload); + for (const spend of spends) ws.send(JSON.stringify({ id: msg.id, type: 'next', payload: { data: { shieldedNullifierTransactions: spend } } })); + if (complete) ws.send(JSON.stringify({ id: msg.id, type: 'complete' })); + } + }); + }); + await new Promise((resolve) => wss.on('listening', () => resolve())); + const addr = wss.address(); + return { url: `ws://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`, subscribed }; +} + +describe('spendsOf', () => { + it('finds none while the offer is live, asking from block 0 to the chain\'s tip', async () => { + http = await startLocalIndexer(() => JSON.stringify({ data: { block: { height: 812 } } })); + const ws = await subscriptions([]); + + expect(await spendsOf({ indexer: http.url, indexerWS: ws.url }, [N1, N2])).toEqual([]); + expect(ws.subscribed).toHaveLength(1); + expect(ws.subscribed[0]!.variables).toEqual({ prefixes: [N1, N2], fromBlock: 0, toBlock: 812 }); + }); + + it('returns the exact spends of the offer\'s coins, not a coin that only shares a prefix', async () => { + http = await startLocalIndexer(() => JSON.stringify({ data: { block: { height: 900 } } })); + const taken = { nullifier: N2, transactionHash: 'cd'.repeat(32), blockHeight: 899 }; + const ws = await subscriptions([{ nullifier: 'bb'.repeat(31) + 'cc', transactionHash: 'ef'.repeat(32), blockHeight: 10 }, taken]); + + expect(await spendsOf({ indexer: http.url, indexerWS: ws.url }, [N1, N2])).toEqual([taken]); + }); + + it('says it can\'t tell when the indexer has no blocks yet', async () => { + http = await startLocalIndexer(() => JSON.stringify({ data: { block: null } })); + const ws = await subscriptions([]); + + await expect(spendsOf({ indexer: http.url, indexerWS: ws.url }, [N1])).rejects.toBeInstanceOf(LivenessUnknownError); + expect(ws.subscribed).toEqual([]); + }); + + it('says it can\'t tell when the indexer drops the check part way through', async () => { + http = await startLocalIndexer(() => JSON.stringify({ data: { block: { height: 5 } } })); + const wss = new WebSocketServer({ host: '127.0.0.1', port: 0 }); + servers.push(wss); + wss.on('connection', (ws) => ws.on('message', (raw) => { + const msg = JSON.parse(raw.toString()); + if (msg.type === 'connection_init') ws.send(JSON.stringify({ type: 'connection_ack' })); + else if (msg.type === 'subscribe') { + ws.send(JSON.stringify({ id: msg.id, type: 'next', payload: { data: { shieldedNullifierTransactions: { nullifier: N1, transactionHash: 'ab'.repeat(32), blockHeight: 3 } } } })); + ws.close(); + } + })); + await new Promise((resolve) => wss.on('listening', () => resolve())); + const addr = wss.address(); + + await expect(spendsOf({ indexer: http.url, indexerWS: `ws://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}` }, [N1])) + .rejects.toThrow("Can't tell whether the offer is still live"); + }); +}); From abdae559f2748bb0d8286595ad3e367595f02e77 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 13:01:06 -0800 Subject: [PATCH 48/88] Swap offers: read, made, taken, cancelled, and kept from being spent (SB to SF) The maker's half of a shielded swap, proved and signed and handed to a taker as an offer, on both engines. Reading (SB): each engine reads an offer from its bytes alone with its own ledger (readOffer: terms, id, the nullifiers of the coins it spends), refusing anything that is not a sealed, shielded-only half swap (NOT_AN_OFFER); core checks those terms against the agreed ones (TERMS_MISMATCH). Tested on a real offer recorded on a local chain (fixtures/record-swap-offer.ts): the beta engine reads an offer made on the rc engine. The offer file (core): an envelope with the network, terms, id, mn's own expiry (OFFER_EXPIRED) and the transaction; a taker refuses one that says other than its bytes. Making (SD): the session's makeOffer builds the half swap with no fee (the taker pays) and hands it off, so closing the session or the abandon timer no longer reverts it. Each wallet's open offers are kept in mn's state; a transaction the connector or the shielded transfer builds that would spend an open offer's coins is refused and reverted (OFFER_COINS_IN_USE), unless it is the cancel. Taking (SE): the connector validates the offer's signatures and proofs before building anything, adds this wallet's half and the whole fee, validates the result in full, and holds it pending until submitted. Cancelling (SF): the maker spends its whole balance of the offered token back to itself; refused unless that spends every coin of the offer. --- .../cli-core/src/commands/core.guidance.ts | 8 ++ packages/cli-core/src/lib/engine.ts | 12 ++ packages/cli-core/src/lib/exit-codes.ts | 14 +- packages/cli-core/src/lib/offer-envelope.ts | 98 ++++++++++++++ packages/cli-core/src/lib/open-offers.ts | 88 +++++++++++++ packages/cli-core/src/lib/swap-offer.ts | 66 ++++++++++ packages/cli-core/src/lib/wallet-session.ts | 44 ++++++- packages/engine-beta/src/dapp-connector.ts | 113 +++++++++++++++- packages/engine-beta/src/index.ts | 3 + packages/engine-beta/src/offer-reader.ts | 50 +++++++ packages/engine-beta/src/wallet.ts | 16 +++ packages/engine-rc/src/dapp-connector.ts | 113 +++++++++++++++- packages/engine-rc/src/index.ts | 3 + packages/engine-rc/src/offer-reader.ts | 50 +++++++ packages/engine-rc/src/wallet.ts | 16 +++ scripts/check-layering.mjs | 10 +- .../engine-beta-offer-reader.test.ts | 13 ++ src/__tests__/fixtures/record-swap-offer.ts | 86 ++++++++++++ src/__tests__/fixtures/swap-offer.ts | 6 + src/__tests__/helpers/connector-stub.ts | 6 + src/__tests__/helpers/connector-suite.ts | 123 ++++++++++++++++++ src/__tests__/helpers/offer-reader-suite.ts | 55 ++++++++ src/__tests__/offer-envelope.test.ts | 51 ++++++++ src/__tests__/offer-reader.test.ts | 7 + src/__tests__/open-offers.test.ts | 59 +++++++++ src/__tests__/swap-offer.test.ts | 33 +++++ src/__tests__/wallet-session.test.ts | 18 +++ 27 files changed, 1144 insertions(+), 17 deletions(-) create mode 100644 packages/cli-core/src/lib/offer-envelope.ts create mode 100644 packages/cli-core/src/lib/open-offers.ts create mode 100644 packages/cli-core/src/lib/swap-offer.ts create mode 100644 packages/engine-beta/src/offer-reader.ts create mode 100644 packages/engine-rc/src/offer-reader.ts create mode 100644 src/__tests__/engine-beta-offer-reader.test.ts create mode 100644 src/__tests__/fixtures/record-swap-offer.ts create mode 100644 src/__tests__/fixtures/swap-offer.ts create mode 100644 src/__tests__/helpers/offer-reader-suite.ts create mode 100644 src/__tests__/offer-envelope.test.ts create mode 100644 src/__tests__/offer-reader.test.ts create mode 100644 src/__tests__/open-offers.test.ts create mode 100644 src/__tests__/swap-offer.test.ts diff --git a/packages/cli-core/src/commands/core.guidance.ts b/packages/cli-core/src/commands/core.guidance.ts index 80cab0e9..b14d26c9 100644 --- a/packages/cli-core/src/commands/core.guidance.ts +++ b/packages/cli-core/src/commands/core.guidance.ts @@ -54,6 +54,14 @@ export const coreGuidance: PackageGuidance = { server for that network MIXED_SDK_LAYOUT 1 mn was installed without its shrinkwrap (bun's installer): install it with npm + NOT_AN_OFFER 2 The bytes given as a swap offer are not one; + ask the maker for it again + TERMS_MISMATCH 2 A swap offer's own terms differ from the agreed + ones; don't take it + OFFER_EXPIRED 2 A swap offer is past the expiry its maker set; + ask the maker for a new one + OFFER_COINS_IN_USE 2 A spend would use coins an open swap offer of + this wallet's holds; cancel the offer first CANCELLED 7 Operation cancelled (SIGINT) UNKNOWN 1 Unclassified error `, diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index c24772c5..73e9bc04 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -5,6 +5,8 @@ // loader at start (the shell, the engines it ships), as it does the settings. // Loading an engine loads its SDK, so the loader imports it only when asked. +import type { OfferContents } from './swap-offer.ts'; +import type { OpenOffer } from './open-offers.ts'; import { sdkSetOfNetwork, type NetworkConfig, type NetworkName } from './network.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; import type { VerboseLog } from './verbose.ts'; @@ -57,6 +59,10 @@ export interface EngineLedger { nightTokenId(): string; /** What a serialized transaction (hex) is, as an approval prompt shows it; never throws. */ readTransaction(txHex: string, stage: 'unsealed' | 'sealed'): TransactionDetail[]; + /** What a swap offer (a sealed transaction, hex) gives and wants, and the coins it spends, from its bytes alone. Throws NotAnOfferError for anything else. */ + readOffer(txHex: string): OfferContents; + /** The nullifiers of the shielded coins a transaction (hex, sealed or not) spends. Throws when the bytes aren't a ledger-9 transaction. */ + spentNullifiers(txHex: string): string[]; } /** A contract's ledger state read without its compiled contract: cells as their field-aligned bytes in hex, maps by size. */ @@ -369,6 +375,12 @@ export interface DAppConnector { handlers: Record; /** Revert all pending (unsubmitted) transactions for a connection, releasing locked coins. */ revertPendingTxs(connectionId: string): Promise; + /** Stop tracking a built transaction as this connection's (a swap offer handed to a taker): it is never reverted. False when the connection holds no such transaction. */ + handOffPendingTx(connectionId: string, txHex: string): boolean; + /** Takes a swap offer (sealed, hex): validates it before building, adds this wallet's half and the fee, validates the whole, and holds it pending for the connection; the swap, sealed, hex. The terms and liveness are the caller's to check first. */ + takeOffer(connectionId: string, txHex: string): Promise; + /** Cancels open swap offers of this wallet's by spending their coins back to itself; the cancel, sealed, hex, pending until submitted. Refused when it wouldn't spend every coin of every offer. */ + cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; /** True if any connection has a balanced-but-not-submitted transaction. */ hasPendingTxs(): boolean; dispose(): void; diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index b8ad34e8..630385c3 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -59,6 +59,14 @@ export const ERROR_CODES = { OTHER_SDK_SET: 'OTHER_SDK_SET', /** An engine's SDK packages reach more than one copy of its ledger: mn was installed without its shrinkwrap (bun's installer). Recovery: install mn with npm. */ MIXED_SDK_LAYOUT: 'MIXED_SDK_LAYOUT', + /** Bytes given as a swap offer are not one: not a sealed ledger-9 transaction, or not a shielded half swap. Recovery: ask the maker for the offer again. */ + NOT_AN_OFFER: 'NOT_AN_OFFER', + /** A swap offer's own terms differ from the agreed ones. Recovery: don't take it; agree the terms again with the maker. */ + TERMS_MISMATCH: 'TERMS_MISMATCH', + /** A swap offer is past the expiry its maker set. Recovery: ask the maker for a new one. */ + OFFER_EXPIRED: 'OFFER_EXPIRED', + /** A spend would use coins an open swap offer of this wallet's holds, cancelling it. Recovery: cancel the offer first (mn swap cancel), or wait until it is taken. */ + OFFER_COINS_IN_USE: 'OFFER_COINS_IN_USE', /** mn's passphrase was wrong, or a sealed secret was changed. Recovery: run it again with the passphrase mn was protected with. */ WRONG_PASSPHRASE: 'WRONG_PASSPHRASE', /** A secret was needed and no passphrase could be had. Recovery: set MN_PASSPHRASE, or run at a terminal. */ @@ -66,8 +74,8 @@ export const ERROR_CODES = { UNKNOWN: 'UNKNOWN', } as const; -/** Errors about mn's passphrase, the caller's to fix, classified by their code before any usage error. */ -const PASSPHRASE_ERROR_CODES: ReadonlySet = new Set([ERROR_CODES.WRONG_PASSPHRASE, ERROR_CODES.PASSPHRASE_REQUIRED]); +/** Errors the caller fixes (mn's passphrase, an offer that isn't the agreed one), classified by their code before any usage error. */ +const CALLER_ERROR_CODES: ReadonlySet = new Set([ERROR_CODES.WRONG_PASSPHRASE, ERROR_CODES.PASSPHRASE_REQUIRED, ERROR_CODES.NOT_AN_OFFER, ERROR_CODES.TERMS_MISMATCH, ERROR_CODES.OFFER_EXPIRED, ERROR_CODES.OFFER_COINS_IN_USE]); /** Typed setup errors that carry their own `code`; classified by it, not by message text. */ const SETUP_ERROR_CODES: ReadonlySet = new Set([ @@ -97,7 +105,7 @@ export function classifyError(err: Error): ClassifiedError { // A usage error is the caller's to fix, whatever its text (the CLI and MCP agree on this). // (Tested through `unknown`: UsageError has Error's shape, so narrowing `err` itself would leave `never`.) const code = (err as { code?: unknown }).code; - if (typeof code === 'string' && PASSPHRASE_ERROR_CODES.has(code)) { + if (typeof code === 'string' && CALLER_ERROR_CODES.has(code)) { return { exitCode: EXIT_INVALID_ARGS, errorCode: code as ErrorCode }; } if (isUsageError(err as unknown)) { diff --git a/packages/cli-core/src/lib/offer-envelope.ts b/packages/cli-core/src/lib/offer-envelope.ts new file mode 100644 index 00000000..378fe3a8 --- /dev/null +++ b/packages/cli-core/src/lib/offer-envelope.ts @@ -0,0 +1,98 @@ +// The offer file: what a maker hands a taker. The transaction's bytes are the +// offer; around them the envelope says the network, the terms, the id and +// when the maker means the offer to expire, so a taker can see what it is +// before reading the bytes. The bytes stay the truth: a taker reads them with +// its engine and refuses an envelope that says otherwise. +// +// Expiry is mn's own (the chain gives a shielded half swap none): a taker +// using mn refuses an expired offer, and only the maker cancelling it makes +// that binding on chain. + +import type { NetworkName } from './network.ts'; +import { NotAnOfferError, type OfferContents, type SwapLeg, type SwapTerms } from './swap-offer.ts'; + +/** What the envelope's `kind` says, so a file is known for an offer at a glance. */ +export const OFFER_ENVELOPE_KIND = 'midnight-swap-offer'; +/** The envelope's version: a reader refuses one it doesn't know. */ +export const OFFER_ENVELOPE_VERSION = 1; + +/** An offer as its file holds it. */ +export interface OfferEnvelope { + network: NetworkName; + id: string; + terms: SwapTerms; + /** When the maker means the offer to expire. */ + expiresAt: Date; + /** The offer: a sealed ledger-9 transaction, hex. */ + tx: string; +} + +/** An offer past the expiry its maker set. */ +export class OfferExpiredError extends Error { + readonly code = 'OFFER_EXPIRED'; + constructor(id: string, expiresAt: Date) { + super(`The offer ${id.slice(0, 16)}… expired at ${expiresAt.toISOString()}; ask the maker for a new one`); + this.name = 'OfferExpiredError'; + } +} + +/** The envelope as its file's text: JSON, amounts as decimal strings. */ +export function encodeOfferEnvelope(envelope: OfferEnvelope): string { + const leg = ({ token, amount }: SwapLeg) => ({ token, amount: amount.toString() }); + return JSON.stringify({ + kind: OFFER_ENVELOPE_KIND, + version: OFFER_ENVELOPE_VERSION, + network: envelope.network, + id: envelope.id, + terms: { give: leg(envelope.terms.give), want: leg(envelope.terms.want) }, + expiresAt: envelope.expiresAt.toISOString(), + tx: envelope.tx, + }, null, 2) + '\n'; +} + +/** Reads an offer file's text. Throws NotAnOfferError for text that isn't one. */ +export function decodeOfferEnvelope(text: string): OfferEnvelope { + let raw: Record; + try { + raw = JSON.parse(text) as Record; + } catch { + throw new NotAnOfferError('the file is not an offer file (not JSON)'); + } + if (raw === null || typeof raw !== 'object' || raw.kind !== OFFER_ENVELOPE_KIND) throw new NotAnOfferError('the file is not an offer file'); + if (raw.version !== OFFER_ENVELOPE_VERSION) throw new NotAnOfferError(`the offer file is version ${String(raw.version)}; this mn reads version ${OFFER_ENVELOPE_VERSION}`); + const text_ = (field: string, value: unknown) => { + if (typeof value !== 'string' || value === '') throw new NotAnOfferError(`the offer file has no ${field}`); + return value; + }; + const leg = (field: string, value: unknown): SwapLeg => { + const { token, amount } = (value ?? {}) as { token?: unknown; amount?: unknown }; + if (typeof token !== 'string' || !/^[0-9a-fA-F]{64}$/.test(token) || typeof amount !== 'string' || !/^[1-9][0-9]*$/.test(amount)) { + throw new NotAnOfferError(`the offer file's ${field} is not a token and a whole amount`); + } + return { token, amount: BigInt(amount) }; + }; + const terms = (raw.terms ?? {}) as { give?: unknown; want?: unknown }; + const expiresAt = new Date(text_('expiry', raw.expiresAt)); + if (Number.isNaN(expiresAt.getTime())) throw new NotAnOfferError('the offer file\'s expiry is not a date'); + return { + network: text_('network', raw.network) as NetworkName, + id: text_('id', raw.id), + terms: { give: leg('give', terms.give), want: leg('want', terms.want) }, + expiresAt, + tx: text_('transaction', raw.tx), + }; +} + +/** Throws NotAnOfferError when the envelope says other than its bytes, read by the engine, do. */ +export function assertEnvelopeMatches(envelope: OfferEnvelope, read: OfferContents): void { + const legDiffers = (a: SwapLeg, b: SwapLeg) => a.token.toLowerCase() !== b.token.toLowerCase() || a.amount !== b.amount; + if (envelope.id !== read.id) throw new NotAnOfferError('the offer file\'s id is not its transaction\'s'); + if (legDiffers(envelope.terms.give, read.terms.give) || legDiffers(envelope.terms.want, read.terms.want)) { + throw new NotAnOfferError('the offer file states other terms than its transaction holds'); + } +} + +/** Throws OfferExpiredError once the envelope's expiry has passed. */ +export function assertOfferUnexpired(envelope: OfferEnvelope, now: Date): void { + if (now.getTime() >= envelope.expiresAt.getTime()) throw new OfferExpiredError(envelope.id, envelope.expiresAt); +} diff --git a/packages/cli-core/src/lib/open-offers.ts b/packages/cli-core/src/lib/open-offers.ts new file mode 100644 index 00000000..7685eb5e --- /dev/null +++ b/packages/cli-core/src/lib/open-offers.ts @@ -0,0 +1,88 @@ +// The offers a wallet has made and not yet seen taken or cancelled, kept in +// mn's state. An offer's coins are committed to it until then: a later spend +// of any of them would cancel the offer, so a wallet's spends are checked +// against this record (assertSpendsNoOfferCoin) and refused unless the caller +// says to cancel. Expiry is not an end: the chain lets an expired offer be +// taken until its coins are spent, so it stays open until then. + +import { join } from 'node:path'; +import { readJsonIfPresent, writeJsonDurably } from './durable-file.ts'; +import { stateRoot } from './state-root.ts'; +import type { NetworkName } from './network.ts'; +import type { SwapLeg, SwapTerms } from './swap-offer.ts'; + +export interface OpenOffer { + id: string; + terms: SwapTerms; + /** The nullifiers of the coins the offer spends, hex. */ + nullifiers: string[]; + madeAt: Date; + expiresAt: Date; +} + +/** A spend would use coins an open offer of this wallet's holds, cancelling it. */ +export class OfferCoinsInUseError extends Error { + readonly code = 'OFFER_COINS_IN_USE'; + readonly offerIds: string[]; + constructor(offerIds: string[]) { + super(`This would spend coins held by ${offerIds.length === 1 ? 'an open swap offer' : `${offerIds.length} open swap offers`} (${offerIds.map((id) => `${id.slice(0, 16)}…`).join(', ')}), cancelling ${offerIds.length === 1 ? 'it' : 'them'}. Cancel ${offerIds.length === 1 ? 'it' : 'them'} first, or wait until ${offerIds.length === 1 ? 'it is' : 'they are'} taken.`); + this.name = 'OfferCoinsInUseError'; + this.offerIds = offerIds; + } +} + +interface StoredLeg { token: string; amount: string } +interface StoredOffer { id: string; terms: { give: StoredLeg; want: StoredLeg }; nullifiers: string[]; madeAt: string; expiresAt: string } + +/** The file holding a wallet's open offers on a network; the wallet by its unshielded address there. */ +export function openOffersFile(network: NetworkName, walletAddress: string): string { + return join(stateRoot(), 'swap-offers', network, `${walletAddress}.json`); +} + +const leg = (stored: StoredLeg): SwapLeg => ({ token: stored.token, amount: BigInt(stored.amount) }); +const stored = (l: SwapLeg): StoredLeg => ({ token: l.token, amount: l.amount.toString() }); + +/** The wallet's open offers on the network. */ +export function readOpenOffers(network: NetworkName, walletAddress: string): OpenOffer[] { + const file = readJsonIfPresent<{ offers: StoredOffer[] }>(openOffersFile(network, walletAddress)); + return (file?.offers ?? []).map((o) => ({ + id: o.id, + terms: { give: leg(o.terms.give), want: leg(o.terms.want) }, + nullifiers: o.nullifiers, + madeAt: new Date(o.madeAt), + expiresAt: new Date(o.expiresAt), + })); +} + +function writeOpenOffers(network: NetworkName, walletAddress: string, offers: OpenOffer[]): void { + writeJsonDurably(openOffersFile(network, walletAddress), { + offers: offers.map((o) => ({ + id: o.id, + terms: { give: stored(o.terms.give), want: stored(o.terms.want) }, + nullifiers: o.nullifiers, + madeAt: o.madeAt.toISOString(), + expiresAt: o.expiresAt.toISOString(), + })), + }); +} + +/** Records an offer the wallet made. */ +export function recordOpenOffer(network: NetworkName, walletAddress: string, offer: OpenOffer): void { + const offers = readOpenOffers(network, walletAddress).filter((o) => o.id !== offer.id); + writeOpenOffers(network, walletAddress, [...offers, offer]); +} + +/** Closes the wallet's offers with these ids (taken or cancelled); the ones it had. */ +export function closeOpenOffers(network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[] { + const offers = readOpenOffers(network, walletAddress); + const closing = offers.filter((o) => ids.includes(o.id)); + if (closing.length > 0) writeOpenOffers(network, walletAddress, offers.filter((o) => !ids.includes(o.id))); + return closing; +} + +/** Throws OfferCoinsInUseError when a transaction spending these nullifiers would use an open offer's coins, unless it cancels exactly those offers. */ +export function assertSpendsNoOfferCoin(open: readonly OpenOffer[], spent: readonly string[], cancelling: readonly string[] = []): void { + const spentSet = new Set(spent.map((n) => n.toLowerCase())); + const hit = open.filter((o) => !cancelling.includes(o.id) && o.nullifiers.some((n) => spentSet.has(n.toLowerCase()))); + if (hit.length > 0) throw new OfferCoinsInUseError(hit.map((o) => o.id)); +} diff --git a/packages/cli-core/src/lib/swap-offer.ts b/packages/cli-core/src/lib/swap-offer.ts new file mode 100644 index 00000000..ba3bb15e --- /dev/null +++ b/packages/cli-core/src/lib/swap-offer.ts @@ -0,0 +1,66 @@ +// A swap offer: the maker's half of a shielded swap, proved and signed, and +// deliberately unbalanced. It spends what the maker gives and pays the maker +// what it wants back, so the ledger accepts it only once a taker adds the +// other half: the wanted tokens in, and the given tokens out to itself. +// Neither side can change the other's terms, and there are no partial fills. +// +// What an offer is comes from its bytes alone: each engine reads them with its +// own ledger (EngineLedger.readOffer). Whether those are the terms the two +// sides agreed is checked here, before the taker builds or spends anything. + +/** One side of a swap: a shielded token by its raw type (hex), and how much of it in base units. */ +export interface SwapLeg { + token: string; + amount: bigint; +} + +/** A swap as the maker states it: what the maker gives, and what it wants back. */ +export interface SwapTerms { + give: SwapLeg; + want: SwapLeg; +} + +/** What an offer's bytes say it is. */ +export interface OfferContents { + /** The sha256 of the bytes, hex: short enough for a chat message. */ + id: string; + terms: SwapTerms; + /** The nullifiers of the coins it spends, hex: once any of them is on chain, the offer is dead. */ + nullifiers: string[]; +} + +/** Bytes that are not one shielded swap half: not a sealed ledger-9 transaction, a balanced one, more than two tokens, or unshielded parts. */ +export class NotAnOfferError extends Error { + readonly code = 'NOT_AN_OFFER'; + constructor(reason: string, options?: { cause?: unknown }) { + super(`Not a swap offer: ${reason}`, options); + this.name = 'NotAnOfferError'; + } +} + +/** An offer whose own terms differ from the terms the two sides agreed. */ +export class TermsMismatchError extends Error { + readonly code = 'TERMS_MISMATCH'; + readonly agreed: SwapTerms; + readonly offered: SwapTerms; + constructor(agreed: SwapTerms, offered: SwapTerms) { + super(`The offer gives ${describeLeg(offered.give)} for ${describeLeg(offered.want)}, not the agreed ${describeLeg(agreed.give)} for ${describeLeg(agreed.want)}`); + this.name = 'TermsMismatchError'; + this.agreed = agreed; + this.offered = offered; + } +} + +/** Throws TermsMismatchError unless the offer's own terms are exactly the agreed ones. */ +export function checkTerms(offered: SwapTerms, agreed: SwapTerms): void { + if (!sameLeg(offered.give, agreed.give) || !sameLeg(offered.want, agreed.want)) { + throw new TermsMismatchError(agreed, offered); + } +} + +/** A leg as a person reads it: the amount, then the token's raw type. */ +export function describeLeg(leg: SwapLeg): string { + return `${leg.amount} of token ${leg.token}`; +} + +const sameLeg = (a: SwapLeg, b: SwapLeg) => a.token.toLowerCase() === b.token.toLowerCase() && a.amount === b.amount; diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index ebfbebe9..ad6813b2 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -17,6 +17,8 @@ import { resolveNetwork } from './resolve-network.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; import { throwIfCancelled } from './errors.ts'; import { isColdStartRace } from './sdk-errors.ts'; +import type { SwapLeg } from './swap-offer.ts'; +import type { OpenOffer } from './open-offers.ts'; /** The calls a session makes, under one connection name for the connector's pending transactions. */ const SESSION_CONNECTION = 'wallet-session'; @@ -70,6 +72,20 @@ export interface WalletSession { balanceTransaction(tx: string): Promise; /** A swap offer: the wallet gives `give` for `take`, paying its fees; the transaction to submit or hand on. */ swap(give: TokenAmount[], take: TokenPayment[]): Promise; + /** + * The maker's half of a shielded swap: it gives `give` and is paid `want` to + * its own shielded address, paying no fee (the taker pays the swap's). The + * offer (sealed, hex) is handed off: closing the session doesn't cancel it. + */ + makeOffer(give: SwapLeg, want: SwapLeg): Promise; + /** + * Takes a swap offer (sealed, hex): the offer is validated before anything + * is built, then this wallet adds its half and the fee. The swap (sealed, + * hex), to submit. Check the terms and that the offer is live first. + */ + takeOffer(tx: string): Promise; + /** Cancels open swap offers of this wallet's by spending their coins back to itself (a fee in Dust); the cancel (sealed, hex), to submit. */ + cancelOffers(offers: readonly OpenOffer[]): Promise; /** Signs `data` (hex, base64 or text, as `encoding` says) with the wallet's unshielded key. */ sign(data: string, encoding: 'hex' | 'base64' | 'text'): Promise; /** Submits a sealed transaction (hex) and waits for it to be finalized; its hash. */ @@ -111,10 +127,10 @@ export function sessionOver( return handler(params, { notify: () => {}, connectionId: SESSION_CONNECTION, requestId: ++requestId, metadata: {} }); }; /** Builds a transaction, through the cold-start race while it is the session's first. */ - const build = async (method: string, params: Record): Promise => { + const build = async (making: () => Promise): Promise => { for (let attempt = 1; ; attempt++) { try { - const { tx } = (await call(method, params)) as { tx: string }; + const tx = await making(); built = true; return tx; } catch (err) { @@ -149,14 +165,32 @@ export function sessionOver( return { unshielded: { ...unshielded }, shielded: { ...shielded }, dust: balance }; }, async balanceTransaction(tx) { - return build('balanceUnsealedTransaction', { tx }); + return build(async () => ((await call('balanceUnsealedTransaction', { tx })) as { tx: string }).tx); }, async swap(give, take) { - return build('makeIntent', { + return build(async () => ((await call('makeIntent', { desiredInputs: give.map(({ kind, type, value }) => ({ kind, type, value })), desiredOutputs: take.map(({ kind, type, value, recipient }) => ({ kind, type, value, recipient })), options: { payFees: true }, - }); + })) as { tx: string }).tx); + }, + async makeOffer(give, want) { + const { shieldedAddress } = (await call('getShieldedAddresses', {})) as { shieldedAddress: string }; + const offer = await build(async () => ((await call('makeIntent', { + desiredInputs: [{ kind: 'shielded', type: give.token, value: give.amount }], + desiredOutputs: [{ kind: 'shielded', type: want.token, value: want.amount, recipient: shieldedAddress }], + options: { intentId: 'random', payFees: false }, + })) as { tx: string }).tx); + current.connector.handOffPendingTx(SESSION_CONNECTION, offer); + return offer; + }, + async takeOffer(tx) { + if (closed) throw new Error('The wallet session is closed'); + return build(() => current.connector.takeOffer(SESSION_CONNECTION, tx)); + }, + async cancelOffers(offers) { + if (closed) throw new Error('The wallet session is closed'); + return build(() => current.connector.cancelOffers(SESSION_CONNECTION, offers)); }, async sign(data, encoding) { return (await call('signData', { data, options: { encoding, keyType: 'unshielded' } })) as SignedData; diff --git a/packages/engine-beta/src/dapp-connector.ts b/packages/engine-beta/src/dapp-connector.ts index 70f9702d..fe9b22fb 100644 --- a/packages/engine-beta/src/dapp-connector.ts +++ b/packages/engine-beta/src/dapp-connector.ts @@ -19,6 +19,9 @@ import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; +import { readOffer, spentNullifiers } from './offer-reader.ts'; +import { assertSpendsNoOfferCoin, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { NotAnOfferError, describeLeg } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; @@ -40,6 +43,12 @@ export interface DAppConnectorOptions { approvalOptions: ApprovalOptions; /** Under --approve-fees: the most a transaction may cost, and how many may wait unsubmitted. */ feeLimits?: FeeLimits; + /** + * The swap offers this wallet has open. A transaction this connector builds + * that would spend one's coins (cancelling it) is refused, unless it is the + * cancel itself. None when absent. + */ + openOffers?: () => readonly OpenOffer[]; callbacks?: DAppConnectorCallbacks; /** * The state the caller's own sync ended on. Reads answer from it at once; @@ -277,6 +286,17 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto if (txMap.size === 0) pendingTxsByConnection.delete(connectionId); } + /** + * Hands a built transaction on: it is no longer this connection's to revert, + * on disconnect or by the abandon timer. A swap offer is one: its maker never + * submits it, a taker does. False when the connection holds no such transaction. + */ + function handOffPendingTx(connectionId: string, txHex: string): boolean { + const held = pendingTxsByConnection.get(connectionId)?.has(txHex) ?? false; + untrackPendingTx(connectionId, txHex); + return held; + } + /** Revert and clean up all pending transactions for a connection (disconnect). */ async function revertPendingTxs(connectionId: string): Promise { const txMap = pendingTxsByConnection.get(connectionId); @@ -295,7 +315,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto /** Sign, prove (with timeout), and serialize a transaction recipe. * Returns both the serialized hex and the finalized tx object (for tracking/revert). */ - async function processRecipe(recipe: any, tracker?: PhaseTracker): Promise<{ hex: string; finalized: ledger.FinalizedTransaction }> { + async function processRecipe(recipe: any, tracker?: PhaseTracker, cancelling: readonly string[] = []): Promise<{ hex: string; finalized: ledger.FinalizedTransaction }> { tracker?.start('signing'); let signed: any; try { @@ -329,8 +349,19 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } finally { clearTimeout(timer); } + const hex = toHex(finalized.serialize()); + // Spending an open swap offer's coins would cancel it: refused, unless this transaction is that cancel. + const open = options.openOffers?.() ?? []; + if (open.length > 0) { + try { + assertSpendsNoOfferCoin(open, spentNullifiers(hex), cancelling); + } catch (err) { + try { await facade.revert(finalized); } catch { /* best-effort */ } + throw err; + } + } tracker?.complete(); - return { hex: toHex(finalized.serialize()), finalized }; + return { hex, finalized }; } /** @@ -519,6 +550,82 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } } + /** + * Takes a swap offer (a sealed transaction, hex): checks the offer's own + * signatures and proofs before building anything (a forged or tampered one + * fails here, not after this wallet's proof), adds this wallet's half and + * the whole swap's fee, checks the result in full, and holds it pending for + * the connection until it is submitted. Whether these are the agreed terms, + * and whether the offer is still live, are the caller's checks, made first. + */ + async function takeOffer(connectionId: string, txHex: string): Promise { + assertWalletStarted(); + const { terms } = readOffer(txHex); + const offer = adopt(txHex, 'Finalized'); + const context: RpcHandlerContext = { notify: () => {}, connectionId, requestId: 0, metadata: {} }; + const tracker = makeTracker('takeOffer', context); + + tracker.start('approve'); + await requireApproval('takeOffer', [ + { label: 'You give', value: describeLeg(terms.want) }, + { label: 'You get', value: describeLeg(terms.give) }, + ...inspectTxHex(txHex, 'sealed'), + ], context); + + tracker.start('checking'); + try { + await facade.validateTransaction(offer, { flags: { enforceBalancing: false, verifySignatures: true, enforceLimits: false } }); + } catch (cause) { + throw new NotAnOfferError(`its signatures or proofs don't check (${extractErrorDetail(cause)})`, { cause }); + } + + tracker.start('building'); + const ttl = createTtl(); + const recipe: any = await withDustRetry(() => facade.balanceFinalizedTransaction(offer, secretKeys, { ttl, tokenKindsToBalance: 'all' })); + const { hex, finalized } = await processRecipe(recipe, tracker); + try { + await facade.validateTransaction(finalized, { flags: { enforceBalancing: true, verifySignatures: true, enforceLimits: true }, blockData: recipe.blockData }); + } catch (cause) { + try { await facade.revert(finalized); } catch { /* best-effort */ } + throw new Error(`The swap this wallet built doesn't check, so it was not kept: ${extractErrorDetail(cause)}`, { cause }); + } + trackPendingTx(connectionId, hex, finalized); + return hex; + } + + /** + * Cancels open swap offers of this wallet's: sends its whole balance of + * each token they give back to its own shielded address, which spends the + * offers' coins (it costs a fee in Dust). Refused, and nothing kept, when + * the transaction doesn't spend every coin of every offer (one already + * taken, or coins this wallet no longer sees). Held pending for the + * connection until it is submitted. + */ + async function cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise { + assertWalletStarted(); + const state = getState(); + const tokens = [...new Set(offers.map((offer) => offer.terms.give.token))]; + const outputs = tokens.map((type) => { + const amount = state.shielded.balances[type] ?? 0n; + if (amount === 0n) throw createApiError('InvalidRequest', `This wallet holds none of token ${type}: the offer's coins are gone (it was taken)`); + return { type, amount, receiverAddress: state.shielded.address }; + }); + const context: RpcHandlerContext = { notify: () => {}, connectionId, requestId: 0, metadata: {} }; + const tracker = makeTracker('cancelOffers', context); + tracker.start('approve'); + await requireApproval('cancelOffers', offers.map((offer) => ({ label: 'Cancel', value: `${offer.id.slice(0, 16)}… (${describeLeg(offer.terms.give)})` })), context); + tracker.start('building'); + const recipe = await withDustRetry(() => facade.transferTransaction([{ type: 'shielded' as const, outputs }], secretKeys, { ttl: createTtl() })); + const { hex, finalized } = await processRecipe(recipe, tracker, offers.map((offer) => offer.id)); + const spent = new Set(spentNullifiers(hex).map((n) => n.toLowerCase())); + if (!offers.every((offer) => offer.nullifiers.every((n) => spent.has(n.toLowerCase())))) { + try { await facade.revert(finalized); } catch { /* best-effort */ } + throw createApiError('InvalidRequest', 'The cancel would not spend every coin of the offers: one was taken, or its coins are gone'); + } + trackPendingTx(connectionId, hex, finalized); + return hex; + } + /** Encode an SDK address object to bech32m string. */ function encodeAddress(address: any): string { return MidnightBech32m.encode(networkId, address).asString(); @@ -1015,5 +1122,5 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return false; } - return { handlers, revertPendingTxs, hasPendingTxs, dispose }; + return { handlers, revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; } diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts index 0dd7fc12..8dbbb6cf 100644 --- a/packages/engine-beta/src/index.ts +++ b/packages/engine-beta/src/index.ts @@ -14,6 +14,7 @@ import { blockLimitsOf } from './ledger-parameters.ts'; import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; import { inspectTxHex } from './tx-inspect.ts'; +import { readOffer, spentNullifiers } from './offer-reader.ts'; import { betaWallet } from './wallet.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; @@ -42,6 +43,8 @@ export const betaEngine: Engine = { blockLimits: blockLimitsOf, nightTokenId: () => ledger.unshieldedToken().raw, readTransaction: inspectTxHex, + readOffer, + spentNullifiers, }, contracts: { rawState: rawContractState, diff --git a/packages/engine-beta/src/offer-reader.ts b/packages/engine-beta/src/offer-reader.ts new file mode 100644 index 00000000..a0baa7d2 --- /dev/null +++ b/packages/engine-beta/src/offer-reader.ts @@ -0,0 +1,50 @@ +// Reads a swap offer from its bytes alone, trusting nothing said about it: a +// sealed ledger-9 transaction whose only part is a shielded offer in the +// guaranteed segment, giving one token for one other. And which shielded +// coins any transaction spends, so a wallet's spends can be checked against +// the offers it has open. + +import { createHash } from 'node:crypto'; +import { Transaction } from '@midnightntwrk/ledger-v9'; +import { NotAnOfferError, type OfferContents } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; + +export function readOffer(txHex: string): OfferContents { + if (!/^(?:[0-9a-fA-F]{2})+$/.test(txHex)) throw new NotAnOfferError('it is not hex'); + const bytes = Buffer.from(txHex, 'hex'); + let tx; + try { + tx = Transaction.deserialize('signature', 'proof', 'binding', bytes); + } catch (cause) { + throw new NotAnOfferError('it is not a sealed ledger-9 transaction', { cause }); + } + const offer = tx.guaranteedOffer; + if (offer === undefined || (tx.fallibleOffer?.size ?? 0) > 0 || (tx.intents?.size ?? 0) > 0) { + throw new NotAnOfferError('a swap offer has shielded parts only, in the guaranteed segment'); + } + // Deltas are inputs minus outputs: what the maker gives is in surplus, what it wants in deficit. + const gives = [...offer.deltas].filter(([, delta]) => delta > 0n); + const wants = [...offer.deltas].filter(([, delta]) => delta < 0n); + if (gives.length !== 1 || wants.length !== 1) { + throw new NotAnOfferError(`a swap offer gives one token for one other, not ${gives.length} for ${wants.length}`); + } + const [[giveToken, give]] = gives; + const [[wantToken, want]] = wants; + return { + id: createHash('sha256').update(bytes).digest('hex'), + terms: { give: { token: giveToken, amount: give }, want: { token: wantToken, amount: -want } }, + nullifiers: offer.inputs.map((input) => input.nullifier), + }; +} + +/** The nullifiers of the shielded coins a transaction (hex, sealed or not) spends, in every segment. */ +export function spentNullifiers(txHex: string): string[] { + const bytes = Buffer.from(txHex, 'hex'); + let tx; + try { + tx = Transaction.deserialize('signature', 'proof', 'binding', bytes); + } catch { + tx = Transaction.deserialize('signature', 'proof', 'pre-binding', bytes); + } + const offers = [tx.guaranteedOffer, ...(tx.fallibleOffer?.values() ?? [])]; + return offers.flatMap((offer) => offer?.inputs.map((input) => input.nullifier) ?? []); +} diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index ff943347..103f7cba 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -3,6 +3,9 @@ // The flows are the ones the commands, the test preparation and mn serve ran // themselves before the SDK moved behind the engine. +import { deriveUnshieldedAddress } from './derive-address.ts'; +import { assertSpendsNoOfferCoin, readOpenOffers } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { spentNullifiers } from './offer-reader.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; import { MidnightBech32m } from '@midnightntwrk/wallet-sdk-address-format'; import type { @@ -72,6 +75,17 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise progress.update('Generating ZK proof (this may take a few minutes)...'); const finalized = await bundle.facade.finalizeRecipe(signed); + // Spending an open swap offer's coins would cancel it: refused. + const open = readOpenOffers(network, deriveUnshieldedAddress(seed, network)); + if (open.length > 0) { + try { + assertSpendsNoOfferCoin(open, spentNullifiers(Buffer.from(finalized.serialize()).toString('hex'))); + } catch (err) { + try { await bundle.facade.revert(finalized); } catch { /* best-effort */ } + throw err; + } + } + // facade.submitTransaction blocks until the chain finalizes the block // (typically 12 to 30s on hosted networks, ~6 to 12s on localnet). // trackElapsed updates the spinner once a second so users see the wait @@ -220,6 +234,7 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise isFacadeSynced(state, syncMode, built.emptyStreams), dustWaitMs: options.dustWaitMs, + openOffers: () => readOpenOffers(network, address), callbacks: { onPhaseStart: (_connId, _method, phase) => { onMessage(`${phase}...`); @@ -269,6 +284,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { // one that is synced by the rule the sync used. initialState: lastState, isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), + openOffers: () => readOpenOffers(network, address), }), }; return serve(session); diff --git a/packages/engine-rc/src/dapp-connector.ts b/packages/engine-rc/src/dapp-connector.ts index d7381fd7..f575c922 100644 --- a/packages/engine-rc/src/dapp-connector.ts +++ b/packages/engine-rc/src/dapp-connector.ts @@ -19,6 +19,9 @@ import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; +import { readOffer, spentNullifiers } from './offer-reader.ts'; +import { assertSpendsNoOfferCoin, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { NotAnOfferError, describeLeg } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; @@ -41,6 +44,12 @@ export interface DAppConnectorOptions { approvalOptions: ApprovalOptions; /** Under --approve-fees: the most a transaction may cost, and how many may wait unsubmitted. */ feeLimits?: FeeLimits; + /** + * The swap offers this wallet has open. A transaction this connector builds + * that would spend one's coins (cancelling it) is refused, unless it is the + * cancel itself. None when absent. + */ + openOffers?: () => readonly OpenOffer[]; callbacks?: DAppConnectorCallbacks; /** * The state the caller's own sync ended on. Reads answer from it at once; @@ -279,6 +288,17 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto if (txMap.size === 0) pendingTxsByConnection.delete(connectionId); } + /** + * Hands a built transaction on: it is no longer this connection's to revert, + * on disconnect or by the abandon timer. A swap offer is one: its maker never + * submits it, a taker does. False when the connection holds no such transaction. + */ + function handOffPendingTx(connectionId: string, txHex: string): boolean { + const held = pendingTxsByConnection.get(connectionId)?.has(txHex) ?? false; + untrackPendingTx(connectionId, txHex); + return held; + } + /** Revert and clean up all pending transactions for a connection (disconnect). */ async function revertPendingTxs(connectionId: string): Promise { const txMap = pendingTxsByConnection.get(connectionId); @@ -297,7 +317,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto /** Sign, prove (with timeout), and serialize a transaction recipe. * Returns both the serialized hex and the finalized tx object (for tracking/revert). */ - async function processRecipe(recipe: any, tracker?: PhaseTracker): Promise<{ hex: string; finalized: FinalizedTx }> { + async function processRecipe(recipe: any, tracker?: PhaseTracker, cancelling: readonly string[] = []): Promise<{ hex: string; finalized: FinalizedTx }> { tracker?.start('signing'); let signed: any; try { @@ -331,8 +351,19 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } finally { clearTimeout(timer); } + const hex = toHex(finalized.serialize()); + // Spending an open swap offer's coins would cancel it: refused, unless this transaction is that cancel. + const open = options.openOffers?.() ?? []; + if (open.length > 0) { + try { + assertSpendsNoOfferCoin(open, spentNullifiers(hex), cancelling); + } catch (err) { + try { await facade.revert(finalized); } catch { /* best-effort */ } + throw err; + } + } tracker?.complete(); - return { hex: toHex(finalized.serialize()), finalized }; + return { hex, finalized }; } /** @@ -517,6 +548,82 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } } + /** + * Takes a swap offer (a sealed transaction, hex): checks the offer's own + * signatures and proofs before building anything (a forged or tampered one + * fails here, not after this wallet's proof), adds this wallet's half and + * the whole swap's fee, checks the result in full, and holds it pending for + * the connection until it is submitted. Whether these are the agreed terms, + * and whether the offer is still live, are the caller's checks, made first. + */ + async function takeOffer(connectionId: string, txHex: string): Promise { + assertWalletsOnLedger9(); + const { terms } = readOffer(txHex); + const offer = adopt(txHex, 'Finalized'); + const context: RpcHandlerContext = { notify: () => {}, connectionId, requestId: 0, metadata: {} }; + const tracker = makeTracker('takeOffer', context); + + tracker.start('approve'); + await requireApproval('takeOffer', [ + { label: 'You give', value: describeLeg(terms.want) }, + { label: 'You get', value: describeLeg(terms.give) }, + ...inspectTxHex(txHex, 'sealed'), + ], context); + + tracker.start('checking'); + try { + await facade.validateTransaction(offer, { flags: { enforceBalancing: false, verifySignatures: true, enforceLimits: false } }); + } catch (cause) { + throw new NotAnOfferError(`its signatures or proofs don't check (${extractErrorDetail(cause)})`, { cause }); + } + + tracker.start('building'); + const ttl = createTtl(); + const recipe: any = await withDustRetry(() => facade.balanceFinalizedTransaction(offer, { ttl, tokenKindsToBalance: 'all' })); + const { hex, finalized } = await processRecipe(recipe, tracker); + try { + await facade.validateTransaction(finalized, { flags: { enforceBalancing: true, verifySignatures: true, enforceLimits: true }, blockData: recipe.blockData }); + } catch (cause) { + try { await facade.revert(finalized); } catch { /* best-effort */ } + throw new Error(`The swap this wallet built doesn't check, so it was not kept: ${extractErrorDetail(cause)}`, { cause }); + } + trackPendingTx(connectionId, hex, finalized); + return hex; + } + + /** + * Cancels open swap offers of this wallet's: sends its whole balance of + * each token they give back to its own shielded address, which spends the + * offers' coins (it costs a fee in Dust). Refused, and nothing kept, when + * the transaction doesn't spend every coin of every offer (one already + * taken, or coins this wallet no longer sees). Held pending for the + * connection until it is submitted. + */ + async function cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise { + assertWalletsOnLedger9(); + const state = getState(); + const tokens = [...new Set(offers.map((offer) => offer.terms.give.token))]; + const outputs = tokens.map((type) => { + const amount = state.shielded.balances[type] ?? 0n; + if (amount === 0n) throw createApiError('InvalidRequest', `This wallet holds none of token ${type}: the offer's coins are gone (it was taken)`); + return { type, amount, receiverAddress: state.shielded.address }; + }); + const context: RpcHandlerContext = { notify: () => {}, connectionId, requestId: 0, metadata: {} }; + const tracker = makeTracker('cancelOffers', context); + tracker.start('approve'); + await requireApproval('cancelOffers', offers.map((offer) => ({ label: 'Cancel', value: `${offer.id.slice(0, 16)}… (${describeLeg(offer.terms.give)})` })), context); + tracker.start('building'); + const recipe = await withDustRetry(() => facade.transferTransaction([{ type: 'shielded' as const, outputs }], { ttl: createTtl() })); + const { hex, finalized } = await processRecipe(recipe, tracker, offers.map((offer) => offer.id)); + const spent = new Set(spentNullifiers(hex).map((n) => n.toLowerCase())); + if (!offers.every((offer) => offer.nullifiers.every((n) => spent.has(n.toLowerCase())))) { + try { await facade.revert(finalized); } catch { /* best-effort */ } + throw createApiError('InvalidRequest', 'The cancel would not spend every coin of the offers: one was taken, or its coins are gone'); + } + trackPendingTx(connectionId, hex, finalized); + return hex; + } + /** Encode an SDK address object to bech32m string. */ function encodeAddress(address: any): string { return MidnightBech32m.encode(networkId, address).asString(); @@ -1013,5 +1120,5 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return false; } - return { handlers, revertPendingTxs, hasPendingTxs, dispose }; + return { handlers, revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; } diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index 3317e855..489403e7 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -13,6 +13,7 @@ import { blockLimitsOf } from './ledger-parameters.ts'; import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; import { inspectTxHex } from './tx-inspect.ts'; +import { readOffer, spentNullifiers } from './offer-reader.ts'; import { rcWallet } from './wallet.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; @@ -41,6 +42,8 @@ export const rcEngine: Engine = { blockLimits: blockLimitsOf, nightTokenId: () => ledger.unshieldedToken().raw, readTransaction: inspectTxHex, + readOffer, + spentNullifiers, }, contracts: { rawState: rawContractState, diff --git a/packages/engine-rc/src/offer-reader.ts b/packages/engine-rc/src/offer-reader.ts new file mode 100644 index 00000000..a0baa7d2 --- /dev/null +++ b/packages/engine-rc/src/offer-reader.ts @@ -0,0 +1,50 @@ +// Reads a swap offer from its bytes alone, trusting nothing said about it: a +// sealed ledger-9 transaction whose only part is a shielded offer in the +// guaranteed segment, giving one token for one other. And which shielded +// coins any transaction spends, so a wallet's spends can be checked against +// the offers it has open. + +import { createHash } from 'node:crypto'; +import { Transaction } from '@midnightntwrk/ledger-v9'; +import { NotAnOfferError, type OfferContents } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; + +export function readOffer(txHex: string): OfferContents { + if (!/^(?:[0-9a-fA-F]{2})+$/.test(txHex)) throw new NotAnOfferError('it is not hex'); + const bytes = Buffer.from(txHex, 'hex'); + let tx; + try { + tx = Transaction.deserialize('signature', 'proof', 'binding', bytes); + } catch (cause) { + throw new NotAnOfferError('it is not a sealed ledger-9 transaction', { cause }); + } + const offer = tx.guaranteedOffer; + if (offer === undefined || (tx.fallibleOffer?.size ?? 0) > 0 || (tx.intents?.size ?? 0) > 0) { + throw new NotAnOfferError('a swap offer has shielded parts only, in the guaranteed segment'); + } + // Deltas are inputs minus outputs: what the maker gives is in surplus, what it wants in deficit. + const gives = [...offer.deltas].filter(([, delta]) => delta > 0n); + const wants = [...offer.deltas].filter(([, delta]) => delta < 0n); + if (gives.length !== 1 || wants.length !== 1) { + throw new NotAnOfferError(`a swap offer gives one token for one other, not ${gives.length} for ${wants.length}`); + } + const [[giveToken, give]] = gives; + const [[wantToken, want]] = wants; + return { + id: createHash('sha256').update(bytes).digest('hex'), + terms: { give: { token: giveToken, amount: give }, want: { token: wantToken, amount: -want } }, + nullifiers: offer.inputs.map((input) => input.nullifier), + }; +} + +/** The nullifiers of the shielded coins a transaction (hex, sealed or not) spends, in every segment. */ +export function spentNullifiers(txHex: string): string[] { + const bytes = Buffer.from(txHex, 'hex'); + let tx; + try { + tx = Transaction.deserialize('signature', 'proof', 'binding', bytes); + } catch { + tx = Transaction.deserialize('signature', 'proof', 'pre-binding', bytes); + } + const offers = [tx.guaranteedOffer, ...(tx.fallibleOffer?.values() ?? [])]; + return offers.flatMap((offer) => offer?.inputs.map((input) => input.nullifier) ?? []); +} diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index d13dcce7..d5505551 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -3,6 +3,9 @@ // The flows are the ones the commands, the test preparation and mn serve ran // themselves before the SDK moved behind the engine. +import { deriveUnshieldedAddress } from './derive-address.ts'; +import { assertSpendsNoOfferCoin, readOpenOffers } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { spentNullifiers } from './offer-reader.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; import { MidnightBech32m } from '@midnightntwrk/wallet-sdk/address-format'; import type { @@ -71,6 +74,17 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise progress.update('Generating ZK proof (this may take a few minutes)...'); const finalized = await bundle.facade.finalizeRecipe(signed); + // Spending an open swap offer's coins would cancel it: refused. + const open = readOpenOffers(network, deriveUnshieldedAddress(seed, network)); + if (open.length > 0) { + try { + assertSpendsNoOfferCoin(open, spentNullifiers(Buffer.from(finalized.serialize()).toString('hex'))); + } catch (err) { + try { await bundle.facade.revert(finalized); } catch { /* best-effort */ } + throw err; + } + } + // facade.submitTransaction blocks until the chain finalizes the block // (typically 12 to 30s on hosted networks, ~6 to 12s on localnet). // trackElapsed updates the spinner once a second so users see the wait @@ -219,6 +233,7 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise isFacadeSynced(state, syncMode, built.emptyStreams), dustWaitMs: options.dustWaitMs, + openOffers: () => readOpenOffers(network, address), callbacks: { onPhaseStart: (_connId, _method, phase) => { onMessage(`${phase}...`); @@ -268,6 +283,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { // one that is synced by the rule the sync used. initialState: lastState, isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), + openOffers: () => readOpenOffers(network, address), }), }; return serve(session); diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 0f85eb24..b65d14dc 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -21,7 +21,7 @@ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const SRC = join(ROOT, 'src'); // The packages of the split, in the layering's order. -const PACKAGES = ['core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'grant']; +const PACKAGES = ['core', 'chain', 'wallet', 'contract', 'connect', 'swap', 'dev', 'grant']; // Which package a file belongs to: the first pattern that matches its path // under src/ wins. A file that matches nothing fails the check. @@ -42,7 +42,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], @@ -60,6 +60,9 @@ const HOMES = [ ['connect', /^commands\/serve(\.definition)?\.ts$/], ['connect', /^lib\/(dapp-connector|ws-rpc|sign-recipe|serve-manager|serve-payer)\.ts$/], + ['swap', /^commands\/swap(\.definition)?\.ts$/], + ['swap', /^lib\/swap\//], + ['dev', /^commands\/(dev|test|localnet)(\.definition)?\.ts$/], ['dev', /^lib\/localnet\.ts$/], ['dev', /^lib\/(dev|test)\//], @@ -70,7 +73,7 @@ const HOMES = [ // The packages each package may import, its own included. Dependencies point // one way: core, chain, wallet, then contract and connect side by side, then -// dev, then grant. An engine sits beside chain: it uses core and chain, and +// swap (on connect's wallet session), then dev, then grant. An engine sits beside chain: it uses core and chain, and // nothing imports it but core's loader. const MAY_IMPORT = { engine: ['core', 'chain', 'engine'], @@ -79,6 +82,7 @@ const MAY_IMPORT = { wallet: ['core', 'chain', 'wallet'], contract: ['core', 'chain', 'wallet', 'contract'], connect: ['core', 'chain', 'wallet', 'connect'], + swap: ['core', 'chain', 'wallet', 'connect', 'swap'], dev: ['core', 'chain', 'wallet', 'contract', 'connect', 'dev'], grant: ['core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'grant'], // The shell installs every package's commands and guidance, picks the payer diff --git a/src/__tests__/engine-beta-offer-reader.test.ts b/src/__tests__/engine-beta-offer-reader.test.ts new file mode 100644 index 00000000..0b465e8d --- /dev/null +++ b/src/__tests__/engine-beta-offer-reader.test.ts @@ -0,0 +1,13 @@ +// The offer reader on the beta engine, with the beta engine's own ledger. The +// tests are the suite both engines run: helpers/offer-reader-suite.ts. + +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { readOffer, spentNullifiers } from '@kuiralabs/midnight-engine-beta/offer-reader'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { offerReaderSuite } from './helpers/offer-reader-suite.ts'; + +const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +const ledger = await import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, '@midnightntwrk/ledger-v9')!, 'midnight_ledger_wasm_v9_fs.js')).href); + +offerReaderSuite({ set: 'beta', ledger, readOffer, spentNullifiers }); diff --git a/src/__tests__/fixtures/record-swap-offer.ts b/src/__tests__/fixtures/record-swap-offer.ts new file mode 100644 index 00000000..d5109cd7 --- /dev/null +++ b/src/__tests__/fixtures/record-swap-offer.ts @@ -0,0 +1,86 @@ +// Records a real swap offer for the offer reader's tests: on a local ledger-9 +// chain whose genesis wallet (seed 0x…01) holds the dev chain's two shielded +// test tokens, it pays a new maker some of the first, then has the maker offer +// 10 of it for 7 of the second, paying no fee (the taker pays the swap's). +// The offer is never submitted. Writes swap-offer.ts beside this file. +// +// MN_RECORD_NODE=ws://127.0.0.1:29944 MN_RECORD_INDEXER=http://127.0.0.1:28088 MN_RECORD_PROOF_SERVER=http://127.0.0.1:26300 \ +// npx tsx src/__tests__/fixtures/record-swap-offer.ts +// +// Run it only against a chain of your own. + +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { engineFor, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { loadInstalledEngine } from '../../lib/installed-engines.ts'; + +const GIVE = '00'.repeat(31) + '01'; +const WANT = '00'.repeat(31) + '02'; +const GENESIS_SEED = Buffer.from('00'.repeat(31) + '01', 'hex'); + +const required = (name: string) => process.env[name] ?? (() => { throw new Error(`set ${name}`); })(); +const indexer = required('MN_RECORD_INDEXER'); +const networkConfig: NetworkConfig = { + node: required('MN_RECORD_NODE'), + indexer: `${indexer}/api/v4/graphql`, + indexerWS: `${indexer.replace(/^http/, 'ws')}/api/v4/graphql/ws`, + proofServer: required('MN_RECORD_PROOF_SERVER'), + networkId: 'Undeployed', +}; + +const home = mkdtempSync(join(tmpdir(), 'mn-record-offer-')); +setSettingsSource(() => settingsFromEnvironment(process.env)); +setHostPathsSource(() => ({ stateRoot: join(home, '.midnight'), home })); +setEngineLoader(loadInstalledEngine); + +const engine = await engineFor('undeployed'); +const ctx = { notify: () => {}, connectionId: 'record', requestId: 1, metadata: {} }; +const open = (seed: Buffer) => engine.wallet.openConnector({ + seed, network: 'undeployed', networkConfig, address: engine.keys.unshieldedAddress(seed, 'undeployed'), syncMode: 'full', + onMessage: (m) => { if (!/\d+\/\d+/.test(m)) process.stderr.write(` ${m}\n`); }, +}); + +const makerSeed = randomBytes(32); +const makerShielded = engine.keys.shieldedAddress(makerSeed, 'undeployed'); + +const genesis = await open(GENESIS_SEED); +try { + const { tx } = await genesis.connector.handlers.makeTransfer({ desiredOutputs: [{ kind: 'shielded', type: GIVE, value: '100', recipient: makerShielded }] }, ctx) as { tx: string }; + const { txHash } = await genesis.connector.handlers.submitTransaction({ tx }, ctx) as { txHash: string }; + console.error(` paid the maker: ${txHash}`); +} finally { + await genesis.stop(); +} + +const maker = await open(makerSeed); +let offer: string; +try { + for (let attempt = 1; ; attempt++) { + const held = await maker.connector.handlers.getShieldedBalances({}, ctx) as Record; + if ((held[GIVE] ?? 0n) >= 10n) break; + if (attempt > 60) throw new Error('the maker never received the token'); + await new Promise((resolve) => setTimeout(resolve, 2_000)); + } + ({ tx: offer } = await maker.connector.handlers.makeIntent({ + desiredInputs: [{ kind: 'shielded', type: GIVE, value: '10' }], + desiredOutputs: [{ kind: 'shielded', type: WANT, value: '7', recipient: makerShielded }], + options: { intentId: 'random', payFees: false }, + }, ctx) as { tx: string }); +} finally { + await maker.connector.revertPendingTxs('record').catch(() => {}); + await maker.stop(); +} + +writeFileSync(new URL('./swap-offer.ts', import.meta.url), `// A real swap offer: the maker gives 10 of the dev chain's shielded test token 1 for 7 of token 2, paying no fee. +// Made ${new Date().toISOString().slice(0, 10)} on a local ledger-9 chain (rc engine) by record-swap-offer.ts; never submitted. +export const OFFER_GIVE = '${GIVE}'; +export const OFFER_WANT = '${WANT}'; +export const SWAP_OFFER_HEX = + '${offer}'; +`); +console.error(` wrote swap-offer.ts: ${offer.length / 2} bytes`); diff --git a/src/__tests__/fixtures/swap-offer.ts b/src/__tests__/fixtures/swap-offer.ts new file mode 100644 index 00000000..d851b3a0 --- /dev/null +++ b/src/__tests__/fixtures/swap-offer.ts @@ -0,0 +1,6 @@ +// A real swap offer: the maker gives 10 of the dev chain's shielded test token 1 for 7 of token 2, paying no fee. +// Made 2026-11-02 on a local ledger-9 chain (rc engine) by record-swap-offer.ts; never submitted. +export const OFFER_GIVE = '0000000000000000000000000000000000000000000000000000000000000001'; +export const OFFER_WANT = '0000000000000000000000000000000000000000000000000000000000000002'; +export const SWAP_OFFER_HEX = + '6d69646e696768743a7472616e73616374696f6e5b7631325d287369676e61747572655b76325d2c70726f6f662c706564657273656e2d7363686e6f72725b76315d293a4400114d215b1d41fb70b347e18a4af324729bb022eee9a1a2ac80072289074e9f6026c604adbec48503caff9b458188f07106e310837ed0a3131f635db51e1cd452cc8b0173c26bd086bcabe7eed3557652956bb4d00f9e2aa016558f6e18c6c3e370dcc373814b94d148d8789f8938560574a074741de2ee6b27a0d744394a639729f4f598f2b3b06133a8144261b10d2c23dacb0da831912c90c842ca0f1688a460fdb9d40d9f87ee0996c35e4556eb374583bc55c200e00ce2068a3c21c7f840eaf50fbe0143abf22bf691f3d9ff6af741e93f1541d4516097e60037475848c620ed43c4e17209f7fef717d44ae0f982bc7ecce38476aa05b31d090f1ab43763c69b046dc4fca583afff65d2765c1e49f2305f92e60a7135a74699809d1c680efb7bea439a61a3e2744fa984d3f961d94227e4bfd9c7dc93ed3c9e4db9eb139b81f5fd9201ef200769d917e338a524ee57aa59e4cc0fa4a8889da761e036e29576ae908cc782d3fdd60982c4c6813907c46c970b26a604360ad75c4fbc03fce59b38663e9f3fb789adee4e717cd6d1c4c59afc254b62ce87e15dcce7ef354838b5920ce911c3052681882fb88b153572d11d6da2e1fda7b255fd306ae119fbee7dfa19b69a267390f39407d92461ded88a0cee24de76e5f98275e411c5bb1ca40ed4dd93f3d2af4033d45e92d2ad001393eb705e85513293aa68a5fbeb8165aa7fa059f477a11cf886bfddaf684c4231a4411cb401a6835591168194faef89808299fa60041bf35a8616899ec18fd7ef65a4058c6fa416eb833833cf7714896f71d1109cf8e7b5ba900cb549ea572c068ee05d33fcd78669c440db7cf2d1a7ec7cb0dc02f729fa4299c6a666a7f9e9c87c8549220cd5af1b557b142fe53027efc22bf6b51ac43c795aaf7ed8be9c2128cd51499c95f45e7d3e7a86e53632d5f0ecb9545c6c41970e8052f0abd4a1df2d0392b89694c31e7fe88410d4bfcac4281d675365857096407ec8d856d86e4e764aace55f34b1aef998d3186fbb5ab333fe7969dc1211853bda85432dd6e91f35631d1fa61ee661397b0bb748c81072b7fe37e22c974d949dce38947a49bcd1cce59bce0c7b992e6e16e380600cbc038e5638d03e457df009bb35d11aa7e58e27b88d97e367f4b85c264edda11c82cf3cebbc2c18e6309a96bf457ec7f35554f6570c666cfddb310bbe33b48e9317201f225f0d571f1783a494453e91d0a078d29c7852319fa208a83e05ea3884265963f8fd0f34bd98d5dc8274c78f6b142130dca917689fde8641f32b33be1cc317211dfd9e96f25c8863d7dabac02b3d332f86c644070638cfe17c90d4f25d92193c2c6485f5e1678d67a0f9ee8b2b70686fdcd3ae799c0f1fdf3bd9e86b011b0643540fb61d0dae9632405037702a152bb85517cf37939b9082569202735b964a53d64ebc8f8c0b05cdf6c94465f56672f0196c7ae99adc31fc6f653cb7e91689b3dbf03efe11ef943eda0f515c75f6028155a3a28451adcbae1f10232341ca6b59707d5720ed555d18dffd72f6557a1c559d4e1c4ee48ca0a0f7c5d3e3db00ada8df5ea1f25cba8ff4922e7a6b6c753898c368c9ad5487ca2524856d8c151588c2040242aea71c8a6726099739dd5771e5076bc23be5e630368ed68136892b6a27d0e6c2e187ba6acf53f864ff19632230d83787d6b0708346c7b00fb57668350a99c0f6c96abfcdc0c75f026d6f28c9aaeb535c78b813e2eb266db9c7a1a179f3f7e4f86352e28965a3b42cfbc8184d46aa24c63fc71d9d88014b85ca4e2bba3388240700d5714a583ecdf56485b60685ec59bb95c0ee89485597c407629817e4861053e41ad409379ba53a3e1f657933a95880d14137e43513b4c8b56d8179fe12b85675fd3eb6f29e615e0c0d4fc3bd98bf97afdf55d9bae73cad3a70cf182339a99ee63f86861d715aa5b8c0adc760351455a43bca935111f09983cb638cfb6187937ceff13bc0393634a4e9006e7f6e883a70b16b989e9c77ff4e33e99a8baccf1f78efe60000000000000000000000000000000000000000000000000000000000000000e8d2c90bc88dd68d8447729fb4142c0b8814e3d156a9864cfe83e0979ed9d8035be38e15541940009f00997a27c71a9b50a2f5bceeef4e812ddcb3e21fc0952649c4cfd7e069a461bf76a4bc830dcaa0dc6d23eb8d758a0a57daa78ba977bd299df33830e948341d6ae8dd836cc8cb4cafa9edc60d391650d830184ad16a42518f15e6cb8595a03ebb31f11f6f57fcd4a4d655fba357c53f896ba7aa888b8f7295e7218821ae058cb3bf687bc4a9df7d49def84c06d55c86ca1aa9a4a1de5a05ae33172f5c3d0f09c2ee4d6b8ff879ac8fd0c0a1f02114847e94c6870cfd313ca5ebb9f7e6e3d55e64d798c910b91fbae07db39726a30196da13bffc2e0f5129786ef0678435472d446cb8df1fd8f3f860f5bb8a0d09d78684198e447749014e8c7f6916fcb665e44b3d8bca7b939fbdf8923b4ad38eb4c52f15da3ca6e80e00c06779dc2e0652043d531405b6ade12b35294a81200c08d7dacb4525469ba70367a3800b4b6ab0aaf28c735559ae410aae8132072ab9be9a2c99ff0b79ffc74dc1d1b77ec825a4db9250325cba2e94ab74b0081f92ac78b94d6a71e450c1bb66a91c5c3d6c31c4c173a77460b528968240341660cdcc9ade31575b9eba2d01145d4a911f8d1811c081227c2342eee0ed3cfe9a3056f91b490c487e1759ea6b57d40df1f7b1362d828097d9d0b3de472b4ba954df8c9bf8c624f2d749f99fa7354f6076864ec2beabdb019c2792c774664067cbf869d2fdd7d66a85727536ce2e4f0651173e6750daf4181d8e53e6eb33df13e462a647f015cb4bf29fc7c9be2faccadac857f63d84dd102f0cc028155c8806f7218fd4b6b9d65400659f1cf51089fa9e4cc6faaf365d006781aa32b29d28983c8a81213f7c6733d33bf2e7bd14502f851bbcbe7b0e1a6b4ed9c02c9d8244848f487c7766f3fa18e49c5a2382505358b78f0adcbe3c6bef8b8e3625206fc4dc6c531c5172df06ba35c1d893265fb2442e32d2039ef2ede9dedd8078b9224b053cc8d371d81b0669141ef1f3d61404567c36bf1b5e53ae779ba1a4e25d44fa9f3e771266ce8d0f5d741521799e2cbb0bf5977cdb2c68e22553da4a8a1e2c97b41931f17a0c03fe4a41ee2609e314935bc17d6cfac86a4a6f35fcdbe40a74ff43d8b2d6671c85a5b9af7ec24e9a1ccb6899151e007f71fa7ede5b05cd5d77892dc14f66674cbc84f412474306ca6ae721f2bf0dee8a9c3b181e5d1bfff9643d1f8fea454720f44d0bb9eca67a583415a4255fc842ce72092f8bf9127da34a5ce5e10f7df4b8dbe91f2ffa896b69442ab0a10efd5fa6f78d866a4ea26aeff79acc829b0b9e1d84ed01d780f63c6a1e9c2b36b1dae2750068ad206d44270a04cd810130ecf2f7660d02eca83ad801660ed8db536f6a5f0ac27c1c9f71f284a5d60ef3b42eceaf97de57cf0537d9c12430739c3983c18e38cbed14eb557aaf53e4e9dc2ec1f2d16959b171c75481661b8abade7e8da1ada8a75123e97f8a6347fd495c50e2b3d386c48bcacb3b2e503cc367bfe6cc4722c83c29de256d69ea58da3218a379b2a6ae73d0508d6d75d167d220e452e84fff15a6bcaaa20d80d3269723416bff38d2ece37aa68980dfcd6f4a8f546e8b998b8d09d1eb5bf9ab7afa0db04697db06efb17029dc7fe992405203380f4d71721ec701ec3af779fe043ed1f5e791bd679667bb08a72f4a19ae25580ebda8ca963dfc2ab92c419e138912536800498f8932b8c2672b4ab5594f539578d505e26f1e6a5ec2959b30430526f4e1e8270cfb7372ee8794440a35456601bb7924be121eadb4b774d55042c43ea0700e970ba3adac8dd438b88a5efe35afdb6b31e2f8de499ebd98230b44031362e10aadebee7c1503ce47218fd3c05f0000000000000000000000000000000000000000000000000000000000000000f52ce7297a57d3cf7184c01e281f4ee3cd3dc3c67185a3bf2dc70e6251d75621944d0d9fe5e5455143acd5e54bb4cd5ba1f65e3b22fe7b9e8907595af4460417ef1ac66be3388a42ee76c22c56bcf3b838a3ea0be52b8e4f0043d45152dc0e0001293ce0a74167db94eb55e99e81e7fbb35c00931e43e801cc5de6a024a241691ce14e43d513efaaf2a74fe8a2bf9251a0735c275a40aae628dd341ade1ea50c42dedb51c51baec1861ac27b11452908420c254f711506a0d82cff565e1cfc31236c7ed58be28dce199c150a8c9731519671ddbee01ff9a785b1a54b4306cf1b09a587232ccad767c10cbeab30de8a09742e3c7bb05309d995e7c86eacafc62e8a005c3f728b6755e80b4f2ba43f6bb5999661db82cd5582078d57e9a777e63099e4b008fb4eae9fcde792ff525714f0cbb8c26e4f89fabfdea119b2be149e04ffc963722b9ff6ebbe7299f159559374359cad00681e5280f40948e2159fa54b006304332d1b5e29ed619ddb5df23d2b3895468054f60b950f0d5af762d5f8604c237be67f41d0403fb9efad650c92f8d270eef10f2f3d7275e446dc2868dd44aac817efea263f91fb4460d14766c9e73c03dddb25a4b714a18e2a83c3e53428b94f1cbd9e336b19b7ae8b96e06de90c87c90c21fb7da7872d69d3a5a45c226e172e848a1a6927293b5a43c172cbe9a4f773117e09b61a43cf28c9d98657ae617846b836a6c3d1d3ef953229955721f2b090b7671a2806790d268caf484b2a107ceb3aa755c622fbbe00eddd018efe196d0eaa631f3c66c22640e80e81c01b7143efc7a505449ae72d0aadecae5c88730e8ddeb569be379739402147ae5752270d3f32d0e02a3cb15dadd9ba2a576c151e2c2c762e2c6ef459eff9ce312c9e2399841b191f319e2288c5c467710bde664073a5713b276d689e1c9a433d48051773451163c879e3e65a50fbefe9867926dc1c8b8beeb234791e69bc74169be40e99bb702a5cc1928763f8b6c129ecfcfb32d645c4976f59e79565dc526b3af7153967e69b1575d9c68e06422c0de7e3754c4a546732a4c849e216dfb92ac4561b04a7978e8274948413b2617162bd571eb92ff91a29d910142400d79b2481232da54613c589d52274d22c6661eff1ea3bdf47486e599b51d19d443f29459fc91d50fae9c027038b451c4f7045c56e4c7b832e097f97c5078018c96a8c92c96c209d1991da475be6e2e875f22d247124a748a0223085aed9180134677a7af098291e5ad26a8a31ef19e582e3476e7c59f20697e115649bcad60584c2047034ab1b59a11c61e150ad1e9746614583be4fa3dbf03493de607e44b15658f9798c85531a51468df686a2c908bd09fdb446f8d87cfe2f372559f52393221f32d64f5d49c92d02aba48cae859b5ac5560a16aacbe607e505d039f25de38d70c818bd450580a8a3315a8decce9ef1779cbff6f63f396107d758fb27a2033f7766da73646128438f3ff36e2a3df41215371b62b8ce5f6607142b8f9fac27ca00333db6524c4082451b837f6072f9bc69a5781327bd4916652bf815e32279b156b9b0d0585b63d5cc07e192c56bf35b92bb03854a13b9af7d1ffcff7675ef79abf4ec02746d161c1df6437f3bc9c0ae21114dcfb7a30b123d31ceda0df30be0724f8eb6ec17f46796a8c21f77a1e6900b2a959068b808ca32b9b292d23c87f3085999ecfe6782e686bbbc9648e427967190b8e748fec02d6c71deacad4c25df000e01cc81511bd85decd2caf818cfff6d6d4bc903f4d46dfb2ceca2b77ac4e8bec241c48932322898a2d279827f1a85c55cb98dcb4075dab562b1b49c776a29a20d9744825f2d4b89ac7a500fabfa3808221264a7d1941e7d13b3a8d650e02da613cc51d92fbc981cd2dec1631358b670f13cbcb5e1863933fe54aa05ff4e4a866ca14ba8173d27844648eedeef94291447ee734d1d8fb51dddd87a61ae137335e599cc544001ba4872a5d33f7849f4476e9b6ee96de61b6e766f8341c3ffede41bee674908254177d2538fa87db74ca7cb9d260ab7ef9608d8d797c3e5115fb017c4b158322dd73dc68007f09942c2e725b497e99ae107aef9e79474cc2c38af9846072d23b7f3cc7bc3d90f6cdbe836ae4eec30c0fccffc18f7556c588c4b104ca390401c4f472c8c25b1d311a81ba6d1239bef6830064100da39db2faedd0dc8917d84029b5620575f2673d7da4989d4bc29962ac4082b158757cf469d7dd09b35662037ba090b94b3b323462b4413071ff6e525acf2e118847887b77eac876bd7227c1b523768d46450ee29e09b28baf86319953fb749f336d8d24b704b935e0f7f4b4e5ee2573ca6d56a0d07576da768d72275a63923bd6b8de3b25bfc0d03625cf8563fe0d6406dcea15108f26d84ebea412c88e246bc1972d834abe1d5dc98e0e41809d47daa61671ce0802008f74ff14ce02c55823b8a097dcd22de5fddc8a3c90242df98314502472d131a0d16df10c112f9736278a0202c4422b0f26cbccf4e6eba4790a84042652b5fa1e57eff44e4dab5d2fd5e70db2363c71234cad55e701faee9bd919618569ec02bdfcd74a643e2dd3d8f103a848e5ce4eac4a8c99a2328f48c5e7399811b62b18dbc4c0ca1d35c10344fe8f56a5865ccb69b71bbde9c1f250eef8e04fd9b77e8d73bf8ea39fa4f24048bb9510f72fe9a41e9ba3bef980ff2b57c58e123cc9c671a8af9467cd4315b0164cb7c74b38f6f540ef1aa51b80e7eda801a9f45436418456ead0c95ec718f50cdce8fa037e1bf856844ad0420fa9886adba2588b891235981b485f6ed1cebf41441f3bbc38e084a428a7bce2728220ddafbfb444c85e360e3565f901a2e95d02c7dd5b6126da9531daa9ee0300a04f38d6030a4aadb243d0514574776ac5b50332868fd705594f5430af9a15aa804000801040099031000b48c46b4fff59c401a83b8a61daa179fef47a8ce5656599d1e14b9336249730ee2a1e5f80f0ad342fa43594a98042b6ed47280829b542b2ccbb260d380481d735fa3968cec99fb0597e6d52a08f8f56142764ee096609411ceffaea7edf5bf5a738645009cddd9886a76f04b3d09e6cb67e172e1d5142e843c6963bf19fd5b2a5d735fcf4428573f4c37abd4b067d759e62d4884fa974f79d8cd475a25ed3845071b73eec27129379d96cdd3da857678cc8941abbe380fdf92506c21d142907c800806738824c3820d1437c86380a425dd5ff382290244664fd15e03537618c8c2d7e1520408914cc16f112f56527c91381b5030c2ddf9145fb82a56b8c98c7fe0f26e2a342f5c8fe0019bbdf7bbdd78de3063b0b97e8bcd79e0f0cf79e2504c8b97a1475974fbb30100814b80b3b0f84adc4174a978e7fef9e16247d9566d4b19f99c6c3550062db4ec6d496d724c38446271ab993fc9499113459fb827ed08b60262087af6f8a921eb7fd74cd53868ba0e5320d9938b5a0cc1fedbce14853658b69bbad2de6370e49f322c8cf29a9a6c3788cc2d4bfbaeb72610e4e813f3ea275823531bc4405e8957de83619c3ada3eb2445837344b3ac7847de38e2f7f53f3479d88ef42184f5fe09bb436813983f7d334eba54547cfc23487f0589f0229e4a8705540b81c88f8f977cc9804535d5f673b4a61b47ec3895496e8dc96f340cc5fe8abbb40a6062e1c67bae83037f55557743cda030f03a79a471f97b9a8c13f68fd3ea9ad00a212c070838306930e73e1a19a41a7c040acc8ae1627329e58d49a7066375fd25f711f430b936fd87078b2973f64f773aafda556a8934b72aacd688db0437b6679b8f1ef88733db6fed534252bf90774a67619261f97ef808ea0720f704e4751bf5cda5fb7394bcbdc5e3d96769d32cfdd3e4f95fcdcb35af808ef9a21178ac44af5024fc08a64ecae96e0d8aad3b99a1ae8ffe800020ba118634742518b77026bf93667d5288138b1531b96025a5a479160135febb523d59f8cd50089370fbaa92664012c2f9fd76cd39aa8489a6679187af33209a50e73e624f2d680ff3fbb7c0e1d21f089de8340712c345fafe10240f285a407e6a68a3e1ad00afa3bdb11e3aed9889977f59592b66059d0758439870fb292fd8c847504b33dae82a0e7fd3c4e25cc9790aa070b80a5136b11201792c8b3947021700bdd6a2f09461e31ed8c48c322ea899e56c6997f2dd5791a6806bc1b1ec25658e9e2f429ca68c75b718f82e1aa972a69612194273a9aeafee7c3402adc51911f8a4017d18a0b1ac879c1ade866e01d78e7ebdadcfef705c808a5a0a8683d85393369b139c7a12e0b0b15fc7fe230b6edaf364fbda33c04976aa7c35b8e81bb4764d5e08ed70d5cb140329a5422f1d583a389f48fa0e081b10bb8b6013167a7fac0836847cdc5bfbc1392057bd64f3d6d9c4e577ef9b79c2c917de48346bfad02b7513da9b8fc7d87358141dc374399042cab8a9906094169fa94b93d28ff382f4ae7aa6f05f8373c9103c984a97a5756fb2010a642c03306d73f3d4f179e93cf2f52721ad7abf216a51f1e8220b2c01f6b679c6e5263b69e26024d545b3a2e06620335d5c061e8b4faa7bf2bf2268a18afc0e8ce66742c2103df0fdfbd9da450a8983b8e34ad003ab4a2f891d42ead87bc81825b74e89742bf97adc090cea97e1d25bb1ccb1be7ec8571fdf1f252717da9637be09ff006ba1820a84a54f9e46cc9f3d86c02b19166904996aa281288c61083232cf59f52fb99a7c59051c15edcf3b9ee2545c3b630c761da5afe42d7ee05456d04bcd8dead75e696c27dac99b971be3ca260ae1225d554227dbcf18c0b776b98c8e838139b7312973b42d7bd4d7b1ed145f6d31addd7e26d26ddfab577661c38dfdb83e4b43c2e79af491d5dff4a2db9e7add28cb0490ada353a97c661a7426ceee462e8d0b4bf1449e87fb69ce9d19d60194d2cfc2469ffe5c2ea3a123bb9682498b95af872878f27da2fb84bb2c79d95d2c8b80df67209b3593e97a9b9c9b344742a934efb62e7bb4f55843c8b4322c4c9887504c84eab324fabb631d9b02144cd4096419be925aea087b84e0c8d3a412c5d0e48b7cf7701cd35689f8764239de58f98bb50e2416360d9b97dfa5db0cb223ca1a7a42ee275a0728d42dddd8f11daae06ab7db1fcb445e597e5e0733367c9600f8ef97034fda8333492fb06db84f9be5a1d9179af43840dabd473082299575d41834cb5f1b9a0bbd5b67d261a61658df75a32a46fd0e8671cf4d63524fff97d0650aeb6bc02fa8100000000000000000000000000000000000000000000000000000000000000003b0374fcdd49963033ec0b64966e90511ca10ad21add4cbd7634e2cfe910e5465162938d1c034444d97c19f3a378564f248ed24e9f635860e39424035845ba3934bc0cbc9c114936512c82dcb41b191b9455a77e1e6694e1bb95b412ca6f70011316e8b143083984b42dbd029053cfabbe72c3fbd68b78a12c8d528a6505075891ac94812d5b7163be7d02cbe51bc9762e0a13d9e05907d2fc49cd437902bf1f880d386a35e70ca7223f093fca2e16966436160e23563ad206d5839ec26ec52f7a6869bbb4179d32bdd87de9e49309ad2ebe52425867eb9d831aa05a7dd2261c8e1dc6d24245006474f757761db648e884f321cee38ae0804bf32f6d9a4b530f6ef7d56438173c658488773198854ab107fdacad92f795994c6077d4e548711078f64782db5c6e24398eaf1f59a0cdbdddbf4ae2e36f6da68a9acb01c0e11724f91804fa2b1b5dcbf18d740a242d22ead6e6b16feecb34b4376a1fc71221ac02daf7e72069988b80ab9d4f86097328955b2da6d056a366840d4019052928102a60fd8b519ed8700b316910072807435c034f96a4d937af1d321beb0ed67b353299d0c693ef0528d5159728e9004b9e100e18e476a78ab7a7bb32ece1f53870012c988b8e5417c0e4bf3dce3f55caa016b97dfd3dd0ee2bc4df2e1c1d16d95b4a49bf46d66020cf93e0416ab77132b80666aadf58203744a63401c9ca74366658e6b71170ed3070e6bac40f9705fdafd9436a25b4ac2e402e77b8054e74625a73f7eec5bfd2ee612a5de7239b8989cfa4f2d5d1145ad558ee9176196d9d8fce18249ac090bcc44e8655eabba0a5f000ac520b5e2add5bf8619836f7d0605748235c58671b569d9589eddadfa0b290400461f206f2f16e52b50709347353b2472abfb7c8aa4f9780b98338722395af0e02b3b026aff0d4620d42fa01e2bbf56a2878e53f84dd304787b38d14d2d28ca9f15590d54acbfee5ed3dd641466ced1536261a427f160500708917b1a38c10b3a9148076067f6a033cd7bf50d7477d845cc9b560df5ad6ef5cb2ca34352197d1a8151a3dc02117503d2c9b51183f9c1608d32fef7ecafba02a3a863eeb11b624188569a77d38dd855b48ac6e92f41e87049e4ebdfe7df07e9e37e64685555bdcd39072302b2e30128fd2847843fd656754f729b55f233951774e88a860bf01a701ebbe8616e94173c088ffde135441970130e7281b678014de74492a795e83339951db85b383bc33c21ac7ed99b4e9476f8bdf7d72c0ed585d3f2a0c4aa485856f5be4403e561b70921872e5d7ace59f299cf6431a1020f6ff40045ea4b6f9a23895497cab165859b931e6888f2087ae5f0b122b1f0fecaa1ca5f01951db5a1fdab7e9d4be5e6d135ae9f3d7ba36227a6c6e0fbd79153f0f9312c850cfcff7eb9419d147cf3dcd2388b86a9c544b3d065dfb70e1de68a87131960a9f9ec32ab6a8426bc6ec87a6871573d9728940d41a1bd7f14f2a73af354bac6fec479db3cd321cf361949de9500a421cfb6ad7972a44ceb88c47290a5d4517c249eb2e4c6f830241caf7c0d353fd7c4366858fc72d4651dc015fa7e723e809a74088e72ff36f146ed282151ab9e31d249954715d3a226d251095fe90afee1e6368e8c85b0992cbf3514ad72204fc40710b2091561128e1f793e6dbec06d2a56c78a3e0ebf6b130c4f1516937dd27c196af8b0ad9360d715cc3a84b39c25e912bc1be9e3edfb581eabbb5bc8f697c98eb75737e23a61070a85b894698c6588a3805c9ffef959918e1c0a5748a19411c2563228e58ad0bee22aca34b6f10bb15fa1e12a30e495867edbf5c934e26284c09d6c525386145b4bfb7cabfbc95b0b199c6928d784976d61f735932f3f0df252503037b4330650000000000000000000000000000000000000000000000000000000000000000265014c5c96f5d0590ba14d54ec24feac73e7f59d53bd62169f34da5df0d565c345fa7665ce98b89502519330e058074c35b2ebc11aed15b47ec0958a0ca27678e9f1cb223885352d2ccd4960c11e3802281cfba318c9b53a1ca391608167903f45acd737b36ec7cd5564e6a877f60449aace1e8c07d4d068a46738a6041401b00c9345ee18d46a12114dc7a7abe34c620390aa49a4792c6df0b3819e318c050446911534b3ec2df1714d3296dc100cf7d5c379eed1ddc2311b67eb04339195b2561462e2763f63daf620541c76abbcae692e389b47d59ed032594430f70dc5dd2ff7d62fb67dc786d2599d1addda5ff1ab6d0d801322c0392098ea5cc26b14219d5cf467ae067fd78e7f2ab3c15588a7954624d25d22ae522f0ebcfdca31217ea96edabb46453258331fdb6419c5455e8c7fbefce6e689aa0b3aef067ac992aaa2eb0a4af8bbdd691a2be9347186daca172820c436e484f4612c67b5b405e2ef19b270103e697d3fe5b9c0068ad4ffac743812ff64bebfdbb2d8babed4e5b1e939759290682e383abe7ec099d774fa9c26bd2c8d3fad856cb17d37dc3271847040a1ea9bdca7b7cdd690605cc806a373f7ce74f153e1ce076ffa5f229e16e43b6c22e19c7cbf95c7fb09dfbdc48e8a6ac33c1dbb079ebeee0102ba99c3be8088058f53434e9adb47cc7eb7604192d85dc0c4bb3147bf83364453f021296eb55392542f7b97f238eda859177aa3ec20fc3e451d5d25ac6cf73d87274850b552e8cd1b7a238e3a9a046739fe8f40b9123dafd384701c00db43a4b7263fc4f460d138394089b838029d82c9ead7875287635c197c6c9cb1c5d0777d8764103e6293f5647142eb70dd9cf3888f5d84a3d792b94e8cbc3af6c03e66c4ef6e460a000d198eb78f34f4b9ffe1943dd7849781b5b67a040f36e2803d89637f832d41c5c8f5def445061c80c1da01547c3f1527e49dceb1275fe3bedfc7866e80f92752b4249bba6f4e7d396b9f39e2d9be31aa5d67ec4e3d05702663f80ec532dca3e23d03f51abcca572560237087cae49830bf550667c748414e3c79f98950eec8421ce98625f6cd4e989320329203583e5d7eb91dba59f97beffd3c34fe78c714e012daf90c4892763d43ffdb0c1100ada6b31b572bd0355d8b45a6d2e53d8aff70bd0176f6ed20cace1d1a2a54c334ed6b757812b4396a13ce22f2329d8488130428386496bbeab6df320282b81fa00ac95afb53a9fe244e550cb517aa54819e46193a8e7a71e879c9e1d2b77f85894f5e2b8f6637694255cea067fcc3f5b19ab249c9c252ca69f1ed2e1b8b648525e279ad34d82c556c4a88d29ad6e788d1474624daf12afe5bbaa8be5864154a2cf5a719290c6bfc641180b9a545dfb3723ce69c26c56cd24c27b5a23a56c8fb3e1504c7eeb72f44b6768895c8265f47b4bef1641789dd190e0176962514d80369c9dd9d3a921f10f439cac24a5005cac584c04044b5bba38aa4a1f69afe8998e6e367feb56f9e735fbcb397d6b7bc4f03e3819d3097c249c31cf1e84e5857fcdb52486bcce8189fa70d742b0f09a8b3b81be6497f820a81a85be400e3d36be6f2831a4d4a63a0d6bcb9995be2cad57f3c08c09b61d47d200c0246c7771b4d87b126762bc480bbf9bda61aa1c3534beaffaf62efa1b3a554a799b17d50ea746c4add96e3093187fa6b552645bc30d5e9568513eab3e62f07532a4e0d85b3ea7309287f612cb6591fe5ad7c8ef39513370e48d3c55fa8f16c986c4903f09de2ad1c769d31cf1940cb1f78986bbb96466c06a10150fe2b3acbe114336652fd719af201fd9cf6014bfaefaff2fe8f81ec9e73bb66229d3f871ff528bb2a4c51a4915101dc92c09e2a27fd15b965047e6a5543c95609241bed5c6ce8e4dd48de17d5b6ff9fbd4a033ddfc145a474e989ccdf9e86d6be7f203b1a27ca45f3e98bb0d2b158120d0ef88d50bd62ebb630164e995e49836454c3da3d5a250e94a50b82c96eeec49ae16ddf4896d00c9126552df416fac1745095fc5911f8b874ae71752a4099180d0fd1c263924d2d7472680195224ab27d34302c8749518d41f716a412e00912ba5ac9c44a1be36f85c4b3e10d36eb91cd53fcf62fed7b5888753bdb0bed2440a1b9c5467fdf075feca4c2c2ac95f71000838cf4fa0f556797704b2046b80baa9d2c00f2e45b54f9c2cbd50c543909a3d07ffe7a135a1097f4efe047898918ef8e50be878c450984727a07ef898d5164cf0def0608893df7b1ab5197c69ff52753f2568a1e364b16afc0663e86e36551c68ab1a8659a40862e3d06426177a211c10bf1e5e65ffa0460a33678676b490563783d2934d3d07ccd41ee26b3255ae1869eb1bff7b31dd5658115f2bae65981d9c01da500a60629735d03f450ed4f11230389d5b51dd5399431875bdd1bd9b20d458bb1142e88d57123e66ce89f7f86af90ac7784f685cf85259128462153b09b344e00bee5c5c207e24b64cc4d3e6ed7492abeb8aba7b2fa1104173dc35fc3678ce73e27d5650095869b70b8ad84ea59341dbcb81342d896386c77ad22a4559b9f345e47e95d7a303636b5463cc57724b2942aa64c0b746309d42c4646ef4e10b7e2481a60307a58abd5cf4032528785a83503565c6678c12ee1bed3e887b9a785e3b0b261c50d0bf51f4b95d60384f3fca919aab1475a4c3bcc2a86403f9d42e89e6a75559b253024c8b63dac73d00681e792da1a9f50f17de26a00534f4365846489e9fe35f0aac98c27b4f54fe4743c3c22c39fb672c4bf4f8ca71fd0a3ecfb9df0ddbc7a751c658c4c200f90a1f1785a5d4e77d19fca41d3b86eedd5babc58921a801c83cafb0dcd6091d35282cb96b218837be2303f5ea2f2fa694deed8c769f70a7c01c45d81aaf3b8e37cc0ec8d4bc8c159cc91d1005beceb34fbca1009503f1d92b26bf076f9e3f3d7868a96c055422150d36c4f14642fff176035bf9b54573007fa7bbeac698fb5a27d3af17eb8cc046bb1b30befbfcb07f337560dc6eaa3873f8f44d481bb7e99c54d51e4f9bead04b169ddd56f936aeb0328834bd3696b4547332692e63b1a0dc1cb96004d20aefb3eb507e2bb345ad6eda5b03cb242684c5107390d5b27b9a420e79a305184ff854f4058b7de092ff95a9a70121775fa1b9c91e734bf058fa8a680f08dd16c824012de1096daf6c9fbec970bb502e2d7d066a7a586fa313b8d41f6dbbe8193b4454aa3f23866f5babe386e40dc7d3583038bcdb580410914cd403bd72c5343b7679af9cfe4961e5219e006cd7fbee72d17fd0ad06cd4816b780649db1184511cde161ae091c6ba506cc6c90df56d287650a5d6d5684ead6ba0100814bae297a64ffc02513be9a8ea8c881b220df57cb8e6607ca68fc64308c2e7d61f71448e15cce10a4bdfe92df86eb7e7ab185b47ee5626765085f864c05c48a6a1eb310fe697e36708682791377a5616ce96bd3e7c9625cbd18c1f5a39ee16f8b42adf6456b70864b9f02d3a32f89c100e76d7dc2e68548a3c727b1efeb5f9fc03363d9fa447a36d8618f38b78fc0ac276490ad3ff7101b833e326406fdccf5483764d9b227b17f455ce530f09342880fd9f10e214b3a2be46eeb5bd85d76749520b07783fb9a035df3871299eac1fb70e8603aa49caad87d090720dcbacd04b7e135d51847ed23a30638d36318d083f21c87aef72e877d28ddf7564be66edd8d0cc7a450f6ea3ead668c72fc049e290bd98702602097333a6891bb0d63dc85941e97285d09a26b7fca1797eec11d3d94625589d6b60c2a56d8ecfa5b4fe73a65cc1991703238e0160eb8bb736d1706efd4851be832b872fec891bcf77d0d985b99a1257bfd9945d2b3b284ddac8af7e0342734a271781599202c270e6f79bdbe028212f471a8b4aeae0928747077159f806f9c01ff5151496851227aef014e1ee4ad55d51302b1bf27b538a04685d8f2378ec018482b314b881a7078b07eabcc8542b9b92c302648940e18c464182681260739319659f2358182dfe8a69515f9279970e57fb561ab104cdd4079c2c7653be29783b3f341039ec5f4fd767e722cbd421c97b18c50a69ec0b97b696bf1c481822bc6c9900294e8a43128dd2540f1af4ba85fe2bfccc13bfdb18b28f61142fc552c1dd4dddb1b30809ad8cedf0ed2a186c2c96191fed356249d19f4283fc609459bde807a01b506ff65f8f3f2366ba10048662651d2a7b4673f80d7f178cbee85b49723635df3e79f6dfeadc7a972619af8166e14168512e8d45769683ba718eee5aaf1b4d72ef19a3db67272301da7a4e3917c232ae6f9c39b9658f92cdd6348b0263766e7cc2325c5b67d43304cd02098ef4be9a48420ee86e0fbe807589aa89b189659e917ab6d11d6eb60724abf684c4eb7b25e40fb4effacffb3656622b6ff6a9ad914661357e8feb46d9bbb288f7370e506f187ce05338be103ae3ee0c2479ecc39022bede618d252b5dacdeb4ffd676b50a9b649833ea824cb725ee1a07206719ab90979c6d0c6706933c6e2e3144ab0a7fe9c503a944835fe3511ba058ae8db87ed9a5192fd629b2c5086f7aee3ea7ca2f698b9c8fdc6eb861469b57f3e6d97a773e2a7b84fddf93af577acaf74674a2a8814a2bf0f1f06f292f7c688ad15609e495bf912bf93b3a901c3a5feaab4c52a3fbb69daee14b10b8b67f7a1b0d459b1352ed1f34a74acd684e55c99e5ca5896a55d0c7f18d1d5bd3ab7a34144136dc06f27b56e9f4e305a092ded3069172dde203d936ca61fec89c479fa94831bc5baaf014ee26c0fcc217716a146e269d5f63233f445490d3b5c0a797f3af6234ce7143abee3594719d124bee68b408dd6a09c859efc4ed682c9e4acfe3eee4532a0c6cda9d44e374756cc66b18a0c940fbbdd1fdd683f297f39d1e9068998fda2adb2159490fb2469d1cd90fae6b8a5fabd425e65b6dd0e1d6ba25019732f7da5d80016ade697426f52e0180f81c6274eb3746171214ca0bdb432f22fb186d94a6a4455af31e141753514470dfe3b0c1ee0206165d90a2411f35289c79557865f739957cda03d3817d171c8e5b705a50396eb31c563fe1908519c23125b1c1be1c6806da093efd043a2028c92a654f5fa41f8293c547864efc417f150940bdf3874f1874e05b360b80260a4633a56d49a426c4d49401192d78a2395bc81703743f245675c8e9ca4aa01225783eddc2b7ff295ac5fdf2fccc1aeb5ff2b01b5f217fd5c4f2a7962b72bd48a3cb400000000000000000000000000000000000000000000000000000000000000009bc3eed892e4f07b5ee21a4a5e8a68cf7d3e7ea2fd8825036fafe52824eead44ad5d08f27c226e42be26126c78d66c9a999e8909f3a62d2a50c2835d85333239784ea00a30753704a6f35cc9a6017b8e0a7778781493dc09ff0eeb3653d21116e984d35c74026ca8ef3eb9753241a5319041139d5df7bff3be6e8f22af6ff42e158b172d1c2b06e890e8ee4cd83143fa21bc1f82bf8356b837a7229832f15014b458645182e4ed468865e0b0f4c1a2e58e02ff23832e03035318141e9fd7820d4122a2fb3063d2e067a2651f27ef2e30eb637fd84c5758987a25b8269d0cf762719aa7b748e3aeb2e714bcd3ceac4425cc93d1cc937edbbe9226de6fd017db04f12b81b49714a807c245afb487681259dc33194107c81188e875c933a1f23b25828ea7fa20b34966d3ee657126a9e2b79982763e7ba3376b9a153a766dc6d8213651158252a97579e41ca3c9e0f8e2587763bb0274b81f756bb0f710dc4eaa4a1db14f8416cd7cf5d387fb09828047b0f401cbbd969f44551ddf937d99756b14a3a1f555a6f87289f51a31cc072d7d8521190511bbe99aca61bdc4958fdaac3584acbd1c9e73a51e49e2376b96b54baec2c9003d29a03b8552228babba741942697cc57bafd438aa99048a60ed5440ee5092dca2efd725b6430b2bc050cdb35330f26c7f288423b08846c6ab765c57157aabbd93d11dd859d230065697853b180aec2b3abf4a34e846ccd3a49bd6730d4cb60a8c3bad4a14af8b57b41eb9c14190df7e6aedf480eafdf76a21e5a2bc919702b42338940fb052eda5570a47e7344770ccb7e1d064fec7cbfa3f663778c861add891eef02183aa5bb8a730a8884729f447f69cddb0a44fc98a5a402f56933992a4315391ac1b18af83a14fd672455cfff1c04691842a414624fa9b65c9a5c90df2adfcb915664f77eb6b1dab71449a830d154634e754a013a117b5ff333d6a685f66d5dbf06fc7e6bb894f36116f60fa6f8268aaa970da8b961ee6acf3c39782a345957562e882ca622a1c7ab53ea6a6004439ba5f768b300f346af820df1bad890ce482db9ae836b5daedd6c859b37fc75c83c407b7f1b69cf37c5273313d8f4ae563c0db8c8e7d8c895cf9fd5d33093bb40af0c06b2d10149a192a0e1496d53ea449f39b00868f6c2c7ee0be3e72eaa82d92ba926ded0c74fd3cce83c17732f1958ef70e4dfdd07090e1df9c40643620be7ce6f14da394aab034957f7db7cae29514ac9f7202a58b172076fd085da66517d7d0b1cd3b04bb4632362b996968426b118775d70f43f205fae19f3ee5fcb8caaaea52c27336da88c8a3e7636329261f7250acfa4ba795dceb340e554e454e4baada908a0a93a774dc6658f2c079deb4a8a04cced4fd5ec79ed42a190f540446e557c380a0c061c6371a2747965ace950d864d48d25dd6cbc570fc41b55620c214cb3db90d7476cc830ee2af209a018f9aa3d884971da2e8d59e26220a2391fc15b7c5d59173ba71a65400e1225021299de2259dcc5a597fb02af8465068e11550082ce27d86a450bf6b7ac87065e1ce0265763c1f77f323e82f7647878c5ea6cc7889a71b5f6ce5188a5ebde3081c19368cfa16e348026f01512306d8f6f4af5df71ae7a55a8febcb5953e5cb8ac555bd2e49de65abf863dac78025590a477e18c7106fc5a163acdce55025f16c788a1df4f8f225286b049e24b104264b75dd1589ef9c92c6932918e355c778aaa4ade7085288afc6aedbdcb17636f61fd4ce6269896c265a20345cf592578ed75b1a70ad54572ecee4c95acdef2c9628329bc05e2fae67f6d448b2983ef35a4db9bcb34c96ffd9c71b734421e3053de579d0ac23935b721bee6f89a833f02e9857740395566481c75ff9092cb65b0000000000000000000000000000000000000000000000000000000000000000ef124eb1b25610b67f52810aa3036991e49c811b052245a3340e65896411a85a048064b057cbafa2d9a1fdfb98b3b1cf081bced8bc8991abd5a62a49c4313148440a26d6dc76c09513255af1c965ee3bd38233edf7b67123ed379ee7764f26605c9785c037718341b12877f4b38f40ffa7b2a24c124a29b2b21c480ecb1ace3aede7184905cff493258852cd7acaefc53f46c768728681af35f60c68a339e87221d2bc1e750d6096723fc1c77b9e5d8908731d925442057ea930846356a0bb53757fbaece795c47523614b06191d57ae590ff743cb7fa72927396091b633130478621078bbdf3743ce54a37768c3bedce6f565abf628c2f522071a3b86f4122a1f23a1bdcac5901ecd0e03dff27bcfa093e72fea3c203f827701eb062c969d6a41f5a238fef0638387fbc7993e530139ccb1ba82994a8ad0efbf49662be40d0079e0bcbb1e69df8ee12250ae56114a45c3711ddcc103c67a5c77dce023488522d780f1881c3fbabca588199afb2a4e95c1946537d959a6e1ae6b14a6005b701f9c5bbd9fa8d48aa6ce0f253f0248c1eb1fcd28662b99659b74670297659ed96688aadca7e2351a8aac00b5df2b20eda7d018bce295063240b82989c16e0f153a1a3cc7ff99f3db813380514332dcac2a6208babf150e44cac21a380e61f4db5cb6c93827ce6ba285c62848c711e38e339ce2cbce1c05f1582826b2a79dd18f5e56b0dcce4c959891a8f151ea6997ad5ec453fe5db869f3fc12703824c786a50d5922e88e3f75762e8b8b929c0cefae98d755d493997504b16f086b84bea9f21cd937c1b569855a47628d45cd6a114f045ba883cc0963028454c9171597aadb540ce2b68c3adeaecc892e339b19fb592145cb0315fb7214855639384b368d8f1412db58bb6688fa24ec1d7aafc5c219203540a773957655ee90d1f7c9fc4d914a9de43b92c64892eafbf4c8ddd3191dcdcd8cf7ef2eb067e511df741e75652d4bff4fc6fddd542899936595c34604a7e81a931f200e79c8257f8a7fdce7dcc40f1ba405b91677fb1282478acb3b97e7a78c4ee6fc8a478dc2deffadeb19d78554aa4cc772a7c9ae718cb293c0c4767000bedc859b80d7a6b2e387c149c94fbd5167d3d0ce04799f7bd53c6b3ff5e4779cb3b1e920f30544682145b084f8a5d26d89e6f060a690dc732c422a1e42f5277e16bd59fd7fb490d79ef27710803c0a141229aa7573f88d3346e1e1ec675fb2845e13e24a79998239c8c7d52591735b5d0c26e782a0dd653b3f14a9b15f642bd85a7587671fc0557f0a6b20d6596cc05a3e983fc40a4c3eb0b92e4da989717e28e74631354173e074a9d7eba658036d6636d51116f81b104f08be1bda8f09229d2e9fe99ae4978550b6425e663f727e5b18736663b605f774c2201a2501b087b1b8ba3b904588a2965c87180116c73c44b68dc37d9320650e4aa05d3f8bd9ec2497203c0f0e9a378b566a1b6b912fe270b1c2ddf3bbad204e65e1b490f7cb2c565ba277db70cab51bf91814d7f01fef706661b6535b1875d1a242fb34411c897a5342d825849e6415e69345aa588dbe1a885a0e557fbabb6bc92e1f5b0aaf62ff9cb8701273a0db02a26c84a8167a33547b8d0dd9d551d6e5133a8b2a57357b7f947090ca68a837c967ec44f5f5c08a43c098e28efcc246f7ff4881b9fba2ce2a7f399685d24f335c74f6ec4a90e7806bab62baaaabec3d44fc3ca441a6391c08119927f20f1d1554d25cb805db036f6fd962e3766d528175ee2d4a73ed59dc8a746061df46d411f5cb52a80fdd82552457aa402edd5d7b42963649bdc1543d236acd21f767c26a605848e8d893478212c9d0977f0586f659a1027d829911546425cff54da9686af2127bed9115cc64391145770e38ee0812d87124a92b339d22de8d13aa59a26104e703dc39068dad32bc4b7336a72996d66847a7c5fcbd71d2f36456e2403447fb7f2e8abc0182cb1faae4648bcc570190a69511dd3ec633eb80fcd3afef6cb5ab935766a95a9d643079c4d53e08d27b9b1d630240f4969b527f26ecf80d470f7a64e9b1a7e361b305b995f78219a92f2be7cf2639b437d98041b92fd483950cd754342e7939e0fb260a0375225bc6806302762e8313cc7a2d45277bf34f4ae9aaa7033b9a1162c361fecb9b76f760af7d60ba2994e3fb240cdd8f59a121b7d4e40022468990f685684465cc8ebe3995b9da7e57b2ddf21d70fa8bd1905a1ecb3672c110105a4f5b2b7a639b2995a34ee6a3d9e5b458cbf775203338857a4c47b467d70921f881224d8a9f593e7d5ff723a5b778412a2506d73f65ffbc8e79bf3be756bd32b762190e9328335893ad9a4a4221ac7e104ce4d97173d09138a98a994fb23e95b5b23d372486724f9f3d926d935bf7e3e2b789940465b5ea161c81b7e12e292459990e5b519309fe3c7fcb9ce6126dd08a9cd773e9bc96df43b86560784fd82f0f903705c06fb987d61cbc3910d873e85eec17623b38719c8374069c00d87a801a366018b841647699104318a3ef628c4dc892704b537239bc59993050317c1ea5ba4168afed9d7a5a5445fe57829a34407f0c4e899f86bcb2fc65239f3e148ee0a6e735d544a0dd2778b5e80d5af7e57516f312a8b4c52b733950e52f6ed87573790a9e75a8fa5aa3c3e071c290df3d2107ea0f066c3c4fc4dd59ecfb0aa034cc7f5464edf943fe9bef2de6431f99c8ca457f0de744373e8a94a1fc806f169c7c133097d403ed17b1157bb2b63c8e40acba036db871ec66c5401ccce317f1e0f4d8f2f31dca987e0b258a37847477587a6d555424bb56aa52bef314df874de1521cae6d94d6a78e7aa53508d8445f96ed5a8d28b8331e89637877b46d05b3337703c7c8270a5a69ef7bd6edb6d3668ff6499ef0a1f6e31967d9fcd12d61e5082ede5b9f04140801040418140304010410080c1c08040800040000c000000000000000000000000000000000000000000000000000000000000000010a00000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000002f9ffffffffffffffffffffffffffffff042c08010404301403040104100828340804081004202438000c243c24b80028756e6465706c6f79656400731b7e2230be7e75c79bc6485e46f66b8847990fa6e36d020de062b17263256102'; diff --git a/src/__tests__/helpers/connector-stub.ts b/src/__tests__/helpers/connector-stub.ts index e3280487..38e33188 100644 --- a/src/__tests__/helpers/connector-stub.ts +++ b/src/__tests__/helpers/connector-stub.ts @@ -14,6 +14,10 @@ export interface StubConnector { handlers: Record Promise>; dispose(): void; revertPendingTxs(connectionId: string): Promise; + handOffPendingTx(connectionId: string, txHex: string): boolean; + takeOffer(connectionId: string, txHex: string): Promise; + cancelOffers(connectionId: string, offers: readonly unknown[]): Promise; + hasPendingTxs(): boolean; } /** What the stub takes from an engine. */ @@ -59,6 +63,7 @@ export interface BundleOverrides { initSwap?: (...args: any[]) => Promise; getAllFromTxHistory?: () => Promise; estimateTransactionFee?: (...args: any[]) => Promise; + validateTransaction?: (...args: any[]) => Promise; } /** The facade stub and connector over `engine`'s pieces. */ @@ -120,6 +125,7 @@ export function connectorStub(engine: StubEngine) { adoptTransaction: vi.fn((bytes: Uint8Array, stage: string) => ({ stage, hex: Buffer.from(bytes).toString('hex') })), estimateTransactionFee: overrides?.estimateTransactionFee ?? vi.fn().mockResolvedValue(1_000n), getAllFromTxHistory: overrides?.getAllFromTxHistory ?? vi.fn().mockResolvedValue(HISTORY), + validateTransaction: overrides?.validateTransaction ?? vi.fn().mockResolvedValue(undefined), }, keystore: { signDataAsync: vi.fn().mockResolvedValue({ tag: 'schnorr', value: 'abcd1234signature' }), diff --git a/src/__tests__/helpers/connector-suite.ts b/src/__tests__/helpers/connector-suite.ts index 87b5c61d..47003479 100644 --- a/src/__tests__/helpers/connector-suite.ts +++ b/src/__tests__/helpers/connector-suite.ts @@ -17,6 +17,9 @@ import { Effect } from 'effect'; import { HISTORY, TEST_NETWORK_CONFIG, connectorStub, type BundleOverrides, type StubConnector, type StubEngine } from './connector-stub.ts'; import { startLocalIndexer, type LocalIndexer } from './local-indexer.ts'; import { ledgerTx, type Ledger } from './ledger-tx.ts'; +import { SWAP_OFFER_HEX, OFFER_GIVE } from '../fixtures/swap-offer.ts'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { OfferCoinsInUseError, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; import type { SignatureVerifyingKey } from '@midnightntwrk/ledger-v9'; import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; @@ -1583,6 +1586,104 @@ export function connectorSuite(engine: ConnectorEngine): void { }); }); + describe('swap offers', () => { + /** The real offer, as the SDK holds a finalized transaction. */ + const offerTx = () => engine.ledger.Transaction.deserialize('signature', 'proof', 'binding', Buffer.from(SWAP_OFFER_HEX, 'hex')); + const offerNullifier = () => (offerTx().guaranteedOffer!.inputs[0]!.nullifier as string); + const openOffer = (): OpenOffer => ({ + id: 'f8'.repeat(32), + terms: { give: { token: OFFER_GIVE, amount: 10n }, want: { token: '00'.repeat(31) + '02', amount: 7n } }, + nullifiers: [offerNullifier()], + madeAt: new Date(0), + expiresAt: new Date(0), + }); + + it('takes an offer: checks its signatures and proofs before building, balances every kind, checks the whole, and holds it pending', async () => { + const validate = vi.fn().mockResolvedValue(undefined); + const balance = vi.fn().mockResolvedValue({ type: 'RECIPE', blockData: 'block' }); + const bundle = createBundleStub({ validateTransaction: validate, balanceFinalizedTransaction: balance }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + expect(await connector.takeOffer('taker', SWAP_OFFER_HEX)).toBe(FINALIZED_HEX); + + expect(validate.mock.calls[0]![1]).toEqual({ flags: { enforceBalancing: false, verifySignatures: true, enforceLimits: false } }); + expect(engine.handleHex(validate.mock.calls[0]![0])).toBe(SWAP_OFFER_HEX); + const [call] = balance.mock.calls; + expect(engine.handleHex(call![0])).toBe(SWAP_OFFER_HEX); + if (engine.secretKeys !== undefined) expect(call![1]).toBe(engine.secretKeys); + expect(call!.at(-1)).toMatchObject({ tokenKindsToBalance: 'all' }); + expect(validate.mock.calls[1]![1]).toEqual({ flags: { enforceBalancing: true, verifySignatures: true, enforceLimits: true }, blockData: 'block' }); + expect(connector.hasPendingTxs()).toBe(true); + }); + + it('refuses an offer whose signatures or proofs don\'t check, before building anything', async () => { + const balance = vi.fn(); + const bundle = createBundleStub({ validateTransaction: vi.fn().mockRejectedValue(new Error('invalid proof')), balanceFinalizedTransaction: balance }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const err = await connector.takeOffer('taker', SWAP_OFFER_HEX).catch((e: unknown) => e); + + expect(err).toBeInstanceOf(NotAnOfferError); + expect((err as Error).message).toContain("its signatures or proofs don't check (invalid proof)"); + expect(balance).not.toHaveBeenCalled(); + }); + + it('refuses a transaction that is no offer before validating anything', async () => { + const validate = vi.fn(); + connector = engine.createDAppConnector({ bundle: createBundleStub({ validateTransaction: validate }), networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + await expect(connector.takeOffer('taker', SEALED_AGENT_TX)).rejects.toBeInstanceOf(NotAnOfferError); + expect(validate).not.toHaveBeenCalled(); + }); + + it('refuses, and reverts, a transaction it built that would spend an open offer\'s coins', async () => { + const revertFn = vi.fn().mockResolvedValue(undefined); + const built = offerTx(); + const bundle = createBundleStub({ finalizeRecipe: () => Promise.resolve(built) }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true }, openOffers: () => [openOffer()] }); + + const err = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: unknown) => e); + + expect(err).toBeInstanceOf(OfferCoinsInUseError); + expect(revertFn).toHaveBeenCalledWith(built); + expect(connector.hasPendingTxs()).toBe(false); + }); + + it('cancels an offer by sending its whole balance of the token back to itself, which spends the offer\'s coins', async () => { + const transfer = vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }); + const bundle = createBundleStub({ + stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 100n } })), + transferTransaction: transfer, + finalizeRecipe: () => Promise.resolve(offerTx()), + }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true }, openOffers: () => [openOffer()] }); + + expect(await connector.cancelOffers('maker', [openOffer()])).toBe(SWAP_OFFER_HEX); + const [[outputs]] = transfer.mock.calls; + expect(outputs).toHaveLength(1); + expect(outputs[0].type).toBe('shielded'); + expect(outputs[0].outputs).toHaveLength(1); + expect(outputs[0].outputs[0]).toMatchObject({ type: OFFER_GIVE, amount: 100n }); + expect(outputs[0].outputs[0].receiverAddress.coinPublicKeyString()).toBe(WALLET_SHIELDED.coinPublicKeyString()); + expect(connector.hasPendingTxs()).toBe(true); + }); + + it('refuses a cancel that would not spend the offer\'s coins, keeping nothing', async () => { + const revertFn = vi.fn().mockResolvedValue(undefined); + const bundle = createBundleStub({ + stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 100n } })), + finalizeRecipe: () => Promise.resolve(sealedTx(5)), + }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + await expect(connector.cancelOffers('maker', [openOffer()])).rejects.toMatchObject({ code: 'InvalidRequest' }); + expect(revertFn).toHaveBeenCalled(); + expect(connector.hasPendingTxs()).toBe(false); + }); + }); + describe('pending tx tracking (hex-based)', () => { it('untrackPendingTx works via hex key (not object identity)', async () => { // balanceUnsealedTransaction tracks a tx, then submitTransaction untracks by hex. @@ -1645,6 +1746,28 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(revertFn).toHaveBeenCalledWith(finalized); }); + it('a transaction handed off is never reverted, on disconnect or by the abandon timer', async () => { + vi.useFakeTimers(); + try { + const revertFn = vi.fn().mockResolvedValue(undefined); + process.stderr.write = (() => true) as any; + const bundle = createBundleStub({ finalizeRecipe: () => Promise.resolve(sealedTx(5)) }); + (bundle.facade as any).revert = revertFn; + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + + const built = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('conn_offer')) as { tx: string }; + expect(connector.handOffPendingTx('conn_offer', built.tx)).toBe(true); + expect(connector.handOffPendingTx('conn_offer', built.tx)).toBe(false); + expect(connector.hasPendingTxs()).toBe(false); + + await connector.revertPendingTxs('conn_offer'); + await vi.advanceTimersByTimeAsync(121_000); + expect(revertFn).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + it('submitTransaction rejection reverts and untracks', async () => { const revertFn = vi.fn().mockResolvedValue(undefined); const origIsTTY = process.stdin.isTTY; diff --git a/src/__tests__/helpers/offer-reader-suite.ts b/src/__tests__/helpers/offer-reader-suite.ts new file mode 100644 index 00000000..bb8af395 --- /dev/null +++ b/src/__tests__/helpers/offer-reader-suite.ts @@ -0,0 +1,55 @@ +// The offer reader's tests, over either SDK engine: a real offer (made on a +// local ledger-9 chain, never submitted) is read from its bytes alone, and +// what is not an offer is refused. Each engine reads with its own ledger. +// This file loads no engine: each test file that runs it passes one. + +import { createHash } from 'node:crypto'; +import { describe, it, expect, beforeAll } from 'vitest'; +import { NotAnOfferError, type OfferContents } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { ledgerTx, type Ledger } from './ledger-tx.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../fixtures/swap-offer.ts'; + +export interface OfferReaderEngine { + set: string; + ledger: Ledger; + readOffer(txHex: string): OfferContents; + spentNullifiers(txHex: string): string[]; +} + +export function offerReaderSuite(engine: OfferReaderEngine): void { + const { agentPaysMerchant, sealedBytes, unsealedBytes } = ledgerTx(engine.ledger); + const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex'); + let payment: string; + let unsealedPayment: string; + beforeAll(async () => { + payment = hex(await sealedBytes(agentPaysMerchant())); + unsealedPayment = hex(await unsealedBytes(agentPaysMerchant())); + }); + + describe(`the offer reader (${engine.set} engine)`, () => { + it('reads an offer\'s terms, id and coins from its bytes alone', () => { + const offer = engine.readOffer(SWAP_OFFER_HEX); + expect(offer.terms).toEqual({ give: { token: OFFER_GIVE, amount: 10n }, want: { token: OFFER_WANT, amount: 7n } }); + expect(offer.id).toBe(createHash('sha256').update(Buffer.from(SWAP_OFFER_HEX, 'hex')).digest('hex')); + expect(offer.nullifiers).toHaveLength(1); + expect(offer.nullifiers[0]).toMatch(/^[0-9a-f]{64}$/); + }); + + it('names the coins an offer spends, as it names them for any transaction', () => { + expect(engine.spentNullifiers(SWAP_OFFER_HEX)).toEqual(engine.readOffer(SWAP_OFFER_HEX).nullifiers); + expect(engine.spentNullifiers(payment)).toEqual([]); + expect(engine.spentNullifiers(unsealedPayment)).toEqual([]); + }); + + it.each([ + ['text that is not hex', () => 'zswapoffer1qq', 'it is not hex'], + ['bytes that are no transaction', () => 'deadbeef', 'it is not a sealed ledger-9 transaction'], + ['a truncated offer', () => SWAP_OFFER_HEX.slice(0, SWAP_OFFER_HEX.length - 64), 'it is not a sealed ledger-9 transaction'], + ['an unsealed transaction', () => unsealedPayment, 'it is not a sealed ledger-9 transaction'], + ['an unshielded payment', () => payment, 'a swap offer has shielded parts only'], + ])('refuses %s as no offer', (_case, tx, reason) => { + expect(() => engine.readOffer(tx())).toThrow(NotAnOfferError); + expect(() => engine.readOffer(tx())).toThrow(reason); + }); + }); +} diff --git a/src/__tests__/offer-envelope.test.ts b/src/__tests__/offer-envelope.test.ts new file mode 100644 index 00000000..f6c8e2d6 --- /dev/null +++ b/src/__tests__/offer-envelope.test.ts @@ -0,0 +1,51 @@ +// The offer file: written and read back, refused when it isn't one or says +// other than its transaction, and refused once past the maker's expiry. + +import { describe, it, expect } from 'vitest'; +import { assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, OfferExpiredError, type OfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +const A = '00'.repeat(31) + '01'; +const B = '00'.repeat(31) + '02'; +const ENVELOPE: OfferEnvelope = { + network: 'undeployed', + id: 'ab'.repeat(32), + terms: { give: { token: A, amount: 10n }, want: { token: B, amount: 12345678901234567890n } }, + expiresAt: new Date('2026-11-03T12:00:00.000Z'), + tx: 'beef', +}; + +describe('the offer file', () => { + it('reads back what was written, amounts of any size included', () => { + const text = encodeOfferEnvelope(ENVELOPE); + expect(JSON.parse(text)).toMatchObject({ kind: 'midnight-swap-offer', version: 1, terms: { want: { amount: '12345678901234567890' } } }); + expect(decodeOfferEnvelope(text)).toEqual(ENVELOPE); + }); + + it.each([ + ['text that is not JSON', 'zswapoffer1qq…', 'not JSON'], + ['JSON of another kind', JSON.stringify({ kind: 'contract' }), 'not an offer file'], + ['a version this mn does not read', JSON.stringify({ ...JSON.parse(encodeOfferEnvelope(ENVELOPE)), version: 2 }), 'version 2'], + ['a leg with no amount', JSON.stringify({ ...JSON.parse(encodeOfferEnvelope(ENVELOPE)), terms: { give: { token: A }, want: { token: B, amount: '1' } } }), "give is not a token and a whole amount"], + ['an expiry that is not a date', JSON.stringify({ ...JSON.parse(encodeOfferEnvelope(ENVELOPE)), expiresAt: 'soon' }), 'not a date'], + ])('refuses %s as no offer', (_case, text, reason) => { + expect(() => decodeOfferEnvelope(text)).toThrow(NotAnOfferError); + expect(() => decodeOfferEnvelope(text)).toThrow(reason); + }); + + it('refuses a file whose id or terms are not its transaction\'s', () => { + const read = { id: ENVELOPE.id, terms: ENVELOPE.terms, nullifiers: [] }; + expect(() => assertEnvelopeMatches(ENVELOPE, read)).not.toThrow(); + expect(() => assertEnvelopeMatches(ENVELOPE, { ...read, id: 'cd'.repeat(32) })).toThrow("the offer file's id is not its transaction's"); + expect(() => assertEnvelopeMatches(ENVELOPE, { ...read, terms: { ...read.terms, give: { token: A, amount: 11n } } })).toThrow('states other terms than its transaction holds'); + }); + + it('refuses an offer from its expiry on, as the caller\'s to fix', () => { + expect(() => assertOfferUnexpired(ENVELOPE, new Date('2026-11-03T11:59:59.999Z'))).not.toThrow(); + const err = (() => { try { assertOfferUnexpired(ENVELOPE, ENVELOPE.expiresAt); } catch (e) { return e; } })() as OfferExpiredError; + expect(err).toBeInstanceOf(OfferExpiredError); + expect(err.message).toBe(`The offer ${'ab'.repeat(8)}… expired at 2026-11-03T12:00:00.000Z; ask the maker for a new one`); + expect(classifyError(err)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_EXPIRED }); + }); +}); diff --git a/src/__tests__/offer-reader.test.ts b/src/__tests__/offer-reader.test.ts new file mode 100644 index 00000000..f637e6da --- /dev/null +++ b/src/__tests__/offer-reader.test.ts @@ -0,0 +1,7 @@ +// The offer reader on the rc engine. The tests are the suite both engines run: helpers/offer-reader-suite.ts. + +import * as ledger from '@midnightntwrk/ledger-v9'; +import { readOffer, spentNullifiers } from '@kuiralabs/midnight-engine-rc/offer-reader'; +import { offerReaderSuite } from './helpers/offer-reader-suite.ts'; + +offerReaderSuite({ set: 'rc', ledger, readOffer, spentNullifiers }); diff --git a/src/__tests__/open-offers.test.ts b/src/__tests__/open-offers.test.ts new file mode 100644 index 00000000..6b694e5a --- /dev/null +++ b/src/__tests__/open-offers.test.ts @@ -0,0 +1,59 @@ +// The offers a wallet has made and not seen taken or cancelled, in mn's state, +// and the check that keeps a later spend from silently cancelling one. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync, statSync } from 'node:fs'; +import { tmpdir, homedir } from 'node:os'; +import { join } from 'node:path'; +import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { assertSpendsNoOfferCoin, closeOpenOffers, OfferCoinsInUseError, openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +const WALLET = 'mn_addr_undeployed1maker'; +const offer = (id: string, nullifiers: string[]): OpenOffer => ({ + id, + terms: { give: { token: '00'.repeat(31) + '01', amount: 10n }, want: { token: '00'.repeat(31) + '02', amount: 7n } }, + nullifiers, + madeAt: new Date('2026-11-02T10:00:00.000Z'), + expiresAt: new Date('2026-11-03T10:00:00.000Z'), +}); + +let root: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'mn-open-offers-')); + setHostPathsSource(() => ({ stateRoot: join(root, '.midnight'), home: root })); +}); +afterEach(() => { + setHostPathsSource(() => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() })); + rmSync(root, { recursive: true, force: true }); +}); + +describe('open offers', () => { + it('records an offer per wallet and network, in mn\'s state, readable only by its owner', () => { + recordOpenOffer('undeployed', WALLET, offer('a1', ['n1'])); + expect(readOpenOffers('undeployed', WALLET)).toEqual([offer('a1', ['n1'])]); + expect(readOpenOffers('stagenet', WALLET)).toEqual([]); + expect(openOffersFile('undeployed', WALLET)).toBe(join(root, '.midnight', 'swap-offers', 'undeployed', `${WALLET}.json`)); + expect(statSync(openOffersFile('undeployed', WALLET)).mode & 0o077).toBe(0); + }); + + it('closes offers by id, keeping the rest', () => { + recordOpenOffer('undeployed', WALLET, offer('a1', ['n1'])); + recordOpenOffer('undeployed', WALLET, offer('a2', ['n2'])); + expect(closeOpenOffers('undeployed', WALLET, ['a1']).map((o) => o.id)).toEqual(['a1']); + expect(readOpenOffers('undeployed', WALLET).map((o) => o.id)).toEqual(['a2']); + expect(closeOpenOffers('undeployed', WALLET, ['gone'])).toEqual([]); + }); + + it('refuses a spend of an open offer\'s coin, naming the offer, unless the spend cancels it', () => { + const open = [offer('a1'.repeat(16), ['AA11']), offer('b2'.repeat(16), ['bb22'])]; + expect(() => assertSpendsNoOfferCoin(open, ['cc33'])).not.toThrow(); + const err = (() => { try { assertSpendsNoOfferCoin(open, ['aa11', 'cc33']); } catch (e) { return e; } })() as OfferCoinsInUseError; + expect(err).toBeInstanceOf(OfferCoinsInUseError); + expect(err.offerIds).toEqual(['a1'.repeat(16)]); + expect(err.message).toBe(`This would spend coins held by an open swap offer (${'a1'.repeat(8)}…), cancelling it. Cancel it first, or wait until it is taken.`); + expect(classifyError(err)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_COINS_IN_USE }); + expect(() => assertSpendsNoOfferCoin(open, ['aa11'], ['a1'.repeat(16)])).not.toThrow(); + }); +}); diff --git a/src/__tests__/swap-offer.test.ts b/src/__tests__/swap-offer.test.ts new file mode 100644 index 00000000..a4c13b3b --- /dev/null +++ b/src/__tests__/swap-offer.test.ts @@ -0,0 +1,33 @@ +// The terms check a taker runs before building or spending anything, and how +// its refusals classify: the caller's to fix. + +import { describe, it, expect } from 'vitest'; +import { checkTerms, NotAnOfferError, TermsMismatchError, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +const A = '00'.repeat(31) + '01'; +const B = '00'.repeat(31) + '02'; +const AGREED: SwapTerms = { give: { token: A, amount: 10n }, want: { token: B, amount: 7n } }; + +describe('checkTerms', () => { + it('passes an offer whose terms are exactly the agreed ones, whatever the case of the token hex', () => { + expect(() => checkTerms({ give: { token: A.toUpperCase(), amount: 10n }, want: { token: B, amount: 7n } }, AGREED)).not.toThrow(); + }); + + it.each([ + ['gives less', { give: { token: A, amount: 9n }, want: { token: B, amount: 7n } }], + ['wants more', { give: { token: A, amount: 10n }, want: { token: B, amount: 8n } }], + ['gives another token', { give: { token: B, amount: 10n }, want: { token: B, amount: 7n } }], + ['swaps the sides', { give: { token: B, amount: 7n }, want: { token: A, amount: 10n } }], + ])('refuses an offer that %s, saying what it offers and what was agreed', (_case, offered) => { + const err = (() => { try { checkTerms(offered, AGREED); } catch (e) { return e; } })() as TermsMismatchError; + expect(err).toBeInstanceOf(TermsMismatchError); + expect(err.offered).toEqual(offered); + expect(err.message).toBe(`The offer gives ${offered.give.amount} of token ${offered.give.token} for ${offered.want.amount} of token ${offered.want.token}, not the agreed 10 of token ${A} for 7 of token ${B}`); + }); + + it('classifies a terms mismatch and bytes that are no offer as the caller\'s to fix', () => { + expect(classifyError(new TermsMismatchError(AGREED, AGREED))).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.TERMS_MISMATCH }); + expect(classifyError(new NotAnOfferError('it is not hex'))).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.NOT_AN_OFFER }); + }); +}); diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts index d606503a..f6e03e0a 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/src/__tests__/wallet-session.test.ts @@ -87,6 +87,24 @@ describe('wallet session', () => { await session.close(); }); + it('makes an offer the taker pays for, paid to its own shielded address, which closing does not cancel', async () => { + const initSwap = vi.fn().mockResolvedValue({ type: 'SWAP' }); + const { session, revert } = openSession({ bundleOverrides: { initSwap } }); + const give = { token: '00'.repeat(31) + '01', amount: 10n }; + const want = { token: '00'.repeat(31) + '02', amount: 7n }; + + expect(await session.makeOffer(give, want)).toBe('abcd'); + const [inputs, outputs, options] = initSwap.mock.calls[0]!; + expect(inputs).toEqual({ shielded: { [give.token]: 10n } }); + expect(outputs).toHaveLength(1); + expect(outputs[0].type).toBe('shielded'); + expect(outputs[0].outputs[0]).toMatchObject({ type: want.token, amount: 7n }); + expect(outputs[0].outputs[0].receiverAddress.coinPublicKeyString()).toBe(WALLET_SHIELDED.coinPublicKeyString()); + expect(options.payFees).toBe(false); + await session.close(); + expect(revert).not.toHaveBeenCalled(); + }); + it('signs data with the wallet\'s unshielded key', async () => { const { session } = openSession(); expect(await session.sign('68656c6c6f', 'hex')).toEqual({ data: '68656c6c6f', signature: 'abcd1234signature', verifyingKey: '5678efghpubkey', scheme: 'schnorr_bip340' }); From 369ae25b684038f00b189953ede3a2ac4c69c223 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 13:20:33 -0800 Subject: [PATCH 49/88] mn swap: make, inspect, take, cancel and list offer files (SG) A new package, swap, on connect's wallet session: `mn swap make` writes an offer file (the maker's half, its terms, mn's own expiry, a day by default) and records the offer as open; `inspect` reads a file against its own bytes and asks the indexer whether its coins are spent; `take` refuses other terms, an expired offer, one taken already and a file that is no offer before the taker's wallet builds anything, then adds its half and the fee and submits; `cancel ` spends an open offer's coins back to the maker; `list` shows the wallet's open offers and closes the ones taken since. Five MCP tools beside them, making, taking and cancelling behind confirmation tokens. Tokens are raw types, amounts the smallest unit. Live on a local ledger-9 chain from the packed build: a maker gives 10 of a shielded test token for 7 of another, the taker takes it, and each holds exactly what the other gave; other terms, a second take, an expired offer and a spend of an open offer's coins are refused; a cancelled offer inspects as no longer live. --- README.md | 1 + docs/SKILL-CORE.md | 2 +- docs/SKILL.md | 3 +- src/__tests__/agent-guidance.test.ts | 10 +- src/__tests__/command-flags.test.ts | 3 + src/__tests__/command-registry.test.ts | 11 +- src/__tests__/help.test.ts | 4 +- src/__tests__/sdk-free-base.test.ts | 2 +- src/__tests__/swap-request.test.ts | 76 ++++++++ src/commands/swap.definition.ts | 241 +++++++++++++++++++++++++ src/commands/swap.guidance.ts | 61 +++++++ src/commands/swap.ts | 159 ++++++++++++++++ src/lib/agent-manual.ts | 1 + src/lib/installed-commands.ts | 3 + src/lib/swap/offers.ts | 147 +++++++++++++++ src/lib/swap/request.ts | 77 ++++++++ 16 files changed, 791 insertions(+), 10 deletions(-) create mode 100644 src/__tests__/swap-request.test.ts create mode 100644 src/commands/swap.definition.ts create mode 100644 src/commands/swap.guidance.ts create mode 100644 src/commands/swap.ts create mode 100644 src/lib/swap/offers.ts create mode 100644 src/lib/swap/request.ts diff --git a/README.md b/README.md index 021d2363..51a5a903 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Install the prerelease with npm (or run it with `npx`). It ships an `npm-shrinkw | `midnight test [options]` | Generate and run E2E test suites for Midnight dApps | | `midnight dev [path]` | Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy) | | `midnight contract [options]` | Inspect, deploy, call, and query Midnight smart contracts | +| `midnight swap [options]` | Private swaps of shielded tokens, through offer files (experimental) | | `midnight grant [options]` | This wallet's account, and the grants that let an agent spend from it (experimental) | | `midnight localnet ` | Manage a local Midnight network via Docker Compose (up is refused on this ledger-9 build) | | `midnight help [command]` | Show usage for all commands or a specific command | diff --git a/docs/SKILL-CORE.md b/docs/SKILL-CORE.md index 0a7c25c7..f134c3e1 100644 --- a/docs/SKILL-CORE.md +++ b/docs/SKILL-CORE.md @@ -40,7 +40,7 @@ You have access to the `midnight-wallet-cli` MCP server. This is the **core** sk - **Open-world tools** (`openWorldHint: true`) — touch the network/chain/Docker. Can fail non-deterministically; retry is usually safe for reads, risky for writes. - **Never** auto-execute a fund-moving operation. Always describe amount + recipient + network first. - **Never** invent a mnemonic, seed, or private key. If the user needs one, call `midnight_wallet_generate`. -- **Some tools use a two-step confirmation token**: `midnight_wallet_generate`, `midnight_wallet_remove`, `midnight_transfer`, `midnight_contract_deploy`, `midnight_contract_call`, `midnight_grant_deploy`, `midnight_grant_deposit`, `midnight_grant_issue`, `midnight_grant_revoke`, `midnight_grant_revoke_all`. The first call returns a pending token + description and does nothing else; show the description verbatim, and call `midnight_confirm_operation({ token })` only after the user explicitly says yes. (`midnight_wallet_generate` asks only with `force: true`, which replaces a wallet.) Full flow in `midnight-wallet://skill/full`. +- **Some tools use a two-step confirmation token**: `midnight_wallet_generate`, `midnight_wallet_remove`, `midnight_transfer`, `midnight_contract_deploy`, `midnight_contract_call`, `midnight_grant_deploy`, `midnight_grant_deposit`, `midnight_grant_issue`, `midnight_grant_revoke`, `midnight_grant_revoke_all`, `midnight_swap_make`, `midnight_swap_take`, `midnight_swap_cancel`. The first call returns a pending token + description and does nothing else; show the description verbatim, and call `midnight_confirm_operation({ token })` only after the user explicitly says yes. (`midnight_wallet_generate` asks only with `force: true`, which replaces a wallet.) Full flow in `midnight-wallet://skill/full`. ## When to fetch the full skill diff --git a/docs/SKILL.md b/docs/SKILL.md index 69b2b0d2..d161bfe9 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -14,6 +14,7 @@ Act on the user's behalf on Midnight, through what the installed packages bring: - Deploy, call, inspect and read Compact smart contracts, and read the chain's block limits. - Serve a wallet to a dApp over the DApp connector, including as a fee wallet for an agent's transactions (`mn serve --approve-fees`). - Scaffold and run a dApp's end-to-end tests, and manage a local Midnight network. +- Swap one shielded token for another privately with another wallet, through an offer file: make it, inspect it, take it at the agreed terms. - Deploy the wallet's account, fund it, and issue and revoke the grants that let an agent spend from it. Most commands are MCP tools (`tools/list` shows each, and what it takes). These have none, and the user runs them in their own terminal: `mn generate`, `mn serve`, `mn dev`, `mn help`, `mn manual`; some subcommands have none either. @@ -134,7 +135,7 @@ Running a suite is a CLI command, not an MCP tool: `mn test run --suite ` - **Open-world tools** (`openWorldHint: true`) — touch the network/chain/Docker. Can fail non-deterministically; retry is usually safe for reads, risky for writes. - **Never** auto-execute a fund-moving operation. Always describe amount + recipient + network first. - **Never** invent a mnemonic, seed, or private key. If the user needs one, call `midnight_wallet_generate`. -- **Some tools use a two-step confirmation token**: `midnight_wallet_generate`, `midnight_wallet_remove`, `midnight_transfer`, `midnight_contract_deploy`, `midnight_contract_call`, `midnight_grant_deploy`, `midnight_grant_deposit`, `midnight_grant_issue`, `midnight_grant_revoke`, `midnight_grant_revoke_all`. The first call returns a pending token + description and does nothing else; show the description verbatim, and call `midnight_confirm_operation({ token })` only after the user explicitly says yes. (`midnight_wallet_generate` asks only with `force: true`, which replaces a wallet.) +- **Some tools use a two-step confirmation token**: `midnight_wallet_generate`, `midnight_wallet_remove`, `midnight_transfer`, `midnight_contract_deploy`, `midnight_contract_call`, `midnight_grant_deploy`, `midnight_grant_deposit`, `midnight_grant_issue`, `midnight_grant_revoke`, `midnight_grant_revoke_all`, `midnight_swap_make`, `midnight_swap_take`, `midnight_swap_cancel`. The first call returns a pending token + description and does nothing else; show the description verbatim, and call `midnight_confirm_operation({ token })` only after the user explicitly says yes. (`midnight_wallet_generate` asks only with `force: true`, which replaces a wallet.) ## Error recovery recipes diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index 23551ce8..7897d0a2 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -169,8 +169,10 @@ describe('createPackageRegistry', () => { describe('the installed packages\' guidance', () => { it('names, in every piece, a section its text has', () => { + // A text's own sections, and the ones packages add to it (swap adds its own to the manual). + const added = installedCommands.packages.flatMap((pkg) => pkg.guidance.sections ?? []); const unplaced = installedCommands.packages.flatMap((pkg) => pkg.guidance.pieces - .filter((p) => !SECTIONS[p.text].includes(p.section)) + .filter((p) => !sectionsWithAdded(p.text, SECTIONS[p.text], added).includes(p.section)) .map((p) => `${pkg.name}: ${p.text} ${p.section}`)); expect(unplaced).toStrictEqual([]); }); @@ -205,7 +207,7 @@ describe('the texts, assembled from the installed packages', () => { const shown = [...section.matchAll(/^ {2}(midnight_\w+)/gm)].map((m) => m[1]); expect([...shown].sort()).toStrictEqual([...listed].sort()); expect(section.startsWith(` (${listed.length})\n`)).toBe(true); - expect(listed.length).toBe(38); + expect(listed.length).toBe(43); }); it('lists the grant tools under Grants (experimental), last', () => { @@ -223,7 +225,7 @@ describe('the texts, assembled from the installed packages', () => { const section = toolsSection(agentManual(registry)); expect(section).not.toContain('Grants (experimental)'); expect(section).toContain(' Other\n midnight_grant_status The wallet\'s account: address, owner key, what it holds, number of grants (see skill).'); - expect(section.startsWith(' (38)\n')).toBe(true); + expect(section.startsWith(' (43)\n')).toBe(true); }); it('leaves out a package that is not installed: its sections, its rows and its tools', () => { @@ -232,7 +234,7 @@ describe('the texts, assembled from the installed packages', () => { expect(manual).not.toContain('GRANTS (experimental)'); expect(manual).not.toContain('NO_ACCOUNT'); expect(manual).not.toContain('midnight_grant_'); - expect(toolsSection(manual).startsWith(' (30)\n')).toBe(true); + expect(toolsSection(manual).startsWith(' (35)\n')).toBe(true); expect(skillCore(registry)).not.toContain('midnight_grant_'); const full = skillFull(registry); expect(full).not.toContain('allowance (experimental)'); diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index dd38dedd..4124f887 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -104,6 +104,9 @@ describe('the accepted flags match the code', () => { 'resolvePayingTarget(': ['network', 'node', 'indexer-ws', 'proof-server'], // Reads the request's flags, and the network and endpoints. 'prepareGrant(': ['backup', 'cap', 'expires-in', 'max-coin', 'per-call', 'yes', 'network', 'node', 'indexer-ws', 'proof-server', 'wallet'], + // The swap request's terms and expiry, and the network and endpoints. + 'prepareMake(': ['give', 'give-token', 'want', 'want-token', 'expires-in', 'out', 'network', 'node', 'indexer-ws', 'proof-server'], + 'prepareTake(': ['give', 'give-token', 'want', 'want-token', 'network', 'node', 'indexer-ws', 'proof-server'], 'resolveSeedSource(': ['seed', 'wallet'], 'resolveSeed(': ['seed', 'wallet'], 'isVerbose(': ['verbose'], diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 91a06af5..da9460e9 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -50,6 +50,8 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => 'contract': { payer: true }, 'dev': { payer: true }, 'dust': {}, 'generate': { notice: GENERATE_NOTICE }, 'genesis-address': {}, 'grant': { payer: true }, 'help': {}, 'info': {}, 'inspect-cost': {}, 'localnet': {}, 'manual': {}, 'serve': {}, + // Added since the registry: swap, which pays through the payer as grant does. + 'swap': { payer: true }, 'status': { unavailable: STATUS_REFUSAL }, 'test': {}, 'transfer': {}, 'wallet': { protectors: true }, }; @@ -188,7 +190,8 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => describe('the commands that need the wallet SDK (heap re-exec and forced exit)', () => { // FACADE_COMMANDS in src/wallet.ts before the registry. - const FACADE_COMMANDS_BEFORE_REGISTRY = ['airdrop', 'transfer', 'dust', 'balance', 'serve', 'test', 'contract', 'dev', 'grant']; + // And swap, added since. + const FACADE_COMMANDS_BEFORE_REGISTRY = ['airdrop', 'transfer', 'dust', 'balance', 'serve', 'test', 'contract', 'dev', 'grant', 'swap']; it('are the ones FACADE_COMMANDS listed', () => { const rebuilt = registry.commands.filter((c) => commandNeedsWalletSdk(registry, c.name)).map((c) => c.name); @@ -286,6 +289,7 @@ describe('the MCP tools, generated from the registry', () => { expect(registry.tools.filter((t) => t.confirmation !== undefined).map((t) => t.name).sort()).toStrictEqual([ 'midnight_contract_call', 'midnight_contract_deploy', 'midnight_grant_deploy', 'midnight_grant_deposit', 'midnight_grant_issue', 'midnight_grant_revoke', 'midnight_grant_revoke_all', + 'midnight_swap_cancel', 'midnight_swap_make', 'midnight_swap_take', 'midnight_transfer', 'midnight_wallet_generate', 'midnight_wallet_remove', ]); }); @@ -376,6 +380,11 @@ describe('the MCP tools, generated from the registry', () => { ['midnight_grant_request', { link: 'L', cap: '5' }, args('grant', 'issue', ['L'], { cap: '5' })], ['midnight_grant_deploy', { network: 'undeployed' }, args('grant', 'deploy', [], { network: 'undeployed' })], ['midnight_grant_deposit', { amount: '1.5', wallet: 'alice' }, args('grant', 'deposit', ['1.5'], { wallet: 'alice' })], + ['midnight_swap_make', { give: '10', 'give-token': 'aa', want: '7', 'want-token': 'bb', 'expires-in': '600' }, args('swap', 'make', [], { give: '10', 'give-token': 'aa', want: '7', 'want-token': 'bb', 'expires-in': '600' })], + ['midnight_swap_inspect', { file: 'offer.json' }, args('swap', 'inspect', ['offer.json'], {})], + ['midnight_swap_take', { file: 'offer.json', give: '10', 'give-token': 'aa', want: '7', 'want-token': 'bb', wallet: 'bob' }, args('swap', 'take', ['offer.json'], { give: '10', 'give-token': 'aa', want: '7', 'want-token': 'bb', wallet: 'bob' })], + ['midnight_swap_cancel', { id: '3fa1c0de' }, args('swap', 'cancel', ['3fa1c0de'], {})], + ['midnight_swap_list', { network: 'undeployed' }, args('swap', 'list', [], { network: 'undeployed' })], ['midnight_grant_issue', { link: 'L', 'per-call': '2' }, args('grant', 'issue', ['L'], { 'per-call': '2', yes: true })], ['midnight_grant_revoke', { grant: '3' }, args('grant', 'revoke', ['3'], {})], ['midnight_grant_revoke_all', {}, args('grant', 'revoke-all', [], {})], diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index b346d367..8bea4cc1 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -162,10 +162,10 @@ describe('help — the lists come from the registry', () => { 'contract Inspect, deploy, call contracts', 'dev Contract dev loop (watch + deploy)', 'grant Grants that let agents spend', + 'swap Private swaps through offer files', 'config Manage CLI config', - 'cache Manage wallet cache', ]); - expect(lines).toHaveLength(19); + expect(lines).toHaveLength(20); }); it('the TTY intro lists grant after dev, with its brief', async () => { diff --git a/src/__tests__/sdk-free-base.test.ts b/src/__tests__/sdk-free-base.test.ts index 151ebddf..66f218bc 100644 --- a/src/__tests__/sdk-free-base.test.ts +++ b/src/__tests__/sdk-free-base.test.ts @@ -71,7 +71,7 @@ describe('the SDK-free base', () => { cwd: ROOT, encoding: 'utf8', timeout: 120_000, env: { ...process.env, HOME: dir }, }); expect(run.status, run.stderr).toBe(0); - expect(JSON.parse(run.stdout.trim().split('\n').at(-1)!)).toEqual([21, 37]); + expect(JSON.parse(run.stdout.trim().split('\n').at(-1)!)).toEqual([22, 42]); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/src/__tests__/swap-request.test.ts b/src/__tests__/swap-request.test.ts new file mode 100644 index 00000000..a9dfb334 --- /dev/null +++ b/src/__tests__/swap-request.test.ts @@ -0,0 +1,76 @@ +// What a `swap` command asks for, read from its arguments before any wallet +// opens: the terms, the expiry, and an offer file checked against its bytes, +// its network, the agreed terms and its expiry. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { encodeOfferEnvelope, OfferExpiredError } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { NotAnOfferError, TermsMismatchError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; +import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../lib/swap/request.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; + +const NOW = new Date('2026-11-02T12:00:00.000Z'); +const TERMS = ['--give', '10', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT]; + +describe('the terms', () => { + it('reads what the maker gives and wants, tokens lower-cased', () => { + expect(termsOf(parseArgs(['swap', 'make', '--give', '10', '--give-token', OFFER_GIVE.toUpperCase(), '--want', '7', '--want-token', OFFER_WANT]))).toEqual({ + give: { token: OFFER_GIVE, amount: 10n }, want: { token: OFFER_WANT, amount: 7n }, + }); + }); + + it.each([ + [['--give', '10', '--give-token', OFFER_GIVE], '--want and --want-token are required'], + [['--give', '0', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT], '--give must be a whole amount'], + [['--give', '1.5', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT], '--give must be a whole amount'], + [['--give', '10', '--give-token', 'night', '--want', '7', '--want-token', OFFER_WANT], '--give-token must be a token type'], + [['--give', '10', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_GIVE], 'one token for another'], + ])('refuses %j as a usage error', (flags, reason) => { + expect(() => termsOf(parseArgs(['swap', 'make', ...flags]))).toThrow(UsageError); + expect(() => termsOf(parseArgs(['swap', 'make', ...flags]))).toThrow(reason); + }); +}); + +describe('make', () => { + it('expires a day on unless --expires-in says', () => { + expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed']), NOW).expiresAt).toEqual(new Date(NOW.getTime() + DEFAULT_OFFER_LIFETIME_S * 1000)); + expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', '60']), NOW).expiresAt).toEqual(new Date(NOW.getTime() + 60_000)); + expect(() => prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', 'soon']), NOW)).toThrow('--expires-in must be a whole number of seconds'); + }); +}); + +describe('take', () => { + let dir: string; + beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mn-swap-take-')); }); + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + const offerFile = (overrides: { network?: string; expiresAt?: Date; tx?: string } = {}) => { + const read = readOffer(SWAP_OFFER_HEX); + const file = join(dir, 'offer.json'); + writeFileSync(file, encodeOfferEnvelope({ + network: (overrides.network ?? 'undeployed') as 'undeployed', id: read.id, terms: read.terms, + expiresAt: overrides.expiresAt ?? new Date(NOW.getTime() + 60_000), tx: overrides.tx ?? SWAP_OFFER_HEX, + })); + return file; + }; + const take = (file: string, terms = TERMS) => prepareTake(parseArgs(['swap', 'take', file, ...terms, '--network', 'undeployed']), NOW); + + it('reads a real offer file at the agreed terms', async () => { + const { offer, agreed, target } = await take(offerFile()); + expect(target.network).toBe('undeployed'); + expect(offer.contents.terms).toEqual(agreed); + }); + + it('refuses other terms, an expired offer, an offer for another network, and a file whose bytes say otherwise', async () => { + await expect(take(offerFile(), ['--give', '11', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT])).rejects.toBeInstanceOf(TermsMismatchError); + await expect(take(offerFile({ expiresAt: NOW }))).rejects.toBeInstanceOf(OfferExpiredError); + await expect(take(offerFile({ network: 'preview' }))).rejects.toThrow('The offer is for preview, not undeployed'); + await expect(take(offerFile({ tx: SWAP_OFFER_HEX.slice(0, -2) + '00' }))).rejects.toBeInstanceOf(NotAnOfferError); + await expect(take(join(dir, 'missing.json'))).rejects.toThrow("Can't read the offer file"); + }); +}); diff --git a/src/commands/swap.definition.ts b/src/commands/swap.definition.ts new file mode 100644 index 00000000..91adbc25 --- /dev/null +++ b/src/commands/swap.definition.ts @@ -0,0 +1,241 @@ +// The `swap` command, described once. + +import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; + +/** The terms a swap request states, as the maker gives and wants them. */ +function describeTerms(params: Readonly>): string { + return `${String(params.give)} of token ${String(params['give-token'])} for ${String(params.want)} of token ${String(params['want-token'])}`; +} + +/** A take can run: the offer file is one, for this network, with the agreed terms, not expired. */ +async function checkTake(call: ToolCheckCall) { + const { prepareTake } = await import('../lib/swap/request.ts'); + return prepareTake(call.argv(), new Date()); +} + +export const swapDefinition: CommandDefinition = { + name: 'swap', + order: 165, + subcommands: ['make', 'inspect', 'take', 'cancel', 'list'], + flags: [ + { + name: 'give', + takesValue: true, + subcommands: ['make', 'take'], + help: ['--give The amount the maker gives, in the token\'s smallest unit'], + agent: { type: 'string', description: 'Amount the maker gives (smallest unit)' }, + }, + { + name: 'give-token', + takesValue: true, + subcommands: ['make', 'take'], + help: ['--give-token The shielded token the maker gives (64 hex characters)'], + agent: { type: 'string', description: 'Shielded token the maker gives (64 hex)' }, + }, + { + name: 'want', + takesValue: true, + subcommands: ['make', 'take'], + help: ['--want The amount the maker wants back, in the token\'s smallest unit'], + agent: { type: 'string', description: 'Amount the maker wants back (smallest unit)' }, + }, + { + name: 'want-token', + takesValue: true, + subcommands: ['make', 'take'], + help: ['--want-token The shielded token the maker wants back (64 hex characters)'], + agent: { type: 'string', description: 'Shielded token the maker wants back (64 hex)' }, + }, + { + name: 'expires-in', + takesValue: true, + subcommands: ['make'], + help: ['--expires-in make: how long a taker using mn may take the offer (default: a day)'], + agent: { type: 'string', description: 'Seconds a taker using mn may take the offer (default a day)' }, + }, + { + name: 'out', + takesValue: true, + subcommands: ['make'], + help: ['--out make: where to write the offer file (default: offer-.json here)'], + agent: { type: 'string', description: 'Where to write the offer file' }, + }, + { + name: 'network', + takesValue: true, + help: ['--network Network (default: the selected one)'], + agent: { ...NETWORK_PARAM, description: 'Network (default: the selected one)' }, + }, + { + name: 'wallet', + takesValue: true, + help: ['--wallet The wallet that makes, takes, cancels or lists'], + agent: { type: 'string' }, + }, + { + name: 'node', + takesValue: true, + help: ['--node Node RPC endpoint'], + agent: ENDPOINT_PARAMS.node, + }, + { + name: 'indexer-ws', + takesValue: true, + help: ['--indexer-ws Indexer WebSocket endpoint'], + agent: ENDPOINT_PARAMS['indexer-ws'], + }, + { + name: 'proof-server', + takesValue: true, + help: ['--proof-server Proof server endpoint'], + agent: ENDPOINT_PARAMS['proof-server'], + }, + ], + help: { + description: 'Private swaps of shielded tokens, through offer files (experimental)', + usage: 'midnight swap [options]', + flags: [ + 'make Make an offer: give --give of --give-token for --want of --want-token;', + ' writes the offer file to hand the taker', + 'inspect What an offer file offers, whether it is still live, and its expiry', + 'take Take an offer at the terms agreed (--give, --give-token, --want,', + ' --want-token, as the maker states them); this wallet pays the fee', + 'cancel Cancel an open offer: spend its coins back to this wallet (a fee in Dust)', + 'list This wallet\'s open offers, and which were taken', + { flag: 'give' }, + { flag: 'give-token' }, + { flag: 'want' }, + { flag: 'want-token' }, + { flag: 'expires-in' }, + { flag: 'out' }, + { flag: 'wallet' }, + { flag: 'network' }, + { flag: 'node' }, + { flag: 'indexer-ws' }, + { flag: 'proof-server' }, + '--json Output structured JSON', + ], + examples: [ + 'midnight swap make --give 10 --give-token 00…01 --want 7 --want-token 00…02', + 'midnight swap inspect offer-3fa1….json', + 'midnight swap take offer-3fa1….json --give 10 --give-token 00…01 --want 7 --want-token 00…02', + 'midnight swap cancel 3fa1c0de', + 'midnight swap list --json', + ], + jsonFields: { + subcommand: 'The swap subcommand that ran', + network: 'Network name', + id: 'The offer\'s id: the sha256 of its transaction (make, inspect)', + file: 'Where the offer file was written (make)', + terms: 'What the maker gives and wants back: token and amount (smallest unit) each (make, inspect)', + expiresAt: 'When a taker using mn stops taking the offer (make, inspect)', + live: 'Whether none of the offer\'s coins is spent yet (inspect)', + expired: 'Whether the maker\'s expiry has passed (inspect)', + txHash: 'The swap\'s transaction (take), or the cancel\'s (cancel; null when the offer was taken already)', + cancelled: 'Whether a cancel was submitted; false when the offer was taken already (cancel)', + offers: 'The wallet\'s open offers, each with whether it is expired or taken (list)', + }, + }, + intro: { brief: 'Private swaps through offer files', order: 12.5 }, + needsWalletSdk: true, + shell: { payer: true }, + load: () => import('./swap.ts'), + mcp: { + tools: [ + { + name: 'midnight_swap_make', + description: 'Make a swap offer: the wallet gives one shielded token for another, and the offer file it writes is what to hand the taker (returns pending token). The taker pays the fee.', + annotations: { destructiveHint: true, openWorldHint: true }, + params: [ + { flag: 'give' }, + { flag: 'give-token' }, + { flag: 'want' }, + { flag: 'want-token' }, + { flag: 'expires-in' }, + { flag: 'out' }, + { flag: 'wallet' }, + { flag: 'network' }, + ], + required: ['give', 'give-token', 'want', 'want-token'], + argv: { subcommand: 'make', flags: 'rest' }, + confirmation: { + describe: (params) => { + const { network, wallet } = confirmationTarget(params); + return `Offer ${describeTerms(params)} from wallet ${wallet} on ${network}; its coins stay committed until the offer is taken`; + }, + async check(_params, call) { + const { prepareMake } = await import('../lib/swap/request.ts'); + prepareMake(call.argv(), new Date()); + }, + }, + order: 40, + }, + { + name: 'midnight_swap_inspect', + description: 'What a swap offer file offers, read from its own bytes, whether it is still live, and its expiry. Spends nothing.', + annotations: { readOnlyHint: true, openWorldHint: true }, + params: [ + { name: 'file', schema: { type: 'string', description: 'The offer file' } }, + { flag: 'network' }, + ], + required: ['file'], + argv: { subcommand: 'inspect', positionals: ['file'], flags: 'rest' }, + order: 41, + }, + { + name: 'midnight_swap_take', + description: 'Take a swap offer at the agreed terms, as the maker states them (returns pending token). Refused before anything is spent when the terms differ, the offer expired, or it was taken. The wallet pays the fee.', + annotations: { destructiveHint: true, openWorldHint: true }, + params: [ + { name: 'file', schema: { type: 'string', description: 'The offer file' } }, + { flag: 'give' }, + { flag: 'give-token' }, + { flag: 'want' }, + { flag: 'want-token' }, + { flag: 'wallet' }, + { flag: 'network' }, + ], + required: ['file', 'give', 'give-token', 'want', 'want-token'], + argv: { subcommand: 'take', positionals: ['file'], flags: 'rest' }, + confirmation: { + // The user confirms the offer as its file was read and checked. + async check(_params, call) { + const { offer, target } = await checkTake(call); + const { give, want } = offer.contents.terms; + const wallet = confirmationTarget(_params).wallet; + return `Take offer ${offer.envelope.id.slice(0, 16)}… on ${target.network} with wallet ${wallet}: pay ${want.amount} of token ${want.token}, get ${give.amount} of token ${give.token}, and pay the fee`; + }, + }, + order: 42, + }, + { + name: 'midnight_swap_cancel', + description: 'Cancel an open swap offer of the wallet\'s by spending its coins back to it (returns pending token). Costs a fee in Dust; an offer taken already is only closed.', + annotations: { destructiveHint: true, openWorldHint: true }, + params: [ + { name: 'id', schema: { type: 'string', description: 'The offer\'s id, or 8 characters of it at least' } }, + { flag: 'wallet' }, + { flag: 'network' }, + ], + required: ['id'], + argv: { subcommand: 'cancel', positionals: ['id'], flags: 'rest' }, + confirmation: { + describe: (params) => { + const { network, wallet } = confirmationTarget(params); + return `Cancel swap offer ${String(params.id)} of wallet ${wallet} on ${network}, spending its coins back to the wallet (a fee in Dust)`; + }, + async check() { /* the offer is found, and found live, by the command itself */ }, + }, + order: 43, + }, + { + name: 'midnight_swap_list', + description: 'The wallet\'s open swap offers, each with whether it expired or was taken.', + annotations: { readOnlyHint: true, openWorldHint: true }, + params: [{ flag: 'wallet' }, { flag: 'network' }], + argv: { subcommand: 'list', flags: 'rest' }, + order: 44, + }, + ], + }, +}; diff --git a/src/commands/swap.guidance.ts b/src/commands/swap.guidance.ts new file mode 100644 index 00000000..76538e0d --- /dev/null +++ b/src/commands/swap.guidance.ts @@ -0,0 +1,61 @@ +// What the swap package (mn swap) tells agents: its pieces of `help --agent` +// and of the full skill, the manual section it adds, and its tools' rows. + +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; + +export const swapGuidance: PackageGuidance = { + sections: [{ text: 'agent-manual', name: 'swaps', after: 'grants' }], + pieces: [ + { + text: 'skill-full', + section: 'what-you-can-do', + order: 45, + body: `- Swap one shielded token for another privately with another wallet, through an offer file: make it, inspect it, take it at the agreed terms. +`, + }, + { + text: 'agent-manual', + section: 'swaps', + order: 10, + body: `SWAPS (experimental) +──────────────────── + +Two wallets swap shielded tokens privately. The maker proves and signs its +half of the swap (what it gives, and what it wants paid back to itself) and +writes an offer file; the taker checks the file, adds its half and the whole +fee, and submits. Neither side can change the other's terms. Tokens are +named by their raw type (64 hex) and amounts are in the smallest unit. + + midnight swap make --give --give-token --want --want-token + [--expires-in ] [--out ] [--json] + → { id, file, terms, expiresAt, network } + midnight swap inspect [--json] + → { id, terms, expiresAt, live, expired, network } + midnight swap take --give --give-token --want --want-token [--json] + → { id, txHash, network } + midnight swap cancel [--json] + → { id, cancelled, txHash, network } + midnight swap list [--json] + → { offers: [{ id, terms, madeAt, expiresAt, expired, taken }], network } + +take states the terms as the maker states them (what the maker gives and +wants). Before the taker's wallet builds anything, take refuses an offer +whose terms differ (TERMS_MISMATCH), one past its expiry (OFFER_EXPIRED), +one already taken, and a file that is not an offer or says other than its +transaction (NOT_AN_OFFER). An offer's coins stay committed until it is +taken: the maker's own spends that would use them are refused +(OFFER_COINS_IN_USE). The expiry is mn's own: the chain lets an expired +offer be taken until its maker cancels it, which spends its coins back to +the maker (a fee in Dust). + +`, + }, + ], + toolsTable: [ + { tool: 'midnight_swap_make', group: 'swaps', order: 10, description: ['Make a swap offer file', '(two-step pending token)'] }, + { tool: 'midnight_swap_inspect', group: 'swaps', order: 20, description: ['What an offer file offers, and whether it is live'] }, + { tool: 'midnight_swap_take', group: 'swaps', order: 30, description: ['Take an offer at the agreed terms', '(two-step pending token)'] }, + { tool: 'midnight_swap_cancel', group: 'swaps', order: 35, description: ['Cancel an open offer, spending its coins back', '(two-step pending token)'] }, + { tool: 'midnight_swap_list', group: 'swaps', order: 40, description: ["The wallet's open offers, and which were taken"] }, + ], +}; diff --git a/src/commands/swap.ts b/src/commands/swap.ts new file mode 100644 index 00000000..5ad03311 --- /dev/null +++ b/src/commands/swap.ts @@ -0,0 +1,159 @@ +// swap command — private swaps of shielded tokens through offer files +// Usage: midnight swap [options] +// +// The maker's and the taker's wallets each run in this process, through the +// payer's wallet session: no server, no port. inspect and list open no wallet. + +import { existsSync, writeFileSync } from 'node:fs'; +import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { payerFor, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import type { SwapLeg, SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { header, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { resolveWalletPath, walletAddress } from '../lib/wallet-config.ts'; +import { cancelOffer, listOffers, makeOffer, standingOf, takeOffer } from '../lib/swap/offers.ts'; +import { prepareMake, prepareTake, readOfferArg } from '../lib/swap/request.ts'; + +const legJson = ({ token, amount }: SwapLeg) => ({ token, amount: amount.toString() }); +const termsJson = ({ give, want }: SwapTerms) => ({ give: legJson(give), want: legJson(want) }); +const legText = ({ token, amount }: SwapLeg) => `${amount} of ${token}`; + +export default async function swapCommand(args: ParsedArgs, ctx: CallContext): Promise { + const jsonMode = hasFlag(args, 'json'); + const spinnerFor = (label: string): Spinner => (jsonMode ? ctx.progress.silent() : ctx.progress.start(label)); + const walletFlag = getFlag(args, 'wallet'); + const now = new Date(); + + switch (args.subcommand) { + case 'make': { + const { target, terms, expiresAt, out } = prepareMake(args, now); + if (out !== undefined && existsSync(out)) throw new UsageError(`${out} already exists; an offer file is never written over another`); + if (!jsonMode) { + ctx.output.stderr('\n' + header('Swap: make an offer') + '\n\n'); + ctx.output.stderr(keyValue('Network', target.network) + '\n'); + ctx.output.stderr(keyValue('Gives', legText(terms.give)) + '\n'); + ctx.output.stderr(keyValue('Wants', legText(terms.want)) + '\n\n'); + } + const address = await walletAddress(resolveWalletPath(walletFlag), target.network); + const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal); + try { + const spinner = spinnerFor('Making the offer (proving its half)...'); + const made = await makeOffer(session, address, terms, expiresAt, now); + const file = out ?? `offer-${made.envelope.id.slice(0, 16)}.json`; + writeFileSync(file, made.file, { flag: 'wx' }); + spinner.stop('Offer made'); + if (jsonMode) { + ctx.output.result({ subcommand: 'make', network: target.network, id: made.envelope.id, file, terms: termsJson(made.envelope.terms), expiresAt: expiresAt.toISOString() }); + return; + } + ctx.output.stdout(file + '\n'); + ctx.output.stderr('\n' + keyValue('Offer', made.envelope.id) + '\n'); + ctx.output.stderr(keyValue('File', file) + '\n'); + ctx.output.stderr(keyValue('Expires', expiresAt.toISOString()) + '\n'); + ctx.output.stderr('\n' + dim(' Hand the file to the taker. Its coins stay committed until it is taken.') + '\n\n'); + } finally { + await session.close(); + } + return; + } + + case 'inspect': { + const target = resolvePayingTarget(args, 'swap', 'inspect'); + const offer = await readOfferArg(args, target); + const spinner = spinnerFor('Asking the indexer whether it is still live...'); + const { expired, spends } = await standingOf(offer, target.networkConfig, now, ctx.signal); + spinner.stop(spends.length === 0 ? 'Live' : 'Taken'); + const { envelope } = offer; + if (jsonMode) { + ctx.output.result({ subcommand: 'inspect', network: target.network, id: envelope.id, terms: termsJson(envelope.terms), expiresAt: envelope.expiresAt.toISOString(), live: spends.length === 0, expired }); + return; + } + ctx.output.stderr('\n' + header('Swap offer') + '\n\n'); + ctx.output.stderr(keyValue('Offer', envelope.id) + '\n'); + ctx.output.stderr(keyValue('Network', envelope.network) + '\n'); + ctx.output.stderr(keyValue('Maker gives', legText(envelope.terms.give)) + '\n'); + ctx.output.stderr(keyValue('Maker wants', legText(envelope.terms.want)) + '\n'); + ctx.output.stderr(keyValue('Expires', `${envelope.expiresAt.toISOString()}${expired ? ' (expired)' : ''}`) + '\n'); + ctx.output.stderr(keyValue('Live', spends.length === 0 ? 'yes' : `no: taken in ${spends[0]!.transactionHash}`) + '\n\n'); + return; + } + + case 'take': { + const { target, offer, agreed } = await prepareTake(args, now); + if (!jsonMode) { + ctx.output.stderr('\n' + header('Swap: take an offer') + '\n\n'); + ctx.output.stderr(keyValue('Offer', offer.envelope.id) + '\n'); + ctx.output.stderr(keyValue('You pay', legText(agreed.want)) + '\n'); + ctx.output.stderr(keyValue('You get', legText(agreed.give)) + '\n\n'); + } + const session = await payerFor('swap take', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal); + try { + const spinner = spinnerFor('Checking the offer, adding this half and proving the swap...'); + const txHash = await takeOffer(session, offer, agreed, target.networkConfig, now, ctx.signal); + spinner.stop('Swap submitted'); + if (jsonMode) { + ctx.output.result({ subcommand: 'take', network: target.network, id: offer.envelope.id, txHash }); + return; + } + ctx.output.stdout(txHash + '\n'); + ctx.output.stderr('\n' + dim(' Verify: midnight balance --shielded') + '\n\n'); + } finally { + await session.close(); + } + return; + } + + case 'cancel': { + const id = args.positionals[0]; + if (id === undefined) throw new UsageError('swap cancel needs the offer\'s id (8 characters of it at least): midnight swap cancel '); + const target = resolvePayingTarget(args, 'swap', 'cancel'); + const address = await walletAddress(resolveWalletPath(walletFlag), target.network); + const session = await payerFor('swap cancel', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal); + try { + const spinner = spinnerFor('Spending the offer\'s coins back to this wallet...'); + const outcome = await cancelOffer(session, target.networkConfig, address, id, ctx.signal); + spinner.stop(outcome.txHash === undefined ? 'It was taken already' : 'Offer cancelled'); + const offer = [...outcome.cancelled, ...outcome.alreadyTaken][0]!; + if (jsonMode) { + ctx.output.result({ subcommand: 'cancel', network: target.network, id: offer.id, cancelled: outcome.txHash !== undefined, txHash: outcome.txHash ?? null }); + return; + } + if (outcome.txHash !== undefined) ctx.output.stdout(outcome.txHash + '\n'); + else ctx.output.stderr('\n' + dim(` ${offer.id.slice(0, 16)}… was taken before it could be cancelled; it is closed.`) + '\n\n'); + } finally { + await session.close(); + } + return; + } + + case 'list': { + const target = resolvePayingTarget(args, 'swap', 'list'); + const address = await walletAddress(resolveWalletPath(walletFlag), target.network); + const spinner = spinnerFor('Asking the indexer about each open offer...'); + const listed = await listOffers(target.network, target.networkConfig, address, now, ctx.signal); + spinner.stop(`${listed.length} offer${listed.length === 1 ? '' : 's'}`); + if (jsonMode) { + ctx.output.result({ + subcommand: 'list', + network: target.network, + offers: listed.map(({ offer, expired, taken }) => ({ id: offer.id, terms: termsJson(offer.terms), madeAt: offer.madeAt.toISOString(), expiresAt: offer.expiresAt.toISOString(), expired, taken })), + }); + return; + } + ctx.output.stderr('\n' + header('Swap offers') + '\n\n'); + if (listed.length === 0) ctx.output.stderr(dim(' No open offers.') + '\n\n'); + for (const { offer, expired, taken } of listed) { + const status = taken ? 'taken' : expired ? 'expired (still takeable on chain until cancelled)' : 'open'; + ctx.output.stderr(keyValue(offer.id.slice(0, 16) + '…', `${legText(offer.terms.give)} for ${legText(offer.terms.want)}, ${status}`) + '\n'); + } + ctx.output.stderr('\n'); + return; + } + + default: + throw new UsageError(`Unknown swap subcommand: ${args.subcommand ?? '(none)'}. Use make, inspect, take, cancel or list.`); + } +} diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index a4ddc8bf..505f53a6 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -42,6 +42,7 @@ export const TOOL_GROUPS: readonly { readonly id: string; readonly title: string { id: 'contracts', title: 'Contracts (Compact smart contracts)', width: 52 }, { id: 'test-framework', title: 'Test Framework', width: 52 }, { id: 'grants', title: 'Grants (experimental)', width: 53 }, + { id: 'swaps', title: 'Swaps (experimental)', width: 53 }, ]; /** Where a tool no package gives a row for is listed, with its own description. */ diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 4504a1e5..4923987d 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -24,6 +24,7 @@ import { testDefinition } from '../commands/test.definition.ts'; import { devDefinition } from '../commands/dev.definition.ts'; import { contractDefinition } from '../commands/contract.definition.ts'; import { grantDefinition } from '../commands/grant.definition.ts'; +import { swapDefinition } from '../commands/swap.definition.ts'; import { localnetDefinition } from '../commands/localnet.definition.ts'; import { statusDefinition } from '@kuiralabs/midnight-chain/commands/status.definition'; import { helpDefinition } from '../commands/help.definition.ts'; @@ -35,6 +36,7 @@ import { contractGuidance } from '../commands/contract.guidance.ts'; import { connectGuidance } from '../commands/connect.guidance.ts'; import { devGuidance } from '../commands/dev.guidance.ts'; import { grantGuidance } from '../commands/grant.guidance.ts'; +import { swapGuidance } from '../commands/swap.guidance.ts'; /** The shell answers these before any command runs: no tool passes them on. */ const SHELL_ANSWERS = { notForAgents: 'the shell answers it before any command runs' }; @@ -71,6 +73,7 @@ export const installedCommands = createPackageRegistry([ }, { name: 'contract', commands: [inspectCostDefinition, contractDefinition], guidance: contractGuidance }, { name: 'connect', commands: [serveDefinition], guidance: connectGuidance }, + { name: 'swap', commands: [swapDefinition], guidance: swapGuidance }, { name: 'dev', commands: [testDefinition, devDefinition, localnetDefinition], guidance: devGuidance }, { name: 'grant', commands: [grantDefinition], guidance: grantGuidance }, { name: 'shell', commands: [helpDefinition, manualDefinition], guidance: { pieces: [] } }, diff --git a/src/lib/swap/offers.ts b/src/lib/swap/offers.ts new file mode 100644 index 00000000..b08b8d75 --- /dev/null +++ b/src/lib/swap/offers.ts @@ -0,0 +1,147 @@ +// Private swaps with offer files, over the wallet session: the maker makes an +// offer and hands its file on; the taker reads the file, checks it, and takes +// it. Everything a taker checks happens before its wallet builds or proves +// anything: that the file is an offer for this network, that its bytes say +// what the file says, that the terms are the agreed ones, that the maker's +// expiry hasn't passed, and that none of its coins is spent. + +import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { checkTerms, type OfferContents, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, type OfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { closeOpenOffers, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { spendsOf, type CoinSpend } from '@kuiralabs/midnight-chain/lib/offer-liveness'; + +/** An offer made: its file's text and what it is. */ +export interface MadeOffer { + envelope: OfferEnvelope; + /** The offer file's text. */ + file: string; +} + +/** + * Makes an offer with the session's wallet: its half of the swap, proved and + * signed, recorded among the wallet's open offers so its later spends don't + * cancel it unawares. + */ +export async function makeOffer(session: WalletSession, walletAddress: string, terms: SwapTerms, expiresAt: Date, now: Date = new Date()): Promise { + const engine = await engineFor(session.network); + const tx = await session.makeOffer(terms.give, terms.want); + const read = engine.ledger.readOffer(tx); + const envelope: OfferEnvelope = { network: session.network, id: read.id, terms: read.terms, expiresAt, tx }; + recordOpenOffer(session.network, walletAddress, { id: read.id, terms: read.terms, nullifiers: read.nullifiers, madeAt: now, expiresAt }); + return { envelope, file: encodeOfferEnvelope(envelope) }; +} + +/** An offer file read and checked against its own bytes, for this network. */ +export interface ReadOffer { + envelope: OfferEnvelope; + contents: OfferContents; +} + +/** Reads an offer file's text for `network`. Throws NotAnOfferError for anything that isn't one, or says other than its bytes. */ +export async function readOfferFile(text: string, network: NetworkName): Promise { + const envelope = decodeOfferEnvelope(text); + if (envelope.network !== network) { + throw new UsageError(`The offer is for ${envelope.network}, not ${network}: take it on ${envelope.network} (--network ${envelope.network}).`); + } + const contents = (await engineFor(network)).ledger.readOffer(envelope.tx); + assertEnvelopeMatches(envelope, contents); + return { envelope, contents }; +} + +/** Where an offer stands: live, taken (its coins spent), or past its maker's expiry. */ +export interface OfferStanding { + expired: boolean; + /** The spends of the offer's coins; empty while it is live. */ + spends: CoinSpend[]; +} + +/** Whether the offer is past its expiry, and whether its coins are spent, asked of the indexer. */ +export async function standingOf(offer: ReadOffer, networkConfig: NetworkConfig, now: Date, signal?: AbortSignal): Promise { + const spends = await spendsOf(networkConfig, offer.contents.nullifiers, { signal }); + return { expired: now.getTime() >= offer.envelope.expiresAt.getTime(), spends }; +} + +/** The offer's coins are spent: it was taken, or its maker cancelled it. */ +export class OfferTakenError extends UsageError { + constructor(id: string, spends: readonly CoinSpend[]) { + super(`The offer ${id.slice(0, 16)}… is no longer live: its coins were spent in transaction ${spends[0]!.transactionHash} (block ${spends[0]!.blockHeight}). It was taken, or its maker cancelled it.`); + this.name = 'OfferTakenError'; + } +} + +/** + * Takes an offer with the session's wallet once every check passes: the + * agreed terms, the expiry, and that the offer is live. Submits the swap and + * returns its hash. + */ +export async function takeOffer(session: WalletSession, offer: ReadOffer, agreed: SwapTerms, networkConfig: NetworkConfig, now: Date = new Date(), signal?: AbortSignal): Promise { + checkTerms(offer.contents.terms, agreed); + assertOfferUnexpired(offer.envelope, now); + const { spends } = await standingOf(offer, networkConfig, now, signal); + if (spends.length > 0) throw new OfferTakenError(offer.envelope.id, spends); + const swap = await session.takeOffer(offer.envelope.tx); + return session.submit(swap); +} + +/** An open offer of the wallet's, and whether it has been taken since. */ +export interface ListedOffer { + offer: OpenOffer; + expired: boolean; + taken: boolean; +} + +/** + * The wallet's open offers on the network, each asked of the indexer: the + * ones taken since are closed in mn's record and listed as taken. + */ +export async function listOffers(network: NetworkName, networkConfig: NetworkConfig, walletAddress: string, now: Date = new Date(), signal?: AbortSignal): Promise { + const listed: ListedOffer[] = []; + for (const offer of readOpenOffers(network, walletAddress)) { + const spends = await spendsOf(networkConfig, offer.nullifiers, { signal }); + listed.push({ offer, expired: now.getTime() >= offer.expiresAt.getTime(), taken: spends.length > 0 }); + } + const taken = listed.filter((l) => l.taken).map((l) => l.offer.id); + if (taken.length > 0) closeOpenOffers(network, walletAddress, taken); + return listed; +} + +/** No open offer of the wallet's has that id. */ +export class NoSuchOfferError extends UsageError { + constructor(id: string) { + super(`This wallet has no open offer ${id} on this network: midnight swap list shows its open offers.`); + this.name = 'NoSuchOfferError'; + } +} + +/** What cancelling did: the cancel's transaction, if one was needed, and the offers found already taken. */ +export interface CancelOutcome { + txHash: string | undefined; + cancelled: OpenOffer[]; + alreadyTaken: OpenOffer[]; +} + +/** + * Cancels the wallet's open offer with this id (or a prefix of it, 8 + * characters at least): spends its coins back to the wallet, then closes it in + * mn's record. An offer found taken already is only closed. + */ +export async function cancelOffer(session: WalletSession, networkConfig: NetworkConfig, walletAddress: string, id: string, signal?: AbortSignal): Promise { + const wanted = id.toLowerCase(); + const matches = readOpenOffers(session.network, walletAddress).filter((o) => wanted.length >= 8 && o.id.startsWith(wanted)); + if (matches.length === 0) throw new NoSuchOfferError(id); + if (matches.length > 1) throw new UsageError(`${id} names ${matches.length} open offers: give more of the id`); + const offer = matches[0]!; + const spends = await spendsOf(networkConfig, offer.nullifiers, { signal }); + if (spends.length > 0) { + closeOpenOffers(session.network, walletAddress, [offer.id]); + return { txHash: undefined, cancelled: [], alreadyTaken: [offer] }; + } + const cancel = await session.cancelOffers([offer]); + const txHash = await session.submit(cancel); + closeOpenOffers(session.network, walletAddress, [offer.id]); + return { txHash, cancelled: [offer], alreadyTaken: [] }; +} diff --git a/src/lib/swap/request.ts b/src/lib/swap/request.ts new file mode 100644 index 00000000..3b177614 --- /dev/null +++ b/src/lib/swap/request.ts @@ -0,0 +1,77 @@ +// What a `swap` command asks for, read from its arguments and checked before +// any wallet opens: the terms, the expiry, the offer file, the network. + +import { readFileSync } from 'node:fs'; +import { type ParsedArgs, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type PayingTarget, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { checkTerms, type SwapLeg, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { assertOfferUnexpired } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { readOfferFile, type ReadOffer } from './offers.ts'; + +/** How long an offer lasts for takers using mn unless the maker says. */ +export const DEFAULT_OFFER_LIFETIME_S = 24 * 60 * 60; + +function legOf(args: ParsedArgs, side: 'give' | 'want'): SwapLeg { + const amount = side === 'give' ? getFlag(args, 'give') : getFlag(args, 'want'); + const token = side === 'give' ? getFlag(args, 'give-token') : getFlag(args, 'want-token'); + if (amount === undefined || token === undefined) throw new UsageError(`--${side} and --${side}-token are required: the amount and the shielded token the maker ${side === 'give' ? 'gives' : 'wants back'}`); + if (!/^[1-9][0-9]*$/.test(amount)) throw new UsageError(`--${side} must be a whole amount of the token's smallest unit, above 0, not "${amount}"`); + if (!/^[0-9a-fA-F]{64}$/.test(token)) throw new UsageError(`--${side}-token must be a token type, 64 hex characters, not "${token}"`); + return { token: token.toLowerCase(), amount: BigInt(amount) }; +} + +/** The terms as the maker states them: --give of --give-token for --want of --want-token. */ +export function termsOf(args: ParsedArgs): SwapTerms { + const terms = { give: legOf(args, 'give'), want: legOf(args, 'want') }; + if (terms.give.token === terms.want.token) throw new UsageError('A swap gives one token for another: --give-token and --want-token are the same'); + return terms; +} + +export interface MakeRequest { + target: PayingTarget; + terms: SwapTerms; + expiresAt: Date; + /** Where to write the offer file; offer-.json in the working folder when not given. */ + out: string | undefined; +} + +export function prepareMake(args: ParsedArgs, now: Date): MakeRequest { + const lifetime = getFlag(args, 'expires-in') ?? String(DEFAULT_OFFER_LIFETIME_S); + if (!/^[1-9][0-9]*$/.test(lifetime)) throw new UsageError(`--expires-in must be a whole number of seconds above 0, not "${lifetime}"`); + return { + target: resolvePayingTarget(args, 'swap', 'make'), + terms: termsOf(args), + expiresAt: new Date(now.getTime() + Number(lifetime) * 1000), + out: getFlag(args, 'out'), + }; +} + +export interface TakeRequest { + target: PayingTarget; + offer: ReadOffer; + agreed: SwapTerms; +} + +/** The offer file named by the first positional, read for the network. */ +export async function readOfferArg(args: ParsedArgs, target: PayingTarget): Promise { + const file = args.positionals[0]; + if (file === undefined) throw new UsageError(`swap ${args.subcommand} needs the offer file: midnight swap ${args.subcommand} `); + let text: string; + try { + text = readFileSync(file, 'utf-8'); + } catch (err) { + throw new UsageError(`Can't read the offer file ${file}: ${(err as Error).message}`); + } + return readOfferFile(text, target.network); +} + +/** A take, checked as far as it can be without the chain: the file, its network, the agreed terms and the expiry. */ +export async function prepareTake(args: ParsedArgs, now: Date): Promise { + const target = resolvePayingTarget(args, 'swap', 'take'); + const agreed = termsOf(args); + const offer = await readOfferArg(args, target); + checkTerms(offer.contents.terms, agreed); + assertOfferUnexpired(offer.envelope, now); + return { target, offer, agreed }; +} From 8074271491bc2606074ff1b18496aef05828c52c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 15:17:11 -0800 Subject: [PATCH 50/88] mn balance lists every shielded token; swaps sync shielded everywhere A swap wallet holds shielded tokens besides NIGHT, and mn balance showed only shielded NIGHT. The shielded reader now returns every other token by raw type, on both engines; mn balance lists them after NIGHT, as SHIELDED_= lines on stdout and as shielded.tokens in --json. NIGHT's fields are unchanged. The reader's tests become a suite both engines run, on the real localnet events (genesis holds the two test tokens): the beta engine's reader had none. swap make, take and cancel spend shielded coins only, so the session they open syncs the shielded wallet on every network: stagenet skips it by default. The payer's connect takes { shielded } for it. --- packages/cli-core/src/lib/engine.ts | 4 +- packages/cli-core/src/lib/payer.ts | 8 +- .../engine-beta/src/shielded-direct-cache.ts | 3 +- packages/engine-beta/src/shielded-direct.ts | 16 +- .../engine-rc/src/shielded-direct-cache.ts | 3 +- packages/engine-rc/src/shielded-direct.ts | 16 +- src/__tests__/balance-command.live.test.ts | 20 +++ .../engine-beta-shielded-direct.test.ts | 19 +++ .../helpers/shielded-direct-suite.ts | 138 ++++++++++++++++++ src/__tests__/shielded-direct.test.ts | 114 +-------------- src/__tests__/swap-command.test.ts | 39 +++++ src/commands/balance.definition.ts | 4 +- src/commands/balance.ts | 15 +- src/commands/swap.ts | 10 +- src/commands/wallet.guidance.ts | 3 +- src/lib/serve-manager.ts | 6 +- src/lib/serve-payer.ts | 6 +- 17 files changed, 289 insertions(+), 135 deletions(-) create mode 100644 src/__tests__/engine-beta-shielded-direct.test.ts create mode 100644 src/__tests__/helpers/shielded-direct-suite.ts create mode 100644 src/__tests__/swap-command.test.ts diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 73e9bc04..5c70bd3e 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -142,12 +142,14 @@ export interface EngineContracts { readonly scripts: EngineContractScripts; } -/** A wallet's shielded NIGHT, from mn's own reader of the indexer's events. */ +/** A wallet's shielded balances, from mn's own reader of the indexer's events. */ export interface ShieldedBalanceResult { /** Native (NIGHT) shielded balance in atomic units. */ balance: bigint; /** Number of spendable NIGHT coins. */ availableCoins: number; + /** Shielded tokens other than NIGHT, by raw type (sorted), with their balances. */ + tokens: ReadonlyMap; /** Events applied in this run (delta since last cache save). */ eventCount: number; /** Latest event id in the saved cache (carried from prior cache if no new events). */ diff --git a/packages/cli-core/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts index a43cbccf..1963d50e 100644 --- a/packages/cli-core/src/lib/payer.ts +++ b/packages/cli-core/src/lib/payer.ts @@ -70,7 +70,13 @@ export interface Payer { /** Serves the wallet; one that runs in this process keeps the SDK's warnings to the paying call's `sdkWarnings`. */ serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; /** Opens the wallet in this process as a session, keeping the SDK's warnings to the paying call's `sdkWarnings`. */ - connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; + connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options?: ConnectOptions) => Promise; +} + +/** What a session opened by a payer needs beyond paying. */ +export interface ConnectOptions { + /** Sync the shielded wallet even where the network has no shielded faucet: the call spends shielded coins. */ + shielded?: boolean; } /** What a command's caller gives it for one call. */ diff --git a/packages/engine-beta/src/shielded-direct-cache.ts b/packages/engine-beta/src/shielded-direct-cache.ts index 2bccba78..f27e9199 100644 --- a/packages/engine-beta/src/shielded-direct-cache.ts +++ b/packages/engine-beta/src/shielded-direct-cache.ts @@ -127,7 +127,7 @@ export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/mi import type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; /** - * Read the shielded NIGHT balance for a wallet seed, using (and refreshing) the + * Read a wallet seed's shielded balances, using (and refreshing) the * indexer-direct cache. Loads any cached ZswapLocalState, resumes the * `zswapLedgerEvents` subscription from the last applied event, and persists the * extended state. First sync walks the full history (~50-70s on hosted nets); @@ -176,6 +176,7 @@ export async function readShieldedBalanceCached( return { balance: result.balance, availableCoins: result.availableCoins, + tokens: result.tokens, eventCount: result.eventCount, lastAppliedEventId: result.lastAppliedEventId >= 0 ? result.lastAppliedEventId diff --git a/packages/engine-beta/src/shielded-direct.ts b/packages/engine-beta/src/shielded-direct.ts index c4e49a19..7dd56013 100644 --- a/packages/engine-beta/src/shielded-direct.ts +++ b/packages/engine-beta/src/shielded-direct.ts @@ -37,6 +37,8 @@ export interface ShieldedDirectResult { balance: bigint; /** Number of spendable NIGHT coins tracked. */ availableCoins: number; + /** Shielded tokens other than NIGHT, by raw type, with their balances. */ + tokens: ReadonlyMap; /** Events applied in this run. */ eventCount: number; /** Final ZswapLocalState — callers serialize this for caching. */ @@ -84,25 +86,28 @@ export interface ShieldedDirectOptions { startFromId?: number; } -/** Sum spendable native-token (NIGHT) coins in a state. */ -function nativeBalance(state: ledger.ZswapLocalState): { balance: bigint; count: number } { +/** Sum a state's spendable coins: NIGHT apart, and every other token by its raw type. */ +function balancesOf(state: ledger.ZswapLocalState): { balance: bigint; count: number; tokens: Map } { // Shielded NIGHT coins carry the unshielded raw token type (matches balance.ts / facade). const night = ledger.unshieldedToken().raw; let balance = 0n; let count = 0; + const tokens = new Map(); for (const coin of state.coins) { if (coin.type === night) { balance += coin.value; count++; + } else { + tokens.set(coin.type, (tokens.get(coin.type) ?? 0n) + coin.value); } } - return { balance, count }; + return { balance, count, tokens: new Map([...tokens].sort(([a], [b]) => a.localeCompare(b))) }; } /** * Subscribe to zswap ledger events from `startFromId`, deserialize, replay into a * `ZswapLocalState` with the full secret keys (reconciling receives AND spends), - * and return the NIGHT balance plus the state + resume cursor. + * and return the balances plus the state + resume cursor. * * "Caught up" is detected when the latest `id` received equals `maxId`. */ @@ -180,10 +185,11 @@ export function readShieldedBalanceDirect( buildResult: (partial) => { try { flushPending(); - const { balance, count } = nativeBalance(state); + const { balance, count, tokens } = balancesOf(state); return { balance, availableCoins: count, + tokens, eventCount: eventsAppliedCount, state, lastAppliedEventId: lastEventId, diff --git a/packages/engine-rc/src/shielded-direct-cache.ts b/packages/engine-rc/src/shielded-direct-cache.ts index 2bccba78..f27e9199 100644 --- a/packages/engine-rc/src/shielded-direct-cache.ts +++ b/packages/engine-rc/src/shielded-direct-cache.ts @@ -127,7 +127,7 @@ export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/mi import type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; /** - * Read the shielded NIGHT balance for a wallet seed, using (and refreshing) the + * Read a wallet seed's shielded balances, using (and refreshing) the * indexer-direct cache. Loads any cached ZswapLocalState, resumes the * `zswapLedgerEvents` subscription from the last applied event, and persists the * extended state. First sync walks the full history (~50-70s on hosted nets); @@ -176,6 +176,7 @@ export async function readShieldedBalanceCached( return { balance: result.balance, availableCoins: result.availableCoins, + tokens: result.tokens, eventCount: result.eventCount, lastAppliedEventId: result.lastAppliedEventId >= 0 ? result.lastAppliedEventId diff --git a/packages/engine-rc/src/shielded-direct.ts b/packages/engine-rc/src/shielded-direct.ts index c4e49a19..7dd56013 100644 --- a/packages/engine-rc/src/shielded-direct.ts +++ b/packages/engine-rc/src/shielded-direct.ts @@ -37,6 +37,8 @@ export interface ShieldedDirectResult { balance: bigint; /** Number of spendable NIGHT coins tracked. */ availableCoins: number; + /** Shielded tokens other than NIGHT, by raw type, with their balances. */ + tokens: ReadonlyMap; /** Events applied in this run. */ eventCount: number; /** Final ZswapLocalState — callers serialize this for caching. */ @@ -84,25 +86,28 @@ export interface ShieldedDirectOptions { startFromId?: number; } -/** Sum spendable native-token (NIGHT) coins in a state. */ -function nativeBalance(state: ledger.ZswapLocalState): { balance: bigint; count: number } { +/** Sum a state's spendable coins: NIGHT apart, and every other token by its raw type. */ +function balancesOf(state: ledger.ZswapLocalState): { balance: bigint; count: number; tokens: Map } { // Shielded NIGHT coins carry the unshielded raw token type (matches balance.ts / facade). const night = ledger.unshieldedToken().raw; let balance = 0n; let count = 0; + const tokens = new Map(); for (const coin of state.coins) { if (coin.type === night) { balance += coin.value; count++; + } else { + tokens.set(coin.type, (tokens.get(coin.type) ?? 0n) + coin.value); } } - return { balance, count }; + return { balance, count, tokens: new Map([...tokens].sort(([a], [b]) => a.localeCompare(b))) }; } /** * Subscribe to zswap ledger events from `startFromId`, deserialize, replay into a * `ZswapLocalState` with the full secret keys (reconciling receives AND spends), - * and return the NIGHT balance plus the state + resume cursor. + * and return the balances plus the state + resume cursor. * * "Caught up" is detected when the latest `id` received equals `maxId`. */ @@ -180,10 +185,11 @@ export function readShieldedBalanceDirect( buildResult: (partial) => { try { flushPending(); - const { balance, count } = nativeBalance(state); + const { balance, count, tokens } = balancesOf(state); return { balance, availableCoins: count, + tokens, eventCount: eventsAppliedCount, state, lastAppliedEventId: lastEventId, diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index 8526addb..8a58f7bc 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -82,6 +82,26 @@ describe('balance command — reads address from wallet file', () => { expect(err).toContain('Unshielded'); expect(err).toContain('Shielded'); }); + + it('lists the shielded test tokens genesis holds, by raw type, in the text and in --json', async () => { + // Every dev chain's genesis wallet holds two shielded test tokens beside NIGHT. + const tokens = ['00'.repeat(31) + '01', '00'.repeat(31) + '02']; + const walletFile = path.join(TEST_DIR, 'wallet.json'); + saveWalletConfig({ seed: GENESIS_SEED, addresses: deriveAllAddresses(genesisSeedBuffer), createdAt: '2026-01-01T00:00:00.000Z' }, walletFile); + + await cliCall(balanceCommand, parseArgs(['balance', '--wallet', walletFile, '--network', 'undeployed'])); + for (const token of tokens) { + expect(io.stdout()).toMatch(new RegExp(`^SHIELDED_${token}=[1-9]\\d*$`, 'm')); + expect(io.stderr()).toContain(token); + } + + io.restore(); + io = captureOutput(); + await cliCall(balanceCommand, parseArgs(['balance', '--wallet', walletFile, '--network', 'undeployed', '--json'])); + const data = JSON.parse(io.stdout().trim()); + for (const token of tokens) expect(data.shielded.tokens[token]).toMatch(/^[1-9]\d*$/); + expect(data.shielded.tokens).not.toHaveProperty('NIGHT'); + }); }); diff --git a/src/__tests__/engine-beta-shielded-direct.test.ts b/src/__tests__/engine-beta-shielded-direct.test.ts new file mode 100644 index 00000000..304c66a6 --- /dev/null +++ b/src/__tests__/engine-beta-shielded-direct.test.ts @@ -0,0 +1,19 @@ +// The indexer-direct shielded reader on the beta engine, with the beta +// engine's own ledger. The tests are the suite both engines run: +// helpers/shielded-direct-suite.ts. + +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { readShieldedBalanceDirect } from '@kuiralabs/midnight-engine-beta/shielded-direct'; +import { deriveShieldedSeed } from '@kuiralabs/midnight-engine-beta/derivation'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { shieldedDirectSuite } from './helpers/shielded-direct-suite.ts'; + +const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +const ledger = await import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, '@midnightntwrk/ledger-v9')!, 'midnight_ledger_wasm_v9_fs.js')).href); + +shieldedDirectSuite({ + set: 'beta', + secretKeysFor: (seedHex: string): Parameters[0] => ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(Buffer.from(seedHex, 'hex'))), + readShieldedBalanceDirect, +}); diff --git a/src/__tests__/helpers/shielded-direct-suite.ts b/src/__tests__/helpers/shielded-direct-suite.ts new file mode 100644 index 00000000..c9a3ae63 --- /dev/null +++ b/src/__tests__/helpers/shielded-direct-suite.ts @@ -0,0 +1,138 @@ +// The indexer-direct shielded reader's tests, which both engines run, each +// with its own ledger: shielded-direct.test.ts (rc) and +// engine-beta-shielded-direct.test.ts (beta). + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; +import type { AddressInfo } from 'node:net'; +import zswapEvents from '../fixtures/zswap-events-localnet.json'; + +/** An engine's reader, and a wallet's secret keys made with the engine's own ledger. */ +export interface ShieldedDirectEngine { + set: 'rc' | 'beta'; + secretKeysFor(seedHex: string): Keys; + readShieldedBalanceDirect(secretKeys: Keys, indexerWS: string, options?: { idleMs?: number; initialState?: State; startFromId?: number }): Promise<{ + balance: bigint; + availableCoins: number; + tokens: ReadonlyMap; + eventCount: number; + state: State; + lastAppliedEventId: number; + partial: boolean; + }>; +} + +// Real zswap ledger events (ledger 9, event[v14]) captured from a fresh localnet chain. Seeds 0x01 and +// 0x02 are localnet genesis-funded wallets (250M shielded NIGHT each); genesis +// (0x01) airdropped 100M to 0x02, so 0x01 ends at 150M (a spend) and 0x02 at +// 350M (its 250M allocation + the 100M it received). All seeds are throwaway +// constants — no real wallet's seed is committed. The fixture is the FULL event +// stream; each wallet's balance is reconstructed by replaying it with that +// wallet's secret keys. +const GENESIS_SEED = '0000000000000000000000000000000000000000000000000000000000000001'; // spender +const GENESIS2_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; // received on top +const EMPTY_SEED = '00000000000000000000000000000000000000000000000000000000000000aa'; // non-genesis, no coins +const NIGHT_150M = 150_000_000_000_000n; +const NIGHT_350M = 350_000_000_000_000n; +// Both genesis wallets also hold 50M of each of the dev chain's two shielded test tokens. +const TEST_TOKEN_1 = '00'.repeat(31) + '01'; +const TEST_TOKEN_2 = '00'.repeat(31) + '02'; +const TOKENS_50M = 50_000_000_000_000n; + +/** + * Minimal in-process indexer: speaks the graphql-transport-ws handshake and + * replays the fixture's `zswapLedgerEvents` from the subscription's start index. + * Stubs the external indexer boundary only — the reader under test is real. + */ +function startFakeIndexer(events: { id: number; raw: string; maxId: number }[]): Promise<{ url: string; close: () => Promise }> { + return new Promise((resolve) => { + const wss = new WebSocketServer({ host: '127.0.0.1', port: 0, handleProtocols: () => 'graphql-transport-ws' }); + wss.on('connection', (socket: WsSocket) => { + socket.on('message', (data) => { + const msg = JSON.parse(data.toString()); + if (msg.type === 'connection_init') { + socket.send(JSON.stringify({ type: 'connection_ack' })); + return; + } + if (msg.type === 'subscribe') { + const startId: number = msg.payload?.variables?.id ?? 0; + for (const e of events) { + if (e.id < startId) continue; + socket.send(JSON.stringify({ id: msg.id, type: 'next', payload: { data: { zswapLedgerEvents: e } } })); + } + // Leave the socket open; the reader finishes when it sees id >= maxId. + } + }); + }); + wss.on('listening', () => { + const port = (wss.address() as AddressInfo).port; + resolve({ + url: `ws://127.0.0.1:${port}`, + close: () => new Promise((r) => wss.close(() => r())), + }); + }); + }); +} + +export function shieldedDirectSuite(engine: ShieldedDirectEngine): void { + const { secretKeysFor, readShieldedBalanceDirect } = engine; + + describe(`readShieldedBalanceDirect (${engine.set} engine)`, () => { + let indexer: { url: string; close: () => Promise }; + + beforeAll(async () => { indexer = await startFakeIndexer(zswapEvents as any); }); + afterAll(async () => { await indexer.close(); }); + + it('removes SPENT coins for the spender (regression: was a 250M over-count)', async () => { + // Genesis started with a 250M allocation and spent 100M. If spends weren't + // reconciled, this would read 250M — the bug this reader fixes. + const r = await readShieldedBalanceDirect(secretKeysFor(GENESIS_SEED), indexer.url, { idleMs: 200 }); + expect(r.balance).toBe(NIGHT_150M); + expect(r.availableCoins).toBe(3); + expect(r.partial).toBe(false); + expect(r.eventCount).toBe(zswapEvents.length); + }); + + it('adds received coins on top of an existing balance', async () => { + // 0x02 holds its own 250M allocation AND the 100M it received from genesis. + const r = await readShieldedBalanceDirect(secretKeysFor(GENESIS2_SEED), indexer.url, { idleMs: 200 }); + expect(r.balance).toBe(NIGHT_350M); + expect(r.availableCoins).toBe(6); + }); + + it('reads the other shielded tokens by raw type, apart from NIGHT', async () => { + const r = await readShieldedBalanceDirect(secretKeysFor(GENESIS_SEED), indexer.url, { idleMs: 200 }); + expect([...r.tokens]).toEqual([[TEST_TOKEN_1, TOKENS_50M], [TEST_TOKEN_2, TOKENS_50M]]); + expect(r.balance).toBe(NIGHT_150M); + }); + + it('returns a zero balance for a wallet with no shielded coins', async () => { + const r = await readShieldedBalanceDirect(secretKeysFor(EMPTY_SEED), indexer.url, { idleMs: 200 }); + expect(r.balance).toBe(0n); + expect(r.availableCoins).toBe(0); + expect(r.tokens.size).toBe(0); + }); + + it('resumes from a cached state + cursor and matches a full replay', async () => { + // Full replay of the first half, then resume from the checkpoint for the rest. + const keys = secretKeysFor(GENESIS_SEED); + const midId = zswapEvents[Math.floor(zswapEvents.length / 2)].id; + + const firstHalf = (zswapEvents as any[]).filter((e) => e.id <= midId).map((e) => ({ ...e, maxId: midId })); + const partialIndexer = await startFakeIndexer(firstHalf); + const first = await readShieldedBalanceDirect(keys, partialIndexer.url, { idleMs: 200 }); + await partialIndexer.close(); + expect(first.lastAppliedEventId).toBe(midId); + + // Resume against the full stream from the checkpoint — only the remaining + // events are applied, and the final balance matches a from-scratch read. + const resumed = await readShieldedBalanceDirect(keys, indexer.url, { + idleMs: 200, + initialState: first.state, + startFromId: first.lastAppliedEventId + 1, + }); + expect(resumed.balance).toBe(NIGHT_150M); + expect(resumed.availableCoins).toBe(3); + }); + }); +} diff --git a/src/__tests__/shielded-direct.test.ts b/src/__tests__/shielded-direct.test.ts index a545b936..302cb104 100644 --- a/src/__tests__/shielded-direct.test.ts +++ b/src/__tests__/shielded-direct.test.ts @@ -1,111 +1,13 @@ -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; -import type { AddressInfo } from 'node:net'; +// The indexer-direct shielded reader on the rc engine. The tests are the +// suite both engines run: helpers/shielded-direct-suite.ts. + import * as ledger from '@midnightntwrk/ledger-v9'; import { readShieldedBalanceDirect } from '@kuiralabs/midnight-engine-rc/shielded-direct'; import { deriveShieldedSeed } from '@kuiralabs/midnight-engine-rc/derivation'; -import zswapEvents from './fixtures/zswap-events-localnet.json'; - -// Real zswap ledger events (ledger 9, event[v14]) captured from a fresh localnet chain. Seeds 0x01 and -// 0x02 are localnet genesis-funded wallets (250M shielded NIGHT each); genesis -// (0x01) airdropped 100M to 0x02, so 0x01 ends at 150M (a spend) and 0x02 at -// 350M (its 250M allocation + the 100M it received). All seeds are throwaway -// constants — no real wallet's seed is committed. The fixture is the FULL event -// stream; each wallet's balance is reconstructed by replaying it with that -// wallet's secret keys. -const GENESIS_SEED = '0000000000000000000000000000000000000000000000000000000000000001'; // spender -const GENESIS2_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; // received on top -const EMPTY_SEED = '00000000000000000000000000000000000000000000000000000000000000aa'; // non-genesis, no coins -const NIGHT_150M = 150_000_000_000_000n; -const NIGHT_350M = 350_000_000_000_000n; - -function secretKeysFor(seedHex: string): ledger.ZswapSecretKeys { - return ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(Buffer.from(seedHex, 'hex'))); -} - -/** - * Minimal in-process indexer: speaks the graphql-transport-ws handshake and - * replays the fixture's `zswapLedgerEvents` from the subscription's start index. - * Stubs the external indexer boundary only — the reader under test is real. - */ -function startFakeIndexer(events: { id: number; raw: string; maxId: number }[]): Promise<{ url: string; close: () => Promise }> { - return new Promise((resolve) => { - const wss = new WebSocketServer({ host: '127.0.0.1', port: 0, handleProtocols: () => 'graphql-transport-ws' }); - wss.on('connection', (socket: WsSocket) => { - socket.on('message', (data) => { - const msg = JSON.parse(data.toString()); - if (msg.type === 'connection_init') { - socket.send(JSON.stringify({ type: 'connection_ack' })); - return; - } - if (msg.type === 'subscribe') { - const startId: number = msg.payload?.variables?.id ?? 0; - for (const e of events) { - if (e.id < startId) continue; - socket.send(JSON.stringify({ id: msg.id, type: 'next', payload: { data: { zswapLedgerEvents: e } } })); - } - // Leave the socket open; the reader finishes when it sees id >= maxId. - } - }); - }); - wss.on('listening', () => { - const port = (wss.address() as AddressInfo).port; - resolve({ - url: `ws://127.0.0.1:${port}`, - close: () => new Promise((r) => wss.close(() => r())), - }); - }); - }); -} - -describe('readShieldedBalanceDirect', () => { - let indexer: { url: string; close: () => Promise }; - - beforeAll(async () => { indexer = await startFakeIndexer(zswapEvents as any); }); - afterAll(async () => { await indexer.close(); }); - - it('removes SPENT coins for the spender (regression: was a 250M over-count)', async () => { - // Genesis started with a 250M allocation and spent 100M. If spends weren't - // reconciled, this would read 250M — the bug this reader fixes. - const r = await readShieldedBalanceDirect(secretKeysFor(GENESIS_SEED), indexer.url, { idleMs: 200 }); - expect(r.balance).toBe(NIGHT_150M); - expect(r.availableCoins).toBe(3); - expect(r.partial).toBe(false); - expect(r.eventCount).toBe(zswapEvents.length); - }); - - it('adds received coins on top of an existing balance', async () => { - // 0x02 holds its own 250M allocation AND the 100M it received from genesis. - const r = await readShieldedBalanceDirect(secretKeysFor(GENESIS2_SEED), indexer.url, { idleMs: 200 }); - expect(r.balance).toBe(NIGHT_350M); - expect(r.availableCoins).toBe(6); - }); - - it('returns a zero balance for a wallet with no shielded coins', async () => { - const r = await readShieldedBalanceDirect(secretKeysFor(EMPTY_SEED), indexer.url, { idleMs: 200 }); - expect(r.balance).toBe(0n); - expect(r.availableCoins).toBe(0); - }); - - it('resumes from a cached state + cursor and matches a full replay', async () => { - // Full replay of the first half, then resume from the checkpoint for the rest. - const keys = secretKeysFor(GENESIS_SEED); - const midId = zswapEvents[Math.floor(zswapEvents.length / 2)].id; - - const firstHalf = (zswapEvents as any[]).filter((e) => e.id <= midId).map((e) => ({ ...e, maxId: midId })); - const partialIndexer = await startFakeIndexer(firstHalf); - const first = await readShieldedBalanceDirect(keys, partialIndexer.url, { idleMs: 200 }); - await partialIndexer.close(); - expect(first.lastAppliedEventId).toBe(midId); +import { shieldedDirectSuite } from './helpers/shielded-direct-suite.ts'; - // Resume against the full stream from the checkpoint — only the remaining - // events are applied, and the final balance matches a from-scratch read. - const resumed = await readShieldedBalanceDirect(keys, indexer.url, { - idleMs: 200, - initialState: first.state, - startFromId: first.lastAppliedEventId + 1, - }); - expect(resumed.balance).toBe(NIGHT_150M); - expect(resumed.availableCoins).toBe(3); - }); +shieldedDirectSuite({ + set: 'rc', + secretKeysFor: (seedHex: string): Parameters[0] => ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(Buffer.from(seedHex, 'hex'))), + readShieldedBalanceDirect, }); diff --git a/src/__tests__/swap-command.test.ts b/src/__tests__/swap-command.test.ts new file mode 100644 index 00000000..68b01ed5 --- /dev/null +++ b/src/__tests__/swap-command.test.ts @@ -0,0 +1,39 @@ +// What `swap take` asks of its payer: a wallet session whose shielded side is +// synced, on every network (a swap spends shielded coins only, and stagenet +// skips the shielded sync by default). Nothing reaches a chain: the payer is +// the program's own and opens no wallet. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { encodeOfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import type { ConnectOptions, Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; +import swapCommand from '../commands/swap.ts'; +import { cliCall } from './helpers/cli-call.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; + +const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; +const TERMS = ['--give', '10', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT]; + +let dir: string; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mn-swap-command-')); }); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('swap take', () => { + it('asks its payer for a session with the shielded side synced', async () => { + const read = readOffer(SWAP_OFFER_HEX); + const file = join(dir, 'offer.json'); + writeFileSync(file, encodeOfferEnvelope({ network: 'undeployed', id: read.id, terms: read.terms, expiresAt: new Date(Date.now() + 3_600_000), tx: SWAP_OFFER_HEX })); + const asked: (ConnectOptions | undefined)[] = []; + const payer: Payer = { + assertCanPay: async () => { throw new Error('not used'); }, + serve: async () => { throw new Error('not used'); }, + connect: async (_target, _wallet, _progress, _sdkWarnings, _signal, options) => { asked.push(options); throw new Error('no wallet here'); }, + }; + await expect(cliCall(swapCommand, parseArgs(['swap', 'take', file, ...TERMS, '--network', 'undeployed', ...ENDPOINTS, '--json']), { payer })).rejects.toThrow('no wallet here'); + expect(asked).toEqual([{ shielded: true }]); + }); +}); diff --git a/src/commands/balance.definition.ts b/src/commands/balance.definition.ts index 1f58bd71..b7ab9d12 100644 --- a/src/commands/balance.definition.ts +++ b/src/commands/balance.definition.ts @@ -71,7 +71,7 @@ export const balanceDefinition: CommandDefinition = { shieldedAddress: 'Shielded address', network: 'Network name', unshielded: '{ NIGHT, utxoCount }', - shielded: '{ NIGHT, availableCoins, pendingCoins }', + shielded: '{ NIGHT, availableCoins, pendingCoins, tokens: { : amount } }', }, }, intro: { brief: 'Check balance', order: 3 }, @@ -82,7 +82,7 @@ export const balanceDefinition: CommandDefinition = { tools: [ { name: 'midnight_balance', - description: 'NIGHT balance. Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.', + description: 'NIGHT balance, and any other shielded tokens by raw type (shielded.tokens). Default: { network, unshielded, shielded } — no echoed addresses. Pass { full: true } for the human shape including address + shieldedAddress.', annotations: { readOnlyHint: true, openWorldHint: true }, params: [ { name: 'address', schema: { type: 'string' } }, diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 9a6a6aa2..0dabf1a8 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -249,6 +249,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise let shieldedBalance = 0n; let shieldedCoins = 0; let pendingCoins = 0; + let shieldedTokens: ReadonlyMap = new Map(); if (shieldedEnabled) { if (!isJson) activeSpinner = ctx.progress.start('Syncing shielded...'); @@ -284,6 +285,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise ); shieldedBalance = shieldedResult.balance; shieldedCoins = shieldedResult.availableCoins; + shieldedTokens = shieldedResult.tokens; pendingCoins = 0; // confirmed chain state from events; no in-flight coins if (activeSpinner) { @@ -292,7 +294,12 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise if (shieldedBalance > 0n) { ctx.output.stderr(keyValue(' NIGHT', bold(formatNight(shieldedBalance))) + '\n'); ctx.output.stderr(keyValue(' Coins', `${shieldedCoins} available, ${pendingCoins} pending`) + '\n'); - } else { + } + // Other tokens by their full raw type: what `mn swap` and transfers take. + for (const [tokenType, amount] of shieldedTokens) { + ctx.output.stderr(keyValue(' Token', `${bold(amount.toString())} ${dim(tokenType)}`) + '\n'); + } + if (shieldedBalance === 0n && shieldedTokens.size === 0) { ctx.output.stderr(` ${dim('No shielded balance')}\n`); } } @@ -301,6 +308,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise } if (isJson) { + const tokens = Object.fromEntries([...shieldedTokens].map(([tokenType, amount]) => [tokenType, amount.toString()])); // Slim drops the unshielded + shielded address strings (~220 chars // combined). Agents already know which wallet they queried. // shieldedSynced=false means shielded was skipped (not a confirmed zero) — @@ -309,7 +317,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise ctx.output.result({ network: networkName, unshielded: { NIGHT: toNight(unshieldedBalance), utxoCount: unshieldedUtxos }, - shielded: { NIGHT: toNight(shieldedBalance), availableCoins: shieldedCoins, pendingCoins }, + shielded: { NIGHT: toNight(shieldedBalance), availableCoins: shieldedCoins, pendingCoins, tokens }, shieldedSynced: shieldedEnabled, }); return; @@ -319,7 +327,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise shieldedAddress: liveShieldedAddrStr, network: networkName, unshielded: { NIGHT: toNight(unshieldedBalance), utxoCount: unshieldedUtxos }, - shielded: { NIGHT: toNight(shieldedBalance), availableCoins: shieldedCoins, pendingCoins }, + shielded: { NIGHT: toNight(shieldedBalance), availableCoins: shieldedCoins, pendingCoins, tokens }, shieldedSynced: shieldedEnabled, }); return; @@ -328,6 +336,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise // When shielded was skipped, say so on stdout too — `=0` would read as a // confirmed zero to a script parsing the pipeable output. ctx.output.stdout(`SHIELDED_NIGHT=${shieldedEnabled ? shieldedBalance : 'skipped'}\n`); + for (const [tokenType, amount] of shieldedTokens) ctx.output.stdout(`SHIELDED_${tokenType}=${amount}\n`); ctx.output.stderr('\n' + divider() + '\n\n'); } catch (err) { activeSpinner?.fail('Failed'); diff --git a/src/commands/swap.ts b/src/commands/swap.ts index 5ad03311..16cf63c6 100644 --- a/src/commands/swap.ts +++ b/src/commands/swap.ts @@ -7,7 +7,7 @@ import { existsSync, writeFileSync } from 'node:fs'; import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { payerFor, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { type ConnectOptions, payerFor, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import type { SwapLeg, SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { header, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; @@ -20,6 +20,8 @@ import { prepareMake, prepareTake, readOfferArg } from '../lib/swap/request.ts'; const legJson = ({ token, amount }: SwapLeg) => ({ token, amount: amount.toString() }); const termsJson = ({ give, want }: SwapTerms) => ({ give: legJson(give), want: legJson(want) }); const legText = ({ token, amount }: SwapLeg) => `${amount} of ${token}`; +// A swap spends shielded coins only: its wallet syncs the shielded side on every network, stagenet included. +const SHIELDED: ConnectOptions = { shielded: true }; export default async function swapCommand(args: ParsedArgs, ctx: CallContext): Promise { const jsonMode = hasFlag(args, 'json'); @@ -38,7 +40,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P ctx.output.stderr(keyValue('Wants', legText(terms.want)) + '\n\n'); } const address = await walletAddress(resolveWalletPath(walletFlag), target.network); - const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal); + const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Making the offer (proving its half)...'); const made = await makeOffer(session, address, terms, expiresAt, now); @@ -89,7 +91,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P ctx.output.stderr(keyValue('You pay', legText(agreed.want)) + '\n'); ctx.output.stderr(keyValue('You get', legText(agreed.give)) + '\n\n'); } - const session = await payerFor('swap take', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal); + const session = await payerFor('swap take', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Checking the offer, adding this half and proving the swap...'); const txHash = await takeOffer(session, offer, agreed, target.networkConfig, now, ctx.signal); @@ -111,7 +113,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P if (id === undefined) throw new UsageError('swap cancel needs the offer\'s id (8 characters of it at least): midnight swap cancel '); const target = resolvePayingTarget(args, 'swap', 'cancel'); const address = await walletAddress(resolveWalletPath(walletFlag), target.network); - const session = await payerFor('swap cancel', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal); + const session = await payerFor('swap cancel', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Spending the offer\'s coins back to this wallet...'); const outcome = await cancelOffer(session, target.networkConfig, address, id, ctx.signal); diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index 2abdcccc..295a512f 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -35,7 +35,8 @@ proofs. The CLI provides full shielded support: midnight balance --json → { address, shieldedAddress, network, unshielded: { NIGHT, utxoCount }, - shielded: { NIGHT, availableCoins, pendingCoins } } + shielded: { NIGHT, availableCoins, pendingCoins, + tokens: { : amount } } } Shielded airdrop (localnet only — genesis has 250M shielded NIGHT): midnight airdrop 100 --shielded --json diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 66e6de52..1d293302 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -31,6 +31,8 @@ export interface ServeManagerOptions { dustWaitMs?: number; /** The SDK warnings of the call that serves, listened to while its wallet runs. */ sdkWarnings: CallSdkWarnings; + /** Sync the shielded wallet even where the network has no shielded faucet. */ + forceShielded?: boolean; /** Cancels the start: what was started is stopped, and the start fails with CancelledError. */ signal?: AbortSignal; } @@ -246,8 +248,8 @@ export async function openConnector(options: ServeManagerOptions): Promise { +async function connectWallet({ network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options: ConnectOptions = {}): Promise { const { openConnector } = await import('./serve-manager.ts'); const engine = await engineFor(network); - const open = () => openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, signal }); + const open = () => openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, forceShielded: options.shielded, signal }); return sessionOver(network, await open(), (tx, stage) => engine.ledger.readTransaction(tx, stage), { reopen: open, onMessage: (msg) => progress.update(msg) }); } From 5568197578cbef7360b59b8313dedb8a1bc05181 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Mon, 2 Nov 2026 16:39:44 -0800 Subject: [PATCH 51/88] release 0.6.0-rc.11 Private swaps through offer files (mn swap and its MCP tools), stagenet on the beta engine, the wallet session for programs, and mn balance listing every shielded token. mn now comes with four packages of its own (core, chain and the two engines), each published first by the release job. --- CHANGELOG.md | 22 ++++++++++++++++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fdd22bd..ed27b93a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,17 @@ All notable changes to midnight-wallet-cli will be documented in this file. ## [Unreleased] +## [0.6.0-rc.11] - 2026-11-02 + ### Added +- **Private swaps of shielded tokens, through offer files: `midnight swap make | inspect | take | cancel | list`.** The maker proves and signs its half of a swap (one shielded token for another, no fee) and `make` writes it as an offer file to hand on. `inspect` reads the file from its own bytes and asks the indexer whether its coins are still unspent. `take` adds the taker's half and the fee and submits, after checking, before anything is built or spent, that the file is an offer for this network, that it says what its bytes say, that its terms are the ones agreed (`--give`, `--give-token`, `--want`, `--want-token`), that the maker's expiry (`--expires-in`, a day by default) hasn't passed, and that it wasn't taken. The maker's open offers are recorded, and a later command of the maker's that would spend their coins is refused (`OFFER_COINS_IN_USE`); `cancel ` spends an offer's coins back to the wallet, which is what makes an expiry binding on chain; `list` shows the open offers and closes the ones taken. New error codes, exit code 2: `NOT_AN_OFFER`, `TERMS_MISMATCH`, `OFFER_EXPIRED`, `OFFER_COINS_IN_USE`. +- **MCP tools `midnight_swap_make`, `_inspect`, `_take`, `_cancel` and `_list`.** Make, take and cancel return a confirmation token; take's confirmation names what is paid and what is got, read from the offer itself, and a take at other terms is refused before a token is issued. +- **`mn balance` lists every shielded token the wallet holds**, by its raw type, after NIGHT: in the text, as `SHIELDED_=` lines on stdout, and as `shielded.tokens` in `--json`. NIGHT's fields are unchanged. +- **Stagenet**, Midnight's public ledger-9 network, on the SDK's beta set: wallets get a stagenet address (an existing wallet gets one when it is next read), and every command, the help, the manuals and the MCP tools take `--network stagenet`. Stagenet skips the shielded sync unless a command needs it (a swap) or `--force-shielded` is passed, and reads Dust in WASM, with a notice, until a ledger-9 sidecar exists. +- **Two SDK engines, the network picks one.** The SDK sits behind an engine package: `@kuiralabs/midnight-engine-rc` (the local network) and `@kuiralabs/midnight-engine-beta` (stagenet). `midnight config set sdk-set [--network ]` runs a network on the other set. A process that loaded one set refuses work on the other (`OTHER_SDK_SET`), and the MCP server says to start one for that network. +- **A wallet session for programs.** `openWalletSession` in `@kuiralabs/midnight-cli-core` opens a seed's wallet in the program's own process, on either engine, synced and with its Dust ready, and gives balances, addresses, signing, swaps (`swap`, `makeOffer`, `takeOffer`, `cancelOffers`), reading a transaction and submitting it, with hex and plain values only. Closing it reverts what it built but never submitted. + - **Every secret mn keeps is encrypted under one passphrase.** Each wallet's seed and mnemonic, and each account's owner key, records (its encryption secrets), roster of grants and private state, are sealed at rest: scrypt to a key, then AES-256-GCM, each secret bound to what it is for. A wallet's addresses stay readable, so `wallet list`, `wallet info` and anything that only reads addresses ask for nothing. A command that needs a secret asks for the passphrase once at a terminal, or reads `MN_PASSPHRASE` (scripts, CI, the MCP server); without one it is refused (`PASSPHRASE_REQUIRED`), and a wrong one changes nothing (`WRONG_PASSPHRASE`). The first new wallet sets it, at least 12 characters. - **`midnight wallet protect`** sets the passphrase and encrypts every wallet and account an earlier mn wrote in plain text, in one step, without loss: an account's private state is moved off the public password every account used before onto a password of its own. An interrupted run is finished by running it again. Until then plain-text wallets and accounts keep working, with a warning. - **`midnight grant export ` and `import `**: an account's encrypted backup, everything another machine needs to act as the same owner, opened only with the passphrase. @@ -16,6 +25,16 @@ All notable changes to midnight-wallet-cli will be documented in this file. ### Changed +- **mn comes with four packages of its own.** `midnight-wallet-cli` now depends on `@kuiralabs/midnight-cli-core`, `@kuiralabs/midnight-chain` and the two engines, at exact versions, and ships an `npm-shrinkwrap.json` of the tree its tests ran on; each engine ships one of its own SDK set, for a program that installs it without mn. +- **A contract compiled for another compact runtime is refused up front**, naming both runtimes and the compiler the network's engine needs: by `contract deploy` and `call` before the wallet starts, by their MCP tools before a confirmation token, and by the runner before any script. It used to fail inside its script after the wallet had synced ("Version mismatch"). +- **A transaction the node refuses says why, everywhere.** The CLI and the MCP server report "The node refused the transaction: ", as `INVALID_DUST_PROOF` or `STALE_UTXO` when the reason is known and `TX_REJECTED` otherwise (exit code 6). It was `UNKNOWN` (exit 1), the reason only in the node's log. +- **The CLI refuses a flag that belongs to another subcommand** (`INVALID_ARGS`, exit 2), naming the subcommands it is for: `mn dust register --seed x` ran and ignored the seed. The MCP server already refused it. +- **`mn --help` shows the command's own help**, also on a subcommand line (`mn wallet generate --help`). +- **MCP confirmations name the endpoints a call is sent to**, given ones as given and configured ones marked "set with config". +- **MCP on/off parameters are booleans** (`force`, `shielded`, `no-cache`), and the server refuses a parameter of the wrong type or one a tool doesn't take (`INVALID_ARGS`): `"false"` used to switch them on. `midnight_wallet_generate` with `force` asks for confirmation, and `midnight_wallet_remove` asks too, refusing a wallet it can't remove before asking. +- **Every command stops when it is cancelled**, at the terminal or by an MCP client, with `CANCELLED`, including while its first network read hangs. +- **`mn contract` takes the configured network** (`midnight config set network`), as every other command does; it always took undeployed. + - **A new account's owner key is its own, encrypted.** It is made on this machine as a valid secp256k1 key, independent of the wallet's seed (MIP-0013), and kept encrypted with the account's records; results say `ownerKey: "sealed"`, or `"plain-text"` for an account an earlier mn made, until `wallet protect`. - **`wallet seed`** asks for the passphrase. @@ -27,6 +46,9 @@ All notable changes to midnight-wallet-cli will be documented in this file. ### Fixed +- **`mn contract state` outside the contract's directory shows the state**, as plain JSON, not the runtime's handle (`{"__wbg_ptr":…}`); and a cancelled `contract state` stops instead of waiting for ever on an indexer that never answers. +- **A wallet `mn contract` serves restores from the Dust checkpoint**: with no saved wallet it replayed the whole Dust history and, on stagenet, ran out of time (`SYNC_TIMEOUT`). + - **A refused `mn grant` command leaves no account folder behind.** The folder under `~/.midnight/accounts///` was made before the command checked its wallet or its account; now only `deploy`, `import` and `device new` make it, once the wallet's file is found. `wallet protect` passes over an empty one an earlier release left, rather than naming it as an account whose wallet is gone. - **A transaction the node refuses says why.** When a submit through `mn serve`'s DApp connector (and `mn grant`, which pays through the same code) failed, it reported only `Transaction submission error`: the wallet SDK's error keeps the node's answer where mn did not look. It now carries the node's own words, such as `1010: Invalid Transaction: Custom error: 139`, so an app can tell the node refused it, and why. diff --git a/package-lock.json b/package-lock.json index b876e279..8d299bbd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.10", + "version": "0.6.0-rc.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.10", + "version": "0.6.0-rc.11", "license": "Apache-2.0", "workspaces": [ "packages/connector", diff --git a/package.json b/package.json index 60373294..e5f84664 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.10", + "version": "0.6.0-rc.11", "type": "module", "description": "Git-style CLI wallet for the Midnight blockchain", "license": "Apache-2.0", From 6bbf5731ea6df30ca95747c9f7becb7c7fcdbd28 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 01:34:33 -0800 Subject: [PATCH 52/88] mn tx status, and receipts for the commands that submit midnight tx status asks the indexer what became of a transaction: its block, time, fee in DUST and result. The indexer lists only finalized transactions, so found means final; otherwise the state is notFound. --wait polls up to --timeout. MCP tool midnight_tx_status, read-only. It lives in the chain package. transfer, airdrop, dust register, swap take and swap cancel now wait up to 60 s for the indexer and add a receipt (block, fee, result) to their --json output and text; when the indexer lags, receipt is null and receiptMissing says why. The transaction is submitted either way. Asked by Midnight City for swap receipts. --- CHANGELOG.md | 5 + README.md | 1 + packages/chain/src/commands/chain.guidance.ts | 3 + packages/chain/src/commands/tx.definition.ts | 105 +++++++++ packages/chain/src/commands/tx.ts | 60 +++++ packages/chain/src/lib/tx-receipt.ts | 61 +++++ packages/chain/src/lib/tx-status.ts | 116 ++++++++++ scripts/check-layering.mjs | 5 +- src/__tests__/agent-guidance.test.ts | 6 +- src/__tests__/command-registry.test.ts | 3 + src/__tests__/help.test.ts | 5 +- src/__tests__/sdk-free-base.test.ts | 2 +- src/__tests__/tx-status.test.ts | 217 ++++++++++++++++++ src/commands/airdrop.definition.ts | 4 +- src/commands/airdrop.ts | 11 +- src/commands/dust.definition.ts | 4 +- src/commands/dust.ts | 11 +- src/commands/swap.definition.ts | 4 +- src/commands/swap.ts | 16 +- src/commands/transfer.definition.ts | 4 +- src/commands/transfer.ts | 11 +- src/lib/installed-commands.ts | 3 +- src/ui/receipt.ts | 17 ++ 23 files changed, 655 insertions(+), 19 deletions(-) create mode 100644 packages/chain/src/commands/tx.definition.ts create mode 100644 packages/chain/src/commands/tx.ts create mode 100644 packages/chain/src/lib/tx-receipt.ts create mode 100644 packages/chain/src/lib/tx-status.ts create mode 100644 src/__tests__/tx-status.test.ts create mode 100644 src/ui/receipt.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ed27b93a..77d5087b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to midnight-wallet-cli will be documented in this file. ## [Unreleased] +### Added + +- **`midnight tx status `: what became of a transaction**, from the indexer: its block (height, hash, time), the fee it paid in DUST (exact, and in specks), and its result (`SUCCESS`, `PARTIAL_SUCCESS` with each segment, or `FAILURE`). It takes the transaction's hash or any of its identifiers, which is what mn prints as `txHash` after a submit. The indexer lists only finalized transactions, so one it has is final; one it doesn't have is reported as `notFound` (not on chain yet, dropped, or never sent). `--wait` asks until it is listed, up to `--timeout` seconds (120 by default). MCP tool `midnight_tx_status`, read-only. +- **Receipts in the results of the commands that submit.** `transfer`, `airdrop`, `dust register`, `swap take` and `swap cancel` wait up to 60 s for the indexer to list their transaction and add a `receipt` to their `--json` output (block, fee and result, as `tx status` gives them) and its block and fee to their text. If the indexer has not listed it by then, `receipt` is null and `receiptMissing` says why; the transaction is submitted either way. + ## [0.6.0-rc.11] - 2026-11-02 ### Added diff --git a/README.md b/README.md index 51a5a903..1d6ffd38 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ Install the prerelease with npm (or run it with `npx`). It ships an `npm-shrinkw | `midnight dev [path]` | Iteration loop for Compact contract development (localnet + compile-on-save + one-key deploy) | | `midnight contract [options]` | Inspect, deploy, call, and query Midnight smart contracts | | `midnight swap [options]` | Private swaps of shielded tokens, through offer files (experimental) | +| `midnight tx status [options]` | What became of a transaction: its block, time, fee and result | | `midnight grant [options]` | This wallet's account, and the grants that let an agent spend from it (experimental) | | `midnight localnet ` | Manage a local Midnight network via Docker Compose (up is refused on this ledger-9 build) | | `midnight help [command]` | Show usage for all commands or a specific command | diff --git a/packages/chain/src/commands/chain.guidance.ts b/packages/chain/src/commands/chain.guidance.ts index 3abf6b0e..bd66114b 100644 --- a/packages/chain/src/commands/chain.guidance.ts +++ b/packages/chain/src/commands/chain.guidance.ts @@ -37,4 +37,7 @@ export const chainGuidance: PackageGuidance = { `, }, ], + toolsTable: [ + { tool: 'midnight_tx_status', group: 'transactions', order: 50, description: ['What became of a transaction: block, fee, result'] }, + ], }; diff --git a/packages/chain/src/commands/tx.definition.ts b/packages/chain/src/commands/tx.definition.ts new file mode 100644 index 00000000..d9cbdb42 --- /dev/null +++ b/packages/chain/src/commands/tx.definition.ts @@ -0,0 +1,105 @@ +// The `tx` command, described once. + +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; + +export const txDefinition: CommandDefinition = { + name: 'tx', + order: 167, + subcommands: ['status'], + flags: [ + { + name: 'wait', + takesValue: false, + help: ['--wait Wait until the transaction is on chain, up to --timeout'], + agent: { type: 'boolean', description: 'Wait until the transaction is on chain, up to timeout' }, + }, + { + name: 'timeout', + takesValue: true, + help: ['--timeout How long --wait waits (default: 120)'], + agent: { type: 'string', description: 'Seconds to wait (default 120)' }, + }, + { + name: 'network', + takesValue: true, + help: ['--network Network (default: the selected one)'], + agent: { ...NETWORK_PARAM, description: 'Network (default: the selected one)' }, + }, + { + name: 'node', + takesValue: true, + help: ['--node Node RPC endpoint (accepted like every command\'s; tx reads the indexer only)'], + agent: ENDPOINT_PARAMS.node, + }, + { + name: 'indexer-ws', + takesValue: true, + help: ['--indexer-ws Indexer WebSocket endpoint'], + agent: ENDPOINT_PARAMS['indexer-ws'], + }, + { + name: 'proof-server', + takesValue: true, + help: ['--proof-server Proof server endpoint (accepted like every command\'s; unused)'], + agent: ENDPOINT_PARAMS['proof-server'], + }, + ], + help: { + description: 'What became of a transaction: its block, time, fee and result', + usage: 'midnight tx status [options]', + flags: [ + 'status A transaction by its hash (64 hex characters) or an identifier', + ' (66; the txHash mn prints after a submit). Found means final;', + ' not found means not on chain yet, dropped, or never sent', + { flag: 'wait' }, + { flag: 'timeout' }, + { flag: 'network' }, + { flag: 'node' }, + { flag: 'indexer-ws' }, + { flag: 'proof-server' }, + '--json Output structured JSON', + ], + examples: [ + 'midnight tx status 00408d0e…559086', + 'midnight tx status 00408d0e…559086 --wait --timeout 60 --json', + ], + jsonFields: { + subcommand: 'The tx subcommand that ran', + network: 'Network name', + transaction: 'The hash or identifier asked about', + state: '"final" (in a finalized block) or "notFound"', + kind: '"regular" or "system" (final)', + hash: 'The transaction\'s hash (final)', + identifiers: 'The transaction\'s identifiers (final, regular)', + result: '"SUCCESS", "PARTIAL_SUCCESS" or "FAILURE" (final, regular)', + segments: 'Each segment\'s success, for a partial success', + fee: 'The fee paid, in DUST, exact (final, regular; a failed transaction pays it too)', + feeSpecks: 'The fee paid, in specks (final, regular)', + blockHeight: 'The block\'s height (final)', + blockHash: 'The block\'s hash (final)', + blockTime: 'The block\'s time, ISO 8601 (final)', + }, + }, + intro: { brief: 'What became of a transaction', order: 12.6 }, + needsWalletSdk: false, + shell: {}, + load: () => import('./tx.ts'), + mcp: { + tools: [ + { + name: 'midnight_tx_status', + description: 'What became of a transaction, by its hash or identifier (the txHash a submit returns): its block, time, fee in DUST and result. Found means final; notFound means not on chain yet, dropped, or never sent.', + annotations: { readOnlyHint: true, openWorldHint: true }, + params: [ + { name: 'transaction', schema: { type: 'string', description: 'The transaction\'s hash (64 hex) or identifier (66 hex)' } }, + { flag: 'wait' }, + { flag: 'timeout' }, + { flag: 'network' }, + ], + required: ['transaction'], + argv: { subcommand: 'status', positionals: ['transaction'], flags: 'rest' }, + order: 45, + }, + ], + }, +}; diff --git a/packages/chain/src/commands/tx.ts b/packages/chain/src/commands/tx.ts new file mode 100644 index 00000000..3a9131a3 --- /dev/null +++ b/packages/chain/src/commands/tx.ts @@ -0,0 +1,60 @@ +// tx command: what became of a transaction, from the indexer +// Usage: midnight tx status [--wait [--timeout ]] [--network ] [--json] + +import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { header, keyValue, formatDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { fetchTransactionStatus, parseTxReference, waitForTransactionStatus } from '../lib/tx-status.ts'; +import { transactionStatusJson } from '../lib/tx-receipt.ts'; + +const DEFAULT_TIMEOUT_S = 120; + +function timeoutMsOf(args: ParsedArgs): number { + const raw = getFlag(args, 'timeout'); + if (raw === undefined) return DEFAULT_TIMEOUT_S * 1000; + if (!hasFlag(args, 'wait')) throw new UsageError('--timeout is how long --wait waits; give --wait with it'); + if (!/^\d+$/.test(raw) || Number(raw) === 0) throw new UsageError(`--timeout must be a whole number of seconds, 1 or more (got "${raw}")`); + return Number(raw) * 1000; +} + +export default async function txCommand(args: ParsedArgs, ctx: CallContext): Promise { + if (args.subcommand !== 'status') throw new UsageError(`Unknown tx subcommand: ${args.subcommand ?? '(none)'}. Use status.`); + const given = args.positionals[0]; + if (given === undefined) throw new UsageError('tx status needs a transaction hash or identifier: midnight tx status '); + const ref = parseTxReference(given); + const timeoutMs = timeoutMsOf(args); + const jsonMode = hasFlag(args, 'json'); + const { name: network, config } = resolveNetwork({ args }); + + const wait = hasFlag(args, 'wait'); + const spinner = jsonMode ? ctx.progress.silent() : ctx.progress.start(wait ? 'Waiting for the indexer to list it...' : 'Asking the indexer...'); + const status = wait + ? await waitForTransactionStatus(config.indexer, ref, timeoutMs, ctx.signal) + : await fetchTransactionStatus(config.indexer, ref, ctx.signal); + spinner.stop(status.state === 'final' ? 'Final' : 'Not found'); + + if (jsonMode) { + ctx.output.result({ subcommand: 'status', network, transaction: given, ...transactionStatusJson(status) }); + return; + } + ctx.output.stdout((status.state === 'final' ? (status.result ?? 'final') : 'notFound') + '\n'); + ctx.output.stderr('\n' + header('Transaction') + '\n\n'); + ctx.output.stderr(keyValue('Network', network) + '\n'); + if (status.state === 'notFound') { + ctx.output.stderr(keyValue('State', 'not found') + '\n\n'); + ctx.output.stderr(dim(' The indexer lists only finalized transactions: this one is not on chain yet, was dropped, or was never sent.') + '\n\n'); + return; + } + ctx.output.stderr(keyValue('State', 'final') + '\n'); + ctx.output.stderr(keyValue('Hash', status.hash) + '\n'); + if (status.result !== undefined) ctx.output.stderr(keyValue('Result', status.result) + '\n'); + if (status.segments !== undefined) { + ctx.output.stderr(keyValue('Segments', status.segments.map((s) => `${s.id}: ${s.success ? 'success' : 'failure'}`).join(', ')) + '\n'); + } + if (status.feeSpecks !== undefined) ctx.output.stderr(keyValue('Fee', formatDust(status.feeSpecks)) + '\n'); + ctx.output.stderr(keyValue('Block', `${status.block.height} (${status.block.hash})`) + '\n'); + ctx.output.stderr(keyValue('Time', status.block.time.toISOString()) + '\n\n'); +} diff --git a/packages/chain/src/lib/tx-receipt.ts b/packages/chain/src/lib/tx-receipt.ts new file mode 100644 index 00000000..cf6bdb77 --- /dev/null +++ b/packages/chain/src/lib/tx-receipt.ts @@ -0,0 +1,61 @@ +// A submitted transaction's receipt: its block, time, fee and result, once the +// indexer lists it. mn's submits return when the node has finalized the +// transaction; the indexer may list it a few seconds later. + +import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { IndexerQueryError } from './indexer-graphql.ts'; +import { type FinalTransaction, type TransactionStatus, parseTxReference, waitForTransactionStatus } from './tx-status.ts'; + +/** How long a command that submitted waits for the indexer to list its transaction. */ +export const RECEIPT_WAIT_MS = 60_000; + +/** What a command that submitted reports about its transaction. */ +export type Receipt = + | { readonly listed: true; readonly transaction: FinalTransaction } + | { readonly listed: false; readonly reason: string }; + +/** + * The receipt of a transaction this call submitted (`txId`, its hash or + * identifier). Never throws: the transaction is submitted whatever the indexer + * says, so a lagging or unreachable indexer, or the call's cancellation, gives + * a receipt that says why it is missing. + */ +export async function receiptOf(indexerHttpUrl: string, txId: string, signal?: AbortSignal, waitMs: number = RECEIPT_WAIT_MS): Promise { + try { + const status = await waitForTransactionStatus(indexerHttpUrl, parseTxReference(txId), waitMs, signal); + if (status.state === 'final') return { listed: true, transaction: status }; + return { listed: false, reason: `the indexer has not listed it after ${Math.round(waitMs / 1000)} s` }; + } catch (err) { + if (err instanceof CancelledError) return { listed: false, reason: 'cancelled while waiting for the indexer' }; + if (err instanceof IndexerQueryError) return { listed: false, reason: `the indexer did not answer: ${err.message}` }; + throw err; + } +} + +/** A final transaction's fields, as `--json` output carries them. */ +export function finalTransactionJson(tx: FinalTransaction): Record { + return { + kind: tx.kind, + hash: tx.hash, + ...(tx.kind === 'regular' ? { identifiers: tx.identifiers } : {}), + ...(tx.result === undefined ? {} : { result: tx.result }), + ...(tx.segments === undefined ? {} : { segments: tx.segments }), + ...(tx.feeSpecks === undefined ? {} : { fee: toDust(tx.feeSpecks), feeSpecks: tx.feeSpecks.toString() }), + blockHeight: tx.block.height, + blockHash: tx.block.hash, + blockTime: tx.block.time.toISOString(), + }; +} + +/** A status as `--json` output carries it. */ +export function transactionStatusJson(status: TransactionStatus): Record { + return status.state === 'final' ? { state: 'final', ...finalTransactionJson(status) } : { state: 'notFound' }; +} + +/** A receipt as the `receipt` field of a submitting command's `--json` output: the transaction, or null with why. */ +export function receiptJson(receipt: Receipt): Record { + return receipt.listed + ? { receipt: finalTransactionJson(receipt.transaction) } + : { receipt: null, receiptMissing: receipt.reason }; +} diff --git a/packages/chain/src/lib/tx-status.ts b/packages/chain/src/lib/tx-status.ts new file mode 100644 index 00000000..32785eae --- /dev/null +++ b/packages/chain/src/lib/tx-status.ts @@ -0,0 +1,116 @@ +// What became of a transaction, from the indexer. The indexer takes in only +// finalized blocks, so a transaction it has is final; one it doesn't have may +// still be on its way, may have been dropped, or may never have existed, and +// the indexer can't tell which. +// +// A transaction is found by its hash (32 bytes) or by one of its identifiers +// (33 bytes): what mn reports as a submitted transaction's `txHash` is the +// wallet SDK's identifier. + +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { queryIndexer } from './indexer-graphql.ts'; + +const QUERY_TIMEOUT_MS = 10_000; +const POLL_INTERVAL_MS = 2_000; + +/** How a transaction was looked up: by its hash or by one of its identifiers. */ +export type TxReference = { hash: string } | { identifier: string }; + +/** A transaction's result, as the ledger applied it. A system transaction has none. */ +export type TxResultStatus = 'SUCCESS' | 'PARTIAL_SUCCESS' | 'FAILURE'; + +/** A transaction the indexer has: in a finalized block. */ +export interface FinalTransaction { + readonly state: 'final'; + readonly kind: 'regular' | 'system'; + readonly hash: string; + readonly identifiers: readonly string[]; + /** Regular transactions only. */ + readonly result?: TxResultStatus; + /** Each segment's success, for a partial success (segment 0 is the guaranteed section). */ + readonly segments?: ReadonlyArray<{ id: number; success: boolean }>; + /** The fee paid, in specks (regular transactions only; a failed one pays it too). */ + readonly feeSpecks?: bigint; + readonly block: { readonly height: number; readonly hash: string; readonly time: Date }; +} + +/** A transaction the indexer doesn't have. */ +export interface UnknownTransaction { + readonly state: 'notFound'; +} + +export type TransactionStatus = FinalTransaction | UnknownTransaction; + +const HEX = /^[0-9a-f]+$/; + +/** + * Read a transaction reference given as text: 64 hex characters are a hash, 66 + * an identifier, with or without `0x`. Throws UsageError for anything else. + */ +export function parseTxReference(text: string): TxReference { + const hex = text.trim().toLowerCase().replace(/^0x/, ''); + if (HEX.test(hex) && hex.length === 64) return { hash: hex }; + if (HEX.test(hex) && hex.length === 66) return { identifier: hex }; + throw new UsageError(`"${text}" is not a transaction hash (64 hex characters) or identifier (66 hex characters)`); +} + +const TX_QUERY = `query ($offset: TransactionOffset!) { + transactions(offset: $offset) { + __typename + hash + block { height hash timestamp } + ... on RegularTransaction { identifiers fee transactionResult { status segments { id success } } } + } +}`; + +interface RawTransaction { + __typename: string; + hash: string; + block: { height: number; hash: string; timestamp: number }; + identifiers?: string[]; + fee?: string; + transactionResult?: { status: TxResultStatus; segments?: Array<{ id: number; success: boolean }> | null }; +} + +/** What the indexer knows of a transaction now. Throws IndexerQueryError when it can't answer. */ +export async function fetchTransactionStatus(indexerHttpUrl: string, ref: TxReference, signal?: AbortSignal): Promise { + const data = await queryIndexer<{ transactions: RawTransaction[] }>(indexerHttpUrl, TX_QUERY, { offset: ref }, QUERY_TIMEOUT_MS, signal); + // A transaction is applied once; the first is the one that counts. + const tx = data.transactions[0]; + if (tx === undefined) return { state: 'notFound' }; + const block = { height: tx.block.height, hash: tx.block.hash, time: new Date(tx.block.timestamp) }; + if (tx.__typename !== 'RegularTransaction') return { state: 'final', kind: 'system', hash: tx.hash, identifiers: [], block }; + const result = tx.transactionResult?.status; + return { + state: 'final', + kind: 'regular', + hash: tx.hash, + identifiers: tx.identifiers ?? [], + ...(result === undefined ? {} : { result }), + ...(result === 'PARTIAL_SUCCESS' ? { segments: tx.transactionResult?.segments ?? [] } : {}), + ...(tx.fee === undefined ? {} : { feeSpecks: BigInt(tx.fee) }), + block, + }; +} + +/** + * Ask the indexer until it has the transaction or `timeoutMs` passes; the last + * answer either way. Throws CancelledError when `signal` cancels it, and + * IndexerQueryError when the indexer can't answer. + */ +export async function waitForTransactionStatus( + indexerHttpUrl: string, + ref: TxReference, + timeoutMs: number, + signal?: AbortSignal, + intervalMs: number = POLL_INTERVAL_MS, +): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const status = await fetchTransactionStatus(indexerHttpUrl, ref, signal); + const left = deadline - Date.now(); + if (status.state === 'final' || left <= 0) return status; + await sleep(Math.min(intervalMs, left), signal); + } +} diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index b65d14dc..e5dca5a6 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -46,12 +46,13 @@ const HOMES = [ ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], - ['chain', /^commands\/status(\.definition)?\.ts$/], - ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription|tx-segments|offer-liveness)\.ts$/], + ['chain', /^commands\/(status|tx)(\.definition)?\.ts$/], + ['chain', /^lib\/(node-rpc|chain-id|indexer-graphql|graphql-ws-subscription|event-tip|ledger-guard|node-ready|indexer-ready|proof-server-ready|chain-clock|endpoint-check|balance-subscription|tx-segments|tx-status|tx-receipt|offer-liveness)\.ts$/], ['wallet', /^commands\/(wallet|generate|address|genesis-address|info|balance|transfer|airdrop|dust|cache)(\.definition)?\.ts$/], ['wallet', /^lib\/(derivation|derive-address|wallet-config|seed-resolver|passphrase|facade|wallet-data-repository|transfer|transfer-request|sync-eta|wallet-can-pay|wallet-create|airdrop|wallet-protector|chain-caches|wallet-paths|fork-schedule)\.ts$/], ['wallet', /^lib\/(dust-[a-z-]+|shielded-[a-z-]+)\.ts$/], + ['wallet', /^ui\/receipt\.ts$/], ['contract', /^commands\/(contract|inspect-cost)(\.definition)?\.ts$/], ['contract', /^lib\/contract\//], diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index 7897d0a2..df32bdf9 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -207,7 +207,7 @@ describe('the texts, assembled from the installed packages', () => { const shown = [...section.matchAll(/^ {2}(midnight_\w+)/gm)].map((m) => m[1]); expect([...shown].sort()).toStrictEqual([...listed].sort()); expect(section.startsWith(` (${listed.length})\n`)).toBe(true); - expect(listed.length).toBe(43); + expect(listed.length).toBe(44); }); it('lists the grant tools under Grants (experimental), last', () => { @@ -225,7 +225,7 @@ describe('the texts, assembled from the installed packages', () => { const section = toolsSection(agentManual(registry)); expect(section).not.toContain('Grants (experimental)'); expect(section).toContain(' Other\n midnight_grant_status The wallet\'s account: address, owner key, what it holds, number of grants (see skill).'); - expect(section.startsWith(' (43)\n')).toBe(true); + expect(section.startsWith(' (44)\n')).toBe(true); }); it('leaves out a package that is not installed: its sections, its rows and its tools', () => { @@ -234,7 +234,7 @@ describe('the texts, assembled from the installed packages', () => { expect(manual).not.toContain('GRANTS (experimental)'); expect(manual).not.toContain('NO_ACCOUNT'); expect(manual).not.toContain('midnight_grant_'); - expect(toolsSection(manual).startsWith(' (35)\n')).toBe(true); + expect(toolsSection(manual).startsWith(' (36)\n')).toBe(true); expect(skillCore(registry)).not.toContain('midnight_grant_'); const full = skillFull(registry); expect(full).not.toContain('allowance (experimental)'); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index da9460e9..0e3150f5 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -52,6 +52,8 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => 'help': {}, 'info': {}, 'inspect-cost': {}, 'localnet': {}, 'manual': {}, 'serve': {}, // Added since the registry: swap, which pays through the payer as grant does. 'swap': { payer: true }, + // And tx, which reads the indexer only. + 'tx': {}, 'status': { unavailable: STATUS_REFUSAL }, 'test': {}, 'transfer': {}, 'wallet': { protectors: true }, }; @@ -385,6 +387,7 @@ describe('the MCP tools, generated from the registry', () => { ['midnight_swap_take', { file: 'offer.json', give: '10', 'give-token': 'aa', want: '7', 'want-token': 'bb', wallet: 'bob' }, args('swap', 'take', ['offer.json'], { give: '10', 'give-token': 'aa', want: '7', 'want-token': 'bb', wallet: 'bob' })], ['midnight_swap_cancel', { id: '3fa1c0de' }, args('swap', 'cancel', ['3fa1c0de'], {})], ['midnight_swap_list', { network: 'undeployed' }, args('swap', 'list', [], { network: 'undeployed' })], + ['midnight_tx_status', { transaction: 'ab12', wait: true, timeout: '30' }, args('tx', 'status', ['ab12'], { wait: true, timeout: '30' })], ['midnight_grant_issue', { link: 'L', 'per-call': '2' }, args('grant', 'issue', ['L'], { 'per-call': '2', yes: true })], ['midnight_grant_revoke', { grant: '3' }, args('grant', 'revoke', ['3'], {})], ['midnight_grant_revoke_all', {}, args('grant', 'revoke-all', [], {})], diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index 8bea4cc1..5c894e9a 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -158,14 +158,15 @@ describe('help — the lists come from the registry', () => { Object.defineProperty(process.stderr, 'isTTY', { value: undefined, configurable: true }); await cliCall(helpCommand, parseArgs(['help'])); const lines = introLines(io.stderr()); - expect(lines.slice(9, 14)).toStrictEqual([ + expect(lines.slice(9, 15)).toStrictEqual([ 'contract Inspect, deploy, call contracts', 'dev Contract dev loop (watch + deploy)', 'grant Grants that let agents spend', 'swap Private swaps through offer files', + 'tx What became of a transaction', 'config Manage CLI config', ]); - expect(lines).toHaveLength(20); + expect(lines).toHaveLength(21); }); it('the TTY intro lists grant after dev, with its brief', async () => { diff --git a/src/__tests__/sdk-free-base.test.ts b/src/__tests__/sdk-free-base.test.ts index 66f218bc..58b08fb5 100644 --- a/src/__tests__/sdk-free-base.test.ts +++ b/src/__tests__/sdk-free-base.test.ts @@ -71,7 +71,7 @@ describe('the SDK-free base', () => { cwd: ROOT, encoding: 'utf8', timeout: 120_000, env: { ...process.env, HOME: dir }, }); expect(run.status, run.stderr).toBe(0); - expect(JSON.parse(run.stdout.trim().split('\n').at(-1)!)).toEqual([22, 42]); + expect(JSON.parse(run.stdout.trim().split('\n').at(-1)!)).toEqual([23, 43]); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/src/__tests__/tx-status.test.ts b/src/__tests__/tx-status.test.ts new file mode 100644 index 00000000..5885a976 --- /dev/null +++ b/src/__tests__/tx-status.test.ts @@ -0,0 +1,217 @@ +// What became of a transaction, from the indexer: the lookup, the wait, the +// receipt a submitting command reports, and `mn tx status`. The answers below +// have the shape stagenet's indexer gave on 2026-11-03 for the City's first +// swap (a 4.4 indexer; 4.3's transaction fields are the same). + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { CancelledError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { IndexerQueryError } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; +import { fetchTransactionStatus, parseTxReference, waitForTransactionStatus } from '@kuiralabs/midnight-chain/lib/tx-status'; +import { receiptJson, receiptOf, transactionStatusJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import txCommand from '@kuiralabs/midnight-chain/commands/tx'; +import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { cliCall } from './helpers/cli-call.ts'; + +const IDENTIFIER = '00408d0e7f195ae3a57b908f10513f2200386533960fcdc3fb152076dd84559086'; +const HASH = '1dc5749135a08df5fb95560e1ef1ff3fea6febdd8b263dbd2b371e2f9cb178f8'; +const BLOCK = { height: 1146592, hash: 'd3d3af4c0a35110377d12c1296274603fa75583b274191c8b7063bc913db2f75', timestamp: 1793696118000 }; + +const answer = (transactions: unknown[]) => JSON.stringify({ data: { transactions } }); +const regular = (status: string, segments: unknown = null) => ({ + __typename: 'RegularTransaction', + hash: HASH, + block: BLOCK, + identifiers: [IDENTIFIER], + fee: '845170285714286', + transactionResult: { status, segments }, +}); + +let indexer: LocalIndexer | undefined; +afterEach(async () => { await indexer?.close(); indexer = undefined; }); + +describe('parseTxReference', () => { + it('reads 64 hex characters as a hash and 66 as an identifier, with or without 0x, in any case', () => { + expect(parseTxReference(HASH)).toEqual({ hash: HASH }); + expect(parseTxReference(IDENTIFIER)).toEqual({ identifier: IDENTIFIER }); + expect(parseTxReference(`0x${HASH.toUpperCase()}`)).toEqual({ hash: HASH }); + }); + + it.each(['', 'xyz', HASH.slice(1), `${IDENTIFIER}00`, `${HASH.slice(0, 63)}g`])('refuses %j as a usage error', (text) => { + expect(() => parseTxReference(text)).toThrow(UsageError); + }); +}); + +describe('fetchTransactionStatus', () => { + it('finds a transaction by its identifier: final, with its result, fee in specks and block', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const status = await fetchTransactionStatus(indexer.url, { identifier: IDENTIFIER }); + expect(status).toEqual({ + state: 'final', kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', feeSpecks: 845170285714286n, + block: { height: BLOCK.height, hash: BLOCK.hash, time: new Date('2026-11-03T08:55:18.000Z') }, + }); + expect(indexer.requests[0]!.variables).toEqual({ offset: { identifier: IDENTIFIER } }); + }); + + it('asks by hash when given a hash', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + await fetchTransactionStatus(indexer.url, { hash: HASH }); + expect(indexer.requests[0]!.variables).toEqual({ offset: { hash: HASH } }); + }); + + it('lists the segments of a partial success, and only of one', async () => { + indexer = await startLocalIndexer(() => answer([regular('PARTIAL_SUCCESS', [{ id: 0, success: true }, { id: 1, success: false }])])); + const status = await fetchTransactionStatus(indexer.url, { hash: HASH }); + expect(status).toMatchObject({ result: 'PARTIAL_SUCCESS', segments: [{ id: 0, success: true }, { id: 1, success: false }] }); + }); + + it('reports a failed transaction as final, with the fee it paid', async () => { + indexer = await startLocalIndexer(() => answer([regular('FAILURE')])); + expect(await fetchTransactionStatus(indexer.url, { hash: HASH })).toMatchObject({ state: 'final', result: 'FAILURE', feeSpecks: 845170285714286n }); + }); + + it('reports a system transaction with its block, and no result or fee', async () => { + indexer = await startLocalIndexer(() => answer([{ __typename: 'SystemTransaction', hash: HASH, block: BLOCK }])); + const status = await fetchTransactionStatus(indexer.url, { hash: HASH }); + expect(status).toEqual({ state: 'final', kind: 'system', hash: HASH, identifiers: [], block: { height: BLOCK.height, hash: BLOCK.hash, time: new Date(BLOCK.timestamp) } }); + }); + + it('reports a transaction the indexer does not have as not found', async () => { + indexer = await startLocalIndexer(() => answer([])); + expect(await fetchTransactionStatus(indexer.url, { identifier: IDENTIFIER })).toEqual({ state: 'notFound' }); + }); + + it('throws IndexerQueryError when the indexer refuses the query', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'invalid transaction hash' }] })); + await expect(fetchTransactionStatus(indexer.url, { hash: HASH })).rejects.toThrow(IndexerQueryError); + }); +}); + +describe('waitForTransactionStatus', () => { + it('asks until the indexer lists the transaction', async () => { + let asked = 0; + indexer = await startLocalIndexer(() => (++asked < 3 ? answer([]) : answer([regular('SUCCESS')]))); + const status = await waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 5_000, undefined, 20); + expect(status.state).toBe('final'); + expect(asked).toBe(3); + }); + + it('gives not found once the timeout passes', async () => { + indexer = await startLocalIndexer(() => answer([])); + const started = Date.now(); + expect(await waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 150, undefined, 20)).toEqual({ state: 'notFound' }); + expect(Date.now() - started).toBeLessThan(2_000); + expect(indexer.requests.length).toBeGreaterThan(1); + }); + + it('stops with CancelledError when its call is cancelled', async () => { + indexer = await startLocalIndexer(() => answer([])); + const controller = new AbortController(); + setTimeout(() => controller.abort(), 50); + await expect(waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 10_000, controller.signal, 20)).rejects.toThrow(CancelledError); + }); +}); + +describe('receiptOf', () => { + it('gives the transaction once listed, and its JSON with the fee in DUST exactly', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const receipt = await receiptOf(indexer.url, IDENTIFIER); + expect(receiptJson(receipt)).toEqual({ + receipt: { + kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', fee: '0.845170285714286', feeSpecks: '845170285714286', + blockHeight: BLOCK.height, blockHash: BLOCK.hash, blockTime: '2026-11-03T08:55:18.000Z', + }, + }); + }); + + it('says the indexer has not listed it yet, never throwing', async () => { + indexer = await startLocalIndexer(() => answer([])); + expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER, undefined, 100))).toEqual({ receipt: null, receiptMissing: 'the indexer has not listed it after 0 s' }); + }); + + it('says the indexer did not answer, never throwing', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'overloaded' }] })); + expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER))).toEqual({ receipt: null, receiptMissing: 'the indexer did not answer: overloaded' }); + }); + + it('says it was cancelled, never throwing: the transaction is submitted already', async () => { + indexer = await startLocalIndexer(() => answer([])); + const controller = new AbortController(); + setTimeout(() => controller.abort(), 50); + expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER, controller.signal))).toEqual({ receipt: null, receiptMissing: 'cancelled while waiting for the indexer' }); + }); +}); + +describe('transactionStatusJson', () => { + it('gives not found as its state alone', () => { + expect(transactionStatusJson({ state: 'notFound' })).toEqual({ state: 'notFound' }); + }); +}); + +describe('mn tx status', () => { + let io: CapturedOutput; + let home: string; + let savedHome: string | undefined; + beforeEach(() => { + savedHome = process.env.HOME; + home = mkdtempSync(join(tmpdir(), 'mn-tx-status-')); + process.env.HOME = home; + io = captureOutput(); + }); + afterEach(() => { + io.restore(); + process.env.HOME = savedHome; + rmSync(home, { recursive: true, force: true }); + }); + const wsOf = (url: string) => url.replace('http://', 'ws://') + '/ws'; + const run = (...argv: string[]) => cliCall(txCommand, parseArgs(['tx', ...argv, '--network', 'preview', '--indexer-ws', wsOf(indexer!.url)])); + + it('prints the transaction as one JSON result', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + await run('status', IDENTIFIER, '--json'); + expect(JSON.parse(io.stdout())).toEqual({ + subcommand: 'status', network: 'preview', transaction: IDENTIFIER, state: 'final', + kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', fee: '0.845170285714286', feeSpecks: '845170285714286', + blockHeight: BLOCK.height, blockHash: BLOCK.hash, blockTime: '2026-11-03T08:55:18.000Z', + }); + }); + + it('prints the result on stdout and the details on stderr', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + await run('status', IDENTIFIER); + expect(io.stdout()).toBe('SUCCESS\n'); + expect(io.stderr()).toContain('0.845170285714286 DUST'); + expect(io.stderr()).toContain(String(BLOCK.height)); + }); + + it('reports not found as a result, saying what it can mean', async () => { + indexer = await startLocalIndexer(() => answer([])); + await run('status', IDENTIFIER); + expect(io.stdout()).toBe('notFound\n'); + expect(io.stderr()).toContain('not on chain yet, was dropped, or was never sent'); + }); + + it('with --wait, asks until it is listed', async () => { + let asked = 0; + indexer = await startLocalIndexer(() => (++asked < 2 ? answer([]) : answer([regular('SUCCESS')]))); + await run('status', IDENTIFIER, '--wait', '--timeout', '30', '--json'); + expect(JSON.parse(io.stdout()).state).toBe('final'); + expect(asked).toBe(2); + }); + + it.each([ + [['status'], 'needs a transaction hash or identifier'], + [['status', 'xyz'], 'is not a transaction hash'], + [['status', IDENTIFIER, '--timeout', '5'], 'give --wait with it'], + [['status', IDENTIFIER, '--wait', '--timeout', '0'], 'whole number of seconds'], + [['list'], 'Unknown tx subcommand'], + ])('refuses %j as a usage error', async (argv, message) => { + indexer = await startLocalIndexer(() => answer([])); + await expect(run(...argv)).rejects.toThrow(message); + expect(indexer.requests).toHaveLength(0); + }); +}); diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index c68366aa..f925cc4a 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -59,7 +59,9 @@ export const airdropDefinition: CommandDefinition = { 'midnight airdrop 100 --shielded --wallet mn_shield-addr_undeployed1...', ], jsonFields: { - txHash: 'Transaction hash', + txHash: 'The transaction\'s identifier (midnight tx status takes it)', + receipt: 'The transaction once the indexer lists it: blockHeight, blockHash, blockTime, fee (DUST, exact), feeSpecks, result; null when it has not within 60 s', + receiptMissing: 'Why receipt is null; check later with midnight tx status ', amount: 'Amount airdropped (NIGHT string)', recipient: 'Recipient address (unshielded airdrop)', shieldedAddress: 'Shielded address (--shielded airdrop)', diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 98427c89..5eb8a14d 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -20,6 +20,8 @@ import { parseAmount, nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amou import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptText } from '../ui/receipt.ts'; export default async function airdropCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); @@ -207,6 +209,8 @@ async function unshieldedAirdrop( }, }); + spinner.update('Waiting for the indexer to list it...'); + const receipt = await receiptOf(networkConfig.indexer, result.txHash, ctx.signal); spinner.stop('Transaction submitted'); if (hasFlag(args, 'json')) { @@ -215,6 +219,7 @@ async function unshieldedAirdrop( amount: amountNight, recipient: recipientAddress, network: networkName, + ...receiptJson(receipt), }); return; } @@ -225,6 +230,7 @@ async function unshieldedAirdrop( `Airdropped ${amountNight} NIGHT to your wallet`, result.txHash, ) + '\n'); + ctx.output.stderr(receiptText(receipt, result.txHash)); ctx.output.stderr('\n' + divider() + '\n'); ctx.output.stderr(dim(' Verify: midnight balance') + '\n'); ctx.output.stderr(dim(' Register dust: midnight dust register') + '\n'); @@ -292,14 +298,17 @@ async function shieldedAirdrop( onSyncDetail: (detail) => spinner.update(`Syncing genesis wallet... (waiting on: ${detail})`), }); + spinner.update('Waiting for the indexer to list it...'); + const receipt = await receiptOf(networkConfig.indexer, txHash, ctx.signal); spinner.stop('Transaction submitted'); if (hasFlag(args, 'json')) { - ctx.output.result({ txHash, amount: amountNight, shieldedAddress: userShieldedAddrStr, network: networkName, type: 'shielded' }); + ctx.output.result({ txHash, amount: amountNight, shieldedAddress: userShieldedAddrStr, network: networkName, type: 'shielded', ...receiptJson(receipt) }); return; } ctx.output.stdout(txHash + '\n'); ctx.output.stderr('\n' + successMessage(`Airdropped ${amountNight} shielded NIGHT to your wallet`, txHash) + '\n'); + ctx.output.stderr(receiptText(receipt, txHash)); ctx.output.stderr('\n' + divider() + '\n'); ctx.output.stderr(dim(' Verify: midnight balance --shielded') + '\n\n'); } catch (err) { diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index e9b741fe..7043a318 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -87,7 +87,9 @@ export const dustDefinition: CommandDefinition = { dustBalance: 'Dust balance (raw bigint string; status when registered, register, and export)', nightBalance: 'NIGHT balance (raw bigint string; status only when registered)', dustAvailable: 'Whether dust tokens are available (status only when registered)', - txHash: 'Registration transaction hash (register only, if submitted)', + txHash: 'The registration transaction\'s identifier (register only, if submitted; midnight tx status takes it)', + receipt: 'The transaction once the indexer lists it: blockHeight, blockHash, blockTime, fee (DUST, exact), feeSpecks, result; null when it has not within 60 s (register, if submitted)', + receiptMissing: 'Why receipt is null; check later with midnight tx status ', dustPublicKey: 'Dust public key hex the snapshot belongs to (export only)', offset: 'Last dust event id the snapshot covers, -1 if none (export only)', snapshot: 'Facade-restorable dust snapshot JSON — pass as the SDK dustSerializedState (export only)', diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 4ff2bd8b..09c0a54d 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -14,6 +14,8 @@ import { header, keyValue, divider, formatDust, successMessage, toDust } from '@ import { bold, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { type Receipt, receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptText } from '../ui/receipt.ts'; export default async function dustCommand(args: ParsedArgs, ctx: CallContext): Promise { const subcommand = args.subcommand; @@ -271,12 +273,18 @@ async function dustRegister( onSyncWarning: (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`), }); const dustBal = result.dustBalance; + let receipt: Receipt | undefined; + if (result.txHash) { + spinner.update('Waiting for the indexer to list it...'); + receipt = await receiptOf(networkConfig.indexer, result.txHash, ctx.signal); + } spinner.stop(result.alreadyAvailable ? 'Dust already available' : 'Dust registration complete'); if (jsonMode) { const json: Record = { subcommand: 'register', dustBalance: toDust(dustBal) }; if (result.txHash) json.txHash = result.txHash; + if (receipt) Object.assign(json, receiptJson(receipt)); ctx.output.result(json); return; } @@ -286,7 +294,8 @@ async function dustRegister( result.alreadyAvailable ? `Dust tokens already available: ${formatDust(dustBal)}` : `Dust tokens available: ${formatDust(dustBal)}`, - ) + '\n\n'); + ) + '\n'); + ctx.output.stderr((receipt && result.txHash ? receiptText(receipt, result.txHash) : '') + '\n'); } catch (err) { spinner.fail('Failed'); throw err; diff --git a/src/commands/swap.definition.ts b/src/commands/swap.definition.ts index 91adbc25..66690b96 100644 --- a/src/commands/swap.definition.ts +++ b/src/commands/swap.definition.ts @@ -131,7 +131,9 @@ export const swapDefinition: CommandDefinition = { expiresAt: 'When a taker using mn stops taking the offer (make, inspect)', live: 'Whether none of the offer\'s coins is spent yet (inspect)', expired: 'Whether the maker\'s expiry has passed (inspect)', - txHash: 'The swap\'s transaction (take), or the cancel\'s (cancel; null when the offer was taken already)', + txHash: 'The swap\'s transaction identifier (take), or the cancel\'s (cancel; null when the offer was taken already); midnight tx status takes it', + receipt: 'The transaction once the indexer lists it: blockHeight, blockHash, blockTime, fee (DUST, exact), feeSpecks, result; null when it has not within 60 s (take, and cancel when submitted)', + receiptMissing: 'Why receipt is null; check later with midnight tx status ', cancelled: 'Whether a cancel was submitted; false when the offer was taken already (cancel)', offers: 'The wallet\'s open offers, each with whether it is expired or taken (list)', }, diff --git a/src/commands/swap.ts b/src/commands/swap.ts index 16cf63c6..0e37679e 100644 --- a/src/commands/swap.ts +++ b/src/commands/swap.ts @@ -16,6 +16,8 @@ import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { resolveWalletPath, walletAddress } from '../lib/wallet-config.ts'; import { cancelOffer, listOffers, makeOffer, standingOf, takeOffer } from '../lib/swap/offers.ts'; import { prepareMake, prepareTake, readOfferArg } from '../lib/swap/request.ts'; +import { receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptText } from '../ui/receipt.ts'; const legJson = ({ token, amount }: SwapLeg) => ({ token, amount: amount.toString() }); const termsJson = ({ give, want }: SwapTerms) => ({ give: legJson(give), want: legJson(want) }); @@ -95,12 +97,15 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P try { const spinner = spinnerFor('Checking the offer, adding this half and proving the swap...'); const txHash = await takeOffer(session, offer, agreed, target.networkConfig, now, ctx.signal); + spinner.update('Waiting for the indexer to list it...'); + const receipt = await receiptOf(target.networkConfig.indexer, txHash, ctx.signal); spinner.stop('Swap submitted'); if (jsonMode) { - ctx.output.result({ subcommand: 'take', network: target.network, id: offer.envelope.id, txHash }); + ctx.output.result({ subcommand: 'take', network: target.network, id: offer.envelope.id, txHash, ...receiptJson(receipt) }); return; } ctx.output.stdout(txHash + '\n'); + ctx.output.stderr('\n' + receiptText(receipt, txHash)); ctx.output.stderr('\n' + dim(' Verify: midnight balance --shielded') + '\n\n'); } finally { await session.close(); @@ -117,13 +122,18 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P try { const spinner = spinnerFor('Spending the offer\'s coins back to this wallet...'); const outcome = await cancelOffer(session, target.networkConfig, address, id, ctx.signal); + if (outcome.txHash !== undefined) spinner.update('Waiting for the indexer to list it...'); + const receipt = outcome.txHash === undefined ? undefined : await receiptOf(target.networkConfig.indexer, outcome.txHash, ctx.signal); spinner.stop(outcome.txHash === undefined ? 'It was taken already' : 'Offer cancelled'); const offer = [...outcome.cancelled, ...outcome.alreadyTaken][0]!; if (jsonMode) { - ctx.output.result({ subcommand: 'cancel', network: target.network, id: offer.id, cancelled: outcome.txHash !== undefined, txHash: outcome.txHash ?? null }); + ctx.output.result({ subcommand: 'cancel', network: target.network, id: offer.id, cancelled: outcome.txHash !== undefined, txHash: outcome.txHash ?? null, ...(receipt === undefined ? {} : receiptJson(receipt)) }); return; } - if (outcome.txHash !== undefined) ctx.output.stdout(outcome.txHash + '\n'); + if (outcome.txHash !== undefined) { + ctx.output.stdout(outcome.txHash + '\n'); + if (receipt !== undefined) ctx.output.stderr('\n' + receiptText(receipt, outcome.txHash) + '\n'); + } else ctx.output.stderr('\n' + dim(` ${offer.id.slice(0, 16)}… was taken before it could be cancelled; it is closed.`) + '\n\n'); } finally { await session.close(); diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index ce7631e3..84300fc3 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -80,7 +80,9 @@ export const transferDefinition: CommandDefinition = { 'midnight transfer mn_shield-addr_undeployed1... 50 --shielded', ], jsonFields: { - txHash: 'Transaction hash', + txHash: 'The transaction\'s identifier (midnight tx status takes it)', + receipt: 'The transaction once the indexer lists it: blockHeight, blockHash, blockTime, fee (DUST, exact), feeSpecks, result; null when it has not within 60 s', + receiptMissing: 'Why receipt is null; check later with midnight tx status ', amount: 'Amount transferred (NIGHT string)', recipient: 'Recipient address (bech32m)', network: 'Network name', diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 7c3d9d14..3a4165a5 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -12,6 +12,8 @@ import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptText } from '../ui/receipt.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); @@ -84,6 +86,8 @@ async function unshieldedTransfer( }, }); + spinner.update('Waiting for the indexer to list it...'); + const receipt = await receiptOf(networkConfig.indexer, result.txHash, ctx.signal); spinner.stop('Transaction submitted'); if (hasFlag(args, 'json')) { @@ -92,6 +96,7 @@ async function unshieldedTransfer( amount: amountNight, recipient: recipientAddress, network: networkName, + ...receiptJson(receipt), }); return; } @@ -102,6 +107,7 @@ async function unshieldedTransfer( `Transferred ${amountNight} NIGHT`, result.txHash, ) + '\n'); + ctx.output.stderr(receiptText(receipt, result.txHash)); ctx.output.stderr('\n' + divider() + '\n'); ctx.output.stderr(dim(' Verify: midnight balance') + '\n\n'); } catch (err) { @@ -167,14 +173,17 @@ async function shieldedTransfer( onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), }); + spinner.update('Waiting for the indexer to list it...'); + const receipt = await receiptOf(networkConfig.indexer, txHash, ctx.signal); spinner.stop('Transaction submitted'); if (hasFlag(args, 'json')) { - ctx.output.result({ txHash, amount: amountNight, recipient: recipientAddress, network: networkName, type: 'shielded' }); + ctx.output.result({ txHash, amount: amountNight, recipient: recipientAddress, network: networkName, type: 'shielded', ...receiptJson(receipt) }); return; } ctx.output.stdout(txHash + '\n'); ctx.output.stderr('\n' + successMessage(`Transferred ${amountNight} shielded NIGHT`, txHash) + '\n'); + ctx.output.stderr(receiptText(receipt, txHash)); ctx.output.stderr('\n' + divider() + '\n'); ctx.output.stderr(dim(' Verify: midnight balance --shielded') + '\n\n'); } catch (err) { diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 4923987d..892498d1 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -27,6 +27,7 @@ import { grantDefinition } from '../commands/grant.definition.ts'; import { swapDefinition } from '../commands/swap.definition.ts'; import { localnetDefinition } from '../commands/localnet.definition.ts'; import { statusDefinition } from '@kuiralabs/midnight-chain/commands/status.definition'; +import { txDefinition } from '@kuiralabs/midnight-chain/commands/tx.definition'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; import { coreGuidance } from '@kuiralabs/midnight-cli-core/commands/core.guidance'; @@ -65,7 +66,7 @@ const GLOBAL_FLAGS_HELP: readonly GlobalFlagHelp[] = [ /** Every package, in the layering's order; the shell's own commands last, its guidance being the skeletons. */ export const installedCommands = createPackageRegistry([ { name: 'core', commands: [configDefinition], guidance: coreGuidance }, - { name: 'chain', commands: [statusDefinition], guidance: chainGuidance }, + { name: 'chain', commands: [statusDefinition, txDefinition], guidance: chainGuidance }, { name: 'wallet', commands: [walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition], diff --git a/src/ui/receipt.ts b/src/ui/receipt.ts new file mode 100644 index 00000000..e63ba2c5 --- /dev/null +++ b/src/ui/receipt.ts @@ -0,0 +1,17 @@ +// A submitted transaction's receipt, as a command shows it on stderr. + +import type { Receipt } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { keyValue, formatDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; + +/** The receipt's lines: block, fee and a result other than success; or why there is none yet. */ +export function receiptText(receipt: Receipt, txId: string): string { + if (!receipt.listed) { + return dim(` No receipt yet: ${receipt.reason}. Check with: midnight tx status ${txId}`) + '\n'; + } + const tx = receipt.transaction; + let text = keyValue('Block', `${tx.block.height} at ${tx.block.time.toISOString()}`) + '\n'; + if (tx.feeSpecks !== undefined) text += keyValue('Fee', formatDust(tx.feeSpecks)) + '\n'; + if (tx.result !== undefined && tx.result !== 'SUCCESS') text += keyValue('Result', tx.result) + '\n'; + return text; +} From e9bd29d39dee9ecf52ed66d8152f13a0445f19fc Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 01:44:33 -0800 Subject: [PATCH 53/88] API reports for the public packages (3A) scripts/api-report.mjs emits each public package's declarations in memory and writes api-report.md beside it: every module its exports map makes importable, with what it exports, without comments. The suite compares each report with the code, so a change to an export fails until the report is written again and shows in review. --- package.json | 1 + packages/chain/api-report.md | 266 +++++ packages/cli-core/api-report.md | 1680 ++++++++++++++++++++++++++++ packages/engine-beta/api-report.md | 581 ++++++++++ packages/engine-rc/api-report.md | 591 ++++++++++ scripts/api-report.d.mts | 7 + scripts/api-report.mjs | 120 ++ src/__tests__/api-report.test.ts | 13 + 8 files changed, 3259 insertions(+) create mode 100644 packages/chain/api-report.md create mode 100644 packages/cli-core/api-report.md create mode 100644 packages/engine-beta/api-report.md create mode 100644 packages/engine-rc/api-report.md create mode 100644 scripts/api-report.d.mts create mode 100644 scripts/api-report.mjs create mode 100644 src/__tests__/api-report.test.ts diff --git a/package.json b/package.json index e5f84664..611bc30e 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "test:beta": "vitest run src/__tests__/engine-beta", "test:live": "vitest run --config vitest.live.config.ts", "test:watch": "vitest", + "api-report": "node scripts/api-report.mjs write", "typecheck": "tsc --noEmit", "skill-docs": "tsx --conditions=midnight-cli-source scripts/write-skill-docs.ts", "readme-commands": "tsx --conditions=midnight-cli-source scripts/write-readme-commands.ts" diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md new file mode 100644 index 00000000..e4f284e1 --- /dev/null +++ b/packages/chain/api-report.md @@ -0,0 +1,266 @@ +# API report: @kuiralabs/midnight-chain + +Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-chain/commands/chain.guidance` + +```ts +import type { PackageGuidance } from "@kuiralabs/midnight-cli-core/lib/agent-guidance"; +export declare const chainGuidance: PackageGuidance; +``` + +## `@kuiralabs/midnight-chain/commands/status` + +```ts +import { type ParsedArgs } from "@kuiralabs/midnight-cli-core/lib/argv"; +import type { CallContext, CommandOutcome } from "@kuiralabs/midnight-cli-core/lib/call-context"; +export default function statusCommand(args: ParsedArgs, ctx: CallContext): Promise; +``` + +## `@kuiralabs/midnight-chain/commands/status.definition` + +```ts +import type { CommandDefinition } from "@kuiralabs/midnight-cli-core/lib/command-definition"; +export declare const statusDefinition: CommandDefinition; +``` + +## `@kuiralabs/midnight-chain/commands/tx` + +```ts +import { type ParsedArgs } from "@kuiralabs/midnight-cli-core/lib/argv"; +import type { CallContext } from "@kuiralabs/midnight-cli-core/lib/call-context"; +export default function txCommand(args: ParsedArgs, ctx: CallContext): Promise; +``` + +## `@kuiralabs/midnight-chain/commands/tx.definition` + +```ts +import { type CommandDefinition } from "@kuiralabs/midnight-cli-core/lib/command-definition"; +export declare const txDefinition: CommandDefinition; +``` + +## `@kuiralabs/midnight-chain/lib/balance-subscription` + +```ts +export type { BalanceSummary } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { BalanceSummary } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function checkBalance(address: string, indexerWS: string, onProgress?: (current: number, highest: number) => void, signal?: AbortSignal): Promise; +export declare function isNativeToken(tokenType: string): boolean; +``` + +## `@kuiralabs/midnight-chain/lib/chain-clock` + +```ts +export declare const CHAIN_CLOCK_TOLERANCE_MS: number; +export declare function fetchChainTime(indexerHttpUrl: string): Promise; +export declare class ChainClockBehindError extends Error { + readonly code = "CHAIN_CLOCK_BEHIND"; + constructor(chainTime: Date, now: Date); +} +export declare function assertChainClockCurrent(chainTime: Date, now: Date): void; +``` + +## `@kuiralabs/midnight-chain/lib/chain-id` + +```ts +export declare function getChainGenesisHash(nodeWsUrl: string, signal?: AbortSignal): Promise; +export declare function clearChainIdMemo(): void; +``` + +## `@kuiralabs/midnight-chain/lib/endpoint-check` + +```ts +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare function assertNetworkAnswers(network: Pick, request?: typeof fetch): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/event-tip` + +```ts +export type LedgerEventStream = "dust" | "zswap"; +export declare function fetchEventTip(indexerWS: string, stream: LedgerEventStream): Promise; +export declare function isStreamEmpty(indexerWS: string, stream: LedgerEventStream): Promise; +export declare function isCursorBeyondTip(lastAppliedEventId: number, tip: number | null): boolean; +``` + +## `@kuiralabs/midnight-chain/lib/graphql-ws-subscription` + +```ts +export type WsFinishReason = "caught-up" | "complete" | "idle" | "initial-silence" | "graceful-close" | "closed-early" | "timeout"; +export interface GraphqlWsSubscription { + query: string; + variables: Record; + onNext: (data: unknown) => boolean; + buildResult: (partial: boolean, reason: WsFinishReason) => TResult; + timeoutMs: number; + idleMs: number; + idleBeforeFirstEvent?: boolean; + initialSilenceMs?: number; + signal?: AbortSignal; +} +export declare function subscribeGraphqlWs(wsUrl: string, sub: GraphqlWsSubscription): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/indexer-graphql` + +```ts +export declare class IndexerQueryError extends Error { + constructor(reason: string); +} +export declare function queryIndexer(indexerHttpUrl: string, query: string, variables: Record | undefined, timeoutMs: number, signal?: AbortSignal): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/indexer-ready` + +```ts +export interface WaitForIndexerOptions { + timeoutMs?: number; + pollIntervalMs?: number; + signal?: AbortSignal; +} +export declare function waitForAddressFunded(indexerWS: string, address: string, opts?: WaitForIndexerOptions): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/ledger-guard` + +```ts +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare class UnsupportedLedgerError extends Error { + readonly code = "UNSUPPORTED_LEDGER"; + constructor(network: string, protocolVersion: bigint); +} +export declare function checkLedgerSupported(network: string, protocolVersion: bigint | null): void; +export declare function fetchProtocolVersion(indexerHttpUrl: string, signal?: AbortSignal): Promise; +export declare function assertLedgerSupported(networkName: string, network: NetworkConfig, fetchVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise, signal?: AbortSignal): Promise; +export declare class LocalStackUnreachableError extends Error { + readonly code = "LOCAL_STACK_UNREACHABLE"; + constructor(component: "indexer" | "node", url: string); +} +export interface StackProbes { + fetchVersion?: (indexerHttpUrl: string) => Promise; + fetchGenesis?: (nodeWsUrl: string) => Promise; +} +export declare function assertLedger9StackReachable(networkName: string, network: NetworkConfig, probes?: StackProbes): Promise; +type WalletKind = "shielded" | "unshielded" | "dust"; +export declare function walletsBelowLedger9(versions: Readonly>): WalletKind[]; +``` + +## `@kuiralabs/midnight-chain/lib/node-ready` + +```ts +export interface WaitForFirstBlockOptions { + timeoutMs?: number; + pollIntervalMs?: number; + signal?: AbortSignal; +} +export declare function waitForFirstBlock(nodeWsUrl: string, opts?: WaitForFirstBlockOptions): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/node-rpc` + +```ts +export interface RpcOptions { + url: string; + timeoutMs?: number; + signal?: AbortSignal; +} +export declare function callNodeRpc(opts: RpcOptions, method: string, params?: unknown[]): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/offer-liveness` + +```ts +export interface CoinSpend { + nullifier: string; + transactionHash: string; + blockHeight: number; +} +export declare class LivenessUnknownError extends Error { + constructor(reason: string); +} +export declare function spendsOf(indexer: { + indexer: string; + indexerWS: string; +}, nullifiers: readonly string[], options?: { + fromBlock?: number; + signal?: AbortSignal; +}): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/proof-server-ready` + +```ts +export interface WaitForProofServerOptions { + timeoutMs?: number; + pollIntervalMs?: number; + requestTimeoutMs?: number; + signal?: AbortSignal; +} +export declare function waitForProofServerReady(proofServerUrl: string, opts?: WaitForProofServerOptions): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/tx-receipt` + +```ts +import { type FinalTransaction, type TransactionStatus } from "./tx-status.ts"; +export declare const RECEIPT_WAIT_MS = 60000; +export type Receipt = { + readonly listed: true; + readonly transaction: FinalTransaction; +} | { + readonly listed: false; + readonly reason: string; +}; +export declare function receiptOf(indexerHttpUrl: string, txId: string, signal?: AbortSignal, waitMs?: number): Promise; +export declare function finalTransactionJson(tx: FinalTransaction): Record; +export declare function transactionStatusJson(status: TransactionStatus): Record; +export declare function receiptJson(receipt: Receipt): Record; +``` + +## `@kuiralabs/midnight-chain/lib/tx-segments` + +```ts +export interface SegmentResult { + id: number; + success: boolean; +} +export declare class SegmentResultsUnavailableError extends Error { + constructor(txHash: string, reason: string); +} +export declare function fetchPartialSuccessSegments(indexerHttpUrl: string, txHash: string): Promise; +``` + +## `@kuiralabs/midnight-chain/lib/tx-status` + +```ts +export type TxReference = { + hash: string; +} | { + identifier: string; +}; +export type TxResultStatus = "SUCCESS" | "PARTIAL_SUCCESS" | "FAILURE"; +export interface FinalTransaction { + readonly state: "final"; + readonly kind: "regular" | "system"; + readonly hash: string; + readonly identifiers: readonly string[]; + readonly result?: TxResultStatus; + readonly segments?: ReadonlyArray<{ + id: number; + success: boolean; + }>; + readonly feeSpecks?: bigint; + readonly block: { + readonly height: number; + readonly hash: string; + readonly time: Date; + }; +} +export interface UnknownTransaction { + readonly state: "notFound"; +} +export type TransactionStatus = FinalTransaction | UnknownTransaction; +export declare function parseTxReference(text: string): TxReference; +export declare function fetchTransactionStatus(indexerHttpUrl: string, ref: TxReference, signal?: AbortSignal): Promise; +export declare function waitForTransactionStatus(indexerHttpUrl: string, ref: TxReference, timeoutMs: number, signal?: AbortSignal, intervalMs?: number): Promise; +``` diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md new file mode 100644 index 00000000..3825b1e4 --- /dev/null +++ b/packages/cli-core/api-report.md @@ -0,0 +1,1680 @@ +# API report: @kuiralabs/midnight-cli-core + +Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-cli-core/commands/config` + +```ts +import { type ParsedArgs } from "../lib/argv.ts"; +import type { CallContext } from "../lib/call-context.ts"; +export default function configCommand(args: ParsedArgs, ctx: CallContext): Promise; +``` + +## `@kuiralabs/midnight-cli-core/commands/config.definition` + +```ts +import type { CommandDefinition } from "../lib/command-definition.ts"; +export declare const configDefinition: CommandDefinition; +``` + +## `@kuiralabs/midnight-cli-core/commands/core.guidance` + +```ts +import type { PackageGuidance } from "../lib/agent-guidance.ts"; +export declare const coreGuidance: PackageGuidance; +``` + +## `@kuiralabs/midnight-cli-core/lib/agent-guidance` + +```ts +export type GuidanceText = "agent-manual" | "skill-core" | "skill-full"; +export interface GuidancePiece { + readonly text: GuidanceText; + readonly section: string; + readonly order: number; + readonly body: string; +} +export interface ToolsTableRow { + readonly tool: string; + readonly group: string; + readonly order: number; + readonly description: readonly string[]; + readonly params?: readonly string[]; +} +export interface GuidanceSection { + readonly text: GuidanceText; + readonly name: string; + readonly after: string; +} +export interface PackageGuidance { + readonly pieces: readonly GuidancePiece[]; + readonly sections?: readonly GuidanceSection[]; + readonly toolsTable?: readonly ToolsTableRow[]; +} +export declare class GuidanceError extends Error { + constructor(message: string); +} +export declare function unplacedPieces(text: GuidanceText, sections: readonly string[], pieces: readonly GuidancePiece[]): GuidancePiece[]; +export declare function sectionsWithAdded(text: GuidanceText, skeleton: readonly string[], added: readonly GuidanceSection[]): string[]; +export declare function assertDistinctPlaces(pieces: readonly GuidancePiece[]): void; +export declare function assembleGuidance(text: GuidanceText, sections: readonly string[], pieces: readonly GuidancePiece[]): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/amount` + +```ts +export declare function nightToMicro(amountNight: number): bigint; +export declare function parseAmount(amountStr: string): number; +``` + +## `@kuiralabs/midnight-cli-core/lib/approval` + +```ts +import type { FeeLimits } from "./fee-limits.ts"; +export interface ApprovalDetail { + label: string; + value: string; +} +export interface ApprovalRequest { + method: string; + dappName?: string; + network: string; + details: ApprovalDetail[]; + feeOnly?: boolean; +} +export type ApprovalResult = "approve" | "reject"; +export interface ApprovalOptions { + autoApproveReads?: boolean; + approveAll?: boolean; + approveFees?: boolean; +} +export interface ApprovalPolicy { + reads: "auto"; + balancing: "auto" | "fee-only" | "prompt"; + writes: "auto" | "fee-only" | "prompt"; + feeLimits?: { + maxFeeSpecks: string; + maxPending: number; + }; +} +export declare function describeApprovalPolicy(options: ApprovalOptions, feeLimits: FeeLimits): ApprovalPolicy; +export declare function isReadOnlyMethod(method: string): boolean; +export declare function isPrepMethod(method: string): boolean; +export declare function renderApprovalBox(request: ApprovalRequest): string; +export declare function promptApproval(request: ApprovalRequest, options?: ApprovalOptions): Promise; +``` + +## `@kuiralabs/midnight-cli-core/lib/argv` + +```ts +export interface ParsedArgs { + command: string | undefined; + subcommand: string | undefined; + positionals: string[]; + flags: Record; +} +export declare function parseArgs(argv?: string[]): ParsedArgs; +export declare function getFlag(args: ParsedArgs, name: string): string | undefined; +export declare function hasFlag(args: ParsedArgs, name: string): boolean; +export declare function isVerbose(args: ParsedArgs): boolean; +export declare const MINIMAL_FLAG = "_minimal"; +export declare const FULL_FLAG = "_full"; +export declare function isMinimalMode(args: ParsedArgs): boolean; +export declare function rejectNoCacheForWrites(args: ParsedArgs): void; +export declare function requireFlag(args: ParsedArgs, name: string, description: string): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/blockfrost` + +```ts +declare const BLOCKFROST_NETWORKS: { + readonly preprod: { + readonly host: "midnight-preprod.blockfrost.io"; + readonly prefix: "nightpreprod"; + }; +}; +export type BlockfrostNetwork = keyof typeof BLOCKFROST_NETWORKS; +export declare const BLOCKFROST_SITE = "https://blockfrost.io"; +export declare const SET_PROJECT_ID_COMMAND = "midnight config set blockfrost-project-id "; +export declare function usesBlockfrost(network: string): network is BlockfrostNetwork; +export declare function blockfrostNetworks(): BlockfrostNetwork[]; +export declare function networkOfProjectId(projectId: string): BlockfrostNetwork | undefined; +export declare function checkProjectId(given: string): { + projectId: string; + network: BlockfrostNetwork; +}; +export declare function blockfrostEndpoints(network: BlockfrostNetwork, projectId: string | undefined): { + indexer: string; + indexerWS: string; + node: string; +}; +export declare function isBlockfrostUrl(url: string): boolean; +export declare class BlockfrostProjectIdRequiredError extends Error { + readonly code = "BLOCKFROST_PROJECT_ID_REQUIRED"; + constructor(network: string); +} +export declare class BlockfrostProjectIdRejectedError extends Error { + readonly code = "BLOCKFROST_PROJECT_ID_REJECTED"; + constructor(network: string); +} +export declare class BlockfrostLimitError extends Error { + readonly code = "BLOCKFROST_LIMIT_REACHED"; + constructor(status: number); +} +export declare class EndpointShutDownError extends Error { + readonly code = "ENDPOINT_SHUT_DOWN"; + constructor(url: string); +} +export declare function isEndpointError(err: unknown): boolean; +export declare function assertEndpointUsable(url: string): void; +export declare function endpointRefusal(url: string, status: number): Error | undefined; +export declare function endpointRefusalFromWsError(url: string, error: unknown): Error | undefined; +export declare const REDACTED = "***"; +export declare function redactProjectId(text: string): string; +export declare function mayHoldProjectId(text: string): boolean; +export declare function maskProjectId(projectId: string): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/cache-indexer` + +```ts +export declare function indexerIdentity(indexerUrl: string): string; +export interface IndexerChange { + previous: string; + current: string; + removed: number; +} +export declare function bindCachesToIndexer(network: string, indexerUrl: string, cacheDir?: string): IndexerChange | undefined; +export declare function describeIndexerChange(network: string, change: IndexerChange): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/call-context` + +```ts +import { type ParsedArgs } from "./argv.ts"; +import type { Payer } from "./payer.ts"; +import { type Settings } from "./settings.ts"; +import { type HostPaths } from "./state-root.ts"; +import { type CallSdkWarnings } from "./sdk-warnings.ts"; +import { type Progress, type ProgressReport } from "../ui/spinner.ts"; +export interface CallOutput { + result(data: Readonly>): void; + stdout(text: string): void; + stderr(text: string): void; +} +export type CallProgress = Progress; +export interface CallDiagnostics { + readonly isVerbose: boolean; + line(phase: string, message: string): void; +} +export type { CallSdkWarnings } from "./sdk-warnings.ts"; +export interface CallConfig { + readonly settings: Settings; + readonly paths: HostPaths; +} +export interface CallContext { + readonly signal: AbortSignal; + readonly output: CallOutput; + readonly progress: CallProgress; + readonly diagnostics: CallDiagnostics; + readonly sdkWarnings: CallSdkWarnings; + readonly config: CallConfig; + readonly payer?: Payer; + readonly protectors?: readonly Protector[]; +} +export interface CommandOutcome { + readonly exitCode: number; +} +export type CommandHandler = (args: ParsedArgs, ctx: CallContext) => Promise; +export declare class SecondResultError extends Error { + constructor(); +} +export declare function callOutput(sink: CallOutput): CallOutput; +export declare function callDiagnostics(verbose: boolean, write: (line: string) => void): CallDiagnostics; +export declare function hostCallConfig(): CallConfig; +export interface CallParts { + readonly args: ParsedArgs; + readonly signal: AbortSignal; + readonly output: CallOutput; + readonly onProgress?: ProgressReport; + readonly sdkWarnings?: CallSdkWarnings; + readonly payer?: Payer; + readonly protectors?: readonly Protector[]; +} +export declare function createCallContext(parts: CallParts): CallContext; +export declare function runHandler(handler: CommandHandler, args: ParsedArgs, ctx: CallContext): Promise; +``` + +## `@kuiralabs/midnight-cli-core/lib/cli-config` + +```ts +import { type NetworkName } from "./network.ts"; +import type { SdkSet } from "./engine.ts"; +export interface NetworkEndpointOverrides { + "proof-server"?: string; + node?: string; + "indexer-ws"?: string; +} +export interface NetworkSettings extends NetworkEndpointOverrides { + "blockfrost-project-id"?: string; + "sdk-set"?: SdkSet; +} +export interface CliConfig { + network: NetworkName; + networks?: Partial>; + "proof-server"?: string; + node?: string; + "indexer-ws"?: string; + wallet?: string; +} +export declare function loadCliConfig(configDir?: string): CliConfig; +export declare function getEndpointOverridesForNetwork(config: CliConfig, networkName: NetworkName): NetworkEndpointOverrides; +export declare function getSdkSetOverride(config: CliConfig, networkName: NetworkName): SdkSet | undefined; +export declare function getBlockfrostProjectId(config: CliConfig, networkName: NetworkName): string | undefined; +export declare function saveCliConfig(config: CliConfig, configDir?: string): void; +export declare function getConfigValue(key: string, configDir?: string, scope?: NetworkName): string; +export declare function setConfigValue(key: string, value: string, configDir?: string, scope?: NetworkName): void; +export declare function unsetConfigValue(key: string, configDir?: string, scope?: NetworkName): void; +export declare function getValidConfigKeys(): readonly string[]; +``` + +## `@kuiralabs/midnight-cli-core/lib/command-definition` + +```ts +import { type ParsedArgs } from "./argv.ts"; +import { type PackageGuidance } from "./agent-guidance.ts"; +import type { CallContext, CommandOutcome } from "./call-context.ts"; +export interface ParamSchema { + readonly type: "string" | "boolean"; + readonly enum?: readonly string[]; + readonly description?: string; +} +export declare const NETWORK_PARAM: ParamSchema; +export declare const ENDPOINT_PARAMS: { + readonly node: { + readonly type: "string"; + readonly description: "Node RPC URL (default: the configured one, or the network's)"; + }; + readonly "indexer-ws": { + readonly type: "string"; + readonly description: "Indexer WebSocket URL (default: the configured one, or the network's)"; + }; + readonly "proof-server": { + readonly type: "string"; + readonly description: "Proof server URL (default: the configured one, or the network's)"; + }; +}; +export interface NotForAgents { + readonly notForAgents: string; +} +export interface FlagDefinition { + readonly name: string; + readonly takesValue: boolean; + readonly subcommands?: readonly string[]; + readonly help?: readonly string[]; + readonly agent?: ParamSchema | NotForAgents; +} +export type FlagsSectionEntry = string | { + readonly flag: string; +}; +export interface CommandHelp { + readonly description: string; + readonly usage: string; + readonly flags?: readonly FlagsSectionEntry[]; + readonly examples?: readonly string[]; + readonly jsonFields?: Readonly>; +} +export interface ShellCall { + readonly payer?: true; + readonly protectors?: true; + readonly notice?: string; + readonly unavailable?: string; +} +export interface CommandModule { + default(args: ParsedArgs, ctx: CallContext): Promise; +} +export interface ToolAnnotations { + readonly readOnlyHint?: boolean; + readonly destructiveHint?: boolean; + readonly idempotentHint?: boolean; + readonly openWorldHint?: boolean; +} +export interface ToolInputSchema { + readonly type: "object"; + readonly properties: Readonly>; + readonly required?: readonly string[]; +} +export type ToolParam = { + readonly name: string; + readonly schema: ParamSchema; +} | { + readonly flag: string; + readonly schema?: ParamSchema; +}; +export interface ToolArgv { + readonly subcommand?: string | { + readonly param: string; + }; + readonly positionals?: readonly string[]; + readonly flags: "rest" | readonly string[]; + readonly fixedFlags?: Readonly>; + readonly defaultFlags?: Readonly>; +} +export interface ToolCheckCall { + argv(): ParsedArgs; + run(args: ParsedArgs): Promise>; +} +export interface ToolConfirmation { + readonly when?: (params: Readonly>) => boolean; + readonly describe?: (params: Readonly>) => string; + readonly check?: (params: Readonly>, call: ToolCheckCall) => Promise; +} +export interface ToolDefinition { + readonly name: string; + readonly description: string; + readonly annotations?: ToolAnnotations; + readonly params: readonly ToolParam[]; + readonly required?: readonly string[]; + readonly argv: ToolArgv; + readonly confirmation?: ToolConfirmation; + readonly order: number; +} +export interface CommandDefinition { + readonly name: string; + readonly order: number; + readonly subcommands?: readonly string[]; + readonly subcommandAliases?: Readonly>; + readonly flags: readonly FlagDefinition[]; + readonly help?: CommandHelp; + readonly intro?: { + readonly brief: string; + readonly order: number; + }; + readonly needsWalletSdk: boolean; + readonly shell: ShellCall; + readonly load: () => Promise; + readonly mcp?: { + readonly tools: readonly ToolDefinition[]; + }; +} +export interface CommandPackage { + readonly name: string; + readonly commands: readonly CommandDefinition[]; + readonly guidance: PackageGuidance; +} +export interface RegisteredTool extends ToolDefinition { + readonly inputSchema: ToolInputSchema; + readonly command: CommandDefinition; +} +export interface GlobalFlagHelp { + readonly name: string; + readonly description: string; +} +export interface CommandRegistry { + readonly commands: readonly CommandDefinition[]; + readonly globalFlags: readonly FlagDefinition[]; + readonly globalFlagsHelp: readonly GlobalFlagHelp[]; + find(name: string): CommandDefinition | undefined; + readonly tools: readonly RegisteredTool[]; + readonly packages: readonly CommandPackage[]; +} +export declare class CommandDefinitionError extends Error { + constructor(message: string); +} +export declare function toolInputSchema(command: CommandDefinition, tool: ToolDefinition, globalFlags: readonly FlagDefinition[]): ToolInputSchema; +export declare function toolArgv(tool: RegisteredTool, params: Readonly>): ParsedArgs; +export declare function createCommandRegistry(commands: readonly CommandDefinition[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; +export declare function createPackageRegistry(packages: readonly CommandPackage[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; +export declare function flagsSectionLines(command: CommandDefinition): string[]; +export interface CommandHelpSpec { + readonly name: string; + readonly description: string; + readonly usage: string; + readonly flags?: readonly string[]; + readonly examples?: readonly string[]; + readonly jsonFields?: Readonly>; +} +export declare function commandHelpSpecs(registry: Pick): CommandHelpSpec[]; +export declare function introBriefs(registry: Pick): [ + name: string, + brief: string +][]; +export declare function confirmationTarget(params: Readonly>): { + network: string; + wallet: string; +}; +export declare function needsConfirmation(tool: ToolDefinition, params: Readonly>): boolean; +export declare function confirmationText(tool: ToolDefinition, params: Readonly>): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/command-flags` + +```ts +import { type ParsedArgs } from "./argv.ts"; +import type { CommandRegistry } from "./command-definition.ts"; +type FlagRegistry = Pick; +export declare function findUnknownFlags(args: ParsedArgs, registry: FlagRegistry): string[]; +export declare function findMisplacedFlags(args: ParsedArgs, registry: FlagRegistry): Array<{ + flag: string; + subcommands: readonly string[]; +}>; +export declare function assertKnownFlags(args: ParsedArgs, registry: FlagRegistry): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/connector-api` + +```ts +export type ErrorCode = "InternalError" | "Rejected" | "InvalidRequest" | "PermissionRejected" | "Disconnected"; +export type APIError = Error & { + type: "DAppConnectorAPIError"; + code: ErrorCode; + reason: string; +}; +export interface RpcHandlerContext { + notify: (method: string, params?: Record) => void; + connectionId: string; + requestId: number | string; + metadata: Record; +} +export type RpcHandler = (params: Record, context: RpcHandlerContext) => Promise; +export declare function createApiError(code: ErrorCode, reason: string): APIError; +export declare const OPERATOR_REJECTED_MESSAGE = "User rejected the request"; +``` + +## `@kuiralabs/midnight-cli-core/lib/constants` + +```ts +export declare const GENESIS_SEED = "0000000000000000000000000000000000000000000000000000000000000001"; +export declare const NATIVE_TOKEN_TYPE = "0000000000000000000000000000000000000000000000000000000000000000"; +export declare const INDEXER_API_VERSION = "v4"; +export declare const INDEXER_GRAPHQL_PATH = "/api/v4/graphql"; +export declare const INDEXER_GRAPHQL_WS_PATH = "/api/v4/graphql/ws"; +export declare const TOKEN_DECIMALS = 6; +export declare const TOKEN_MULTIPLIER = 1000000; +export declare const DUST_COST_OVERHEAD = 300000000000000n; +export declare const DUST_FEE_BLOCKS_MARGIN = 5; +export declare const MIN_DUST_FOR_TRANSFER = 900000000000000n; +export declare const INITIAL_NIGHT_DUST_RATIO = 5000000000n; +export declare const INITIAL_GENERATION_DECAY_RATE = 8267n; +export declare const INITIAL_DUST_GRACE_PERIOD_SECONDS = 10800n; +export declare const SYNC_TIMEOUT_MS = 300000; +export declare const SYNC_ATTEMPT_TIMEOUT_MS = 30000; +export declare const SYNC_ATTEMPT_REMOTE_TIMEOUT_MS = 120000; +export declare const PRE_SEND_SYNC_TIMEOUT_MS = 10000; +export declare const DUST_TIMEOUT_MS = 120000; +export declare const PROOF_TIMEOUT_MS = 300000; +export declare const BALANCE_CHECK_TIMEOUT_MS = 60000; +export declare const SYNC_HEAP_TARGET_MB = 16384; +export declare const SYNC_HEAP_RAM_FRACTION = 0.7; +export declare const SYNC_HEAP_MIN_GAIN_MB = 512; +export declare const TX_TTL_MINUTES = 10; +export declare const MAX_RETRY_ATTEMPTS = 3; +export declare const RETRY_BASE_DELAY_MS = 1000; +export declare const DUST_REGISTRATION_TIMEOUT_MS = 600000; +export declare const DUST_REGISTRATION_RETRY_DELAY_MS = 15000; +export declare const STALE_UTXO_ERROR_CODE = 115; +export declare const BALANCE_OVERSPEND_ERROR_CODE = 138; +export declare const MIDNIGHT_DIR = ".midnight"; +export declare const DEFAULT_WALLET_FILENAME = "wallet.json"; +export declare const DEFAULT_CONFIG_FILENAME = "config.json"; +export declare const DIR_MODE = 448; +export declare const FILE_MODE = 384; +export declare const LOCALNET_DIR_NAME = "localnet"; +export declare const CACHE_VERSION = 2; +export declare const CACHE_DIR_NAME = "cache"; +export declare const WALLETS_DIR_NAME = "wallets"; +export declare const DEFAULT_WALLET_NAME = "default"; +export declare function isValidWalletName(name: string): boolean; +export declare const DUST_RETRY_ATTEMPTS = 10; +export declare const DUST_RETRY_DELAY_MS = 3000; +export declare const ABANDONED_TX_TIMEOUT_MS = 120000; +export declare const DEFAULT_SERVE_PORT = 9932; +export declare const DASHBOARD_BASE_URL = "https://midnight-comp-tracker.vercel.app"; +``` + +## `@kuiralabs/midnight-cli-core/lib/durable-file` + +```ts +export declare class FileExistsError extends Error { + constructor(file: string); +} +export declare function writeJsonDurably(file: string, value: unknown, { exclusive }?: { + exclusive?: boolean; +}): void; +export declare function readJsonIfPresent(file: string): T | undefined; +``` + +## `@kuiralabs/midnight-cli-core/lib/duration` + +```ts +export declare function formatWait(ms: number): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/dust-balancing-plan` + +```ts +export interface DustInput { + token: TToken; + value: bigint; +} +export type DustPlan = { + kind: "covered"; + fee: bigint; + inputs: DustInput[]; +} | { + kind: "short"; + atFirstChoice: boolean; +}; +export interface DustPlanOptions { + owed: bigint; + coinCount: number; + choose: (owed: bigint) => DustInput[] | undefined; + feeWith: (inputs: readonly DustInput[]) => bigint; +} +export declare function chooseDustCoins(coins: readonly DustInput[], owed: bigint, combine: (owed: bigint) => DustInput[] | undefined): DustInput[] | undefined; +export declare function planDustInputs({ owed, coinCount, choose, feeWith }: DustPlanOptions): DustPlan; +export declare function spreadFeeAcrossInputs(inputs: readonly DustInput[], fee: bigint): DustInput[]; +``` + +## `@kuiralabs/midnight-cli-core/lib/dust-registration-plan` + +```ts +export interface DustGenerationEstimate { + dust: { + generatedNow: bigint; + rate: bigint; + maxCap: bigint; + }; +} +export interface RegistrationPlan { + fee: bigint; + generated: bigint; + ratePerSecond: bigint; + cap: bigint; + waitMs: number | null; +} +export declare function planRegistration(fee: bigint, estimates: readonly DustGenerationEstimate[]): RegistrationPlan; +export declare class DustFeeNotGeneratedError extends Error { + readonly code = "DUST_GENERATING"; + constructor(plan: RegistrationPlan, now: Date); +} +``` + +## `@kuiralabs/midnight-cli-core/lib/dust-wait` + +```ts +import { sleep } from "./sleep.ts"; +export interface DustBalanceSource { + balance(at: Date): bigint; +} +export declare const DUST_SHORT_WAIT_MS: number; +export declare const OWN_COMMAND_DUST_WAIT_MS: number; +export declare const LOOK_AHEAD_MS: number; +export declare function msUntilDust(dust: DustBalanceSource, needed: bigint, now: Date, horizonMs: number): number | null; +export declare function dustShortError(have: bigint, needed: bigint, waitMs: number | null): Error; +export declare function awaitDustForFee(dust: DustBalanceSource, needed: bigint, onStatus?: (status: string) => void, signal?: AbortSignal): Promise; +export interface DustWaitPlan { + have: bigint; + needed: bigint; + waitMs: number | null; +} +export declare function planDustWait(err: unknown, dust: DustBalanceSource, now: Date): DustWaitPlan | undefined; +export declare function payWhenDustCovers(pay: () => Promise, dust: DustBalanceSource, options: { + maxWaitMs: number; + onStatus?: (status: string) => void; + signal?: AbortSignal; +}): Promise; +export { sleep }; +``` + +## `@kuiralabs/midnight-cli-core/lib/engine` + +```ts +import type { OfferContents } from "./swap-offer.ts"; +import type { OpenOffer } from "./open-offers.ts"; +import { type NetworkConfig, type NetworkName } from "./network.ts"; +import type { CallSdkWarnings } from "./sdk-warnings.ts"; +import type { VerboseLog } from "./verbose.ts"; +import type { ApprovalOptions } from "./approval.ts"; +import type { FeeLimits } from "./fee-limits.ts"; +import type { RpcHandler } from "./connector-api.ts"; +import type { Spinner } from "../ui/spinner.ts"; +export type SdkSet = "rc" | "beta"; +export interface EngineKeys { + unshieldedAddress(seed: Buffer, network: NetworkName, keyIndex?: number): string; + unshieldedAddresses(seed: Buffer, keyIndex?: number): Record; + shieldedAddress(seed: Buffer, network: NetworkName): string; + shieldedAddresses(seed: Buffer): Record; + dustPublicKeyHex(seed: Buffer): string; + shieldedCoinPublicKeyHex(seed: Buffer): string; + assertAddress(address: string, kind: "shielded" | "unshielded", network: NetworkName): void; +} +export interface TransactionDetail { + label: string; + value: string; +} +export interface BlockLimits { + readTime: number; + computeTime: number; + blockUsage: number; + bytesWritten: number; + bytesChurned: number; +} +export interface EngineLedger { + blockLimits(parametersHex: string): BlockLimits; + nightTokenId(): string; + readTransaction(txHex: string, stage: "unsealed" | "sealed"): TransactionDetail[]; + readOffer(txHex: string): OfferContents; + spentNullifiers(txHex: string): string[]; +} +export type RawStateValue = { + type: "null"; +} | { + type: "cell"; + value: string[]; +} | { + type: "array"; + items: RawStateValue[]; +} | { + type: "map"; + size: number; +} | { + type: "boundedMerkleTree"; + height: number; + root: string[] | null; +}; +export interface ScriptParts { + readonly prelude: string; + rpcClientCode(servePort: number): string; + readonly coerceArgFn: string; + readonly privateStateSecretFn: string; + readonly witnessCandidates: readonly string[]; + readonly indexerUrlEnv: string; + readonly indexerWsUrlEnv: string; +} +export interface ScriptContract { + networkConfig: NetworkConfig; + managedDir: string; + contractName: string; +} +export interface DeployScript extends ScriptContract { + servePort: number; + privateStateKey?: string; + args?: unknown[]; +} +export interface CallScript extends ScriptContract { + servePort: number; + contractAddress: string; + circuit: string; + args?: unknown[]; + privateStateKey?: string; +} +export interface StateScript extends ScriptContract { + contractAddress: string; +} +export interface EngineContractScripts { + readonly packages: readonly string[]; + packageFolder(name: string): string | null; + readonly compactRuntimeVersion: string; + readonly compiler: string; + acceptsRuntime(runtimeVersion: string): boolean; + deploy(script: DeployScript, parts: ScriptParts): string; + call(script: CallScript, parts: ScriptParts): string; + state(script: StateScript, parts: ScriptParts): string; +} +export interface EngineContracts { + rawState(networkConfig: NetworkConfig, address: string): Promise; + acceptsPrivateStatePassword(password: string): boolean; + readonly scripts: EngineContractScripts; +} +export interface ShieldedBalanceResult { + balance: bigint; + availableCoins: number; + tokens: ReadonlyMap; + eventCount: number; + lastAppliedEventId: number; + fromCache: boolean; + partial: boolean; +} +export interface ShieldedCachedOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + signal?: AbortSignal; + timeoutMs?: number; + forceFresh?: boolean; + chainId?: string; +} +export interface EngineReaders { + shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options?: ShieldedCachedOptions): Promise; +} +export interface BalanceSummary { + balances: Map; + utxoCount: number; + txCount: number; + highestTxId: number; + registeredUtxos: number; + unregisteredUtxos: number; +} +export interface TransferParams { + seedBuffer: Buffer; + networkConfig: NetworkConfig; + recipientAddress: string; + amountNight: number; + signal?: AbortSignal; + onSync?: (applied: number, highest: number) => void; + onSyncDetail?: (walletsStillSyncing: string) => void; + onDust?: (status: string) => void; + onProving?: () => void; + onSubmitting?: () => void; + onSubmittingTick?: (elapsedMs: number) => void; + onSyncWarning?: (tag: string, message: string) => void; + sdkWarnings: CallSdkWarnings; + log?: VerboseLog; +} +export interface TransferResult { + txHash: string; + amountMicroNight: bigint; +} +export interface EnsureDustResult { + alreadyAvailable: boolean; + txHash?: string; +} +export type AirdropParams = Omit; +export interface DustRegisterOptions { + signal?: AbortSignal; + onStatus?: (status: string) => void; + onSyncProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + onSyncWarning?: (tag: string, message: string) => void; + sdkWarnings: CallSdkWarnings; + log?: VerboseLog; +} +export interface DustRegistration { + alreadyAvailable: boolean; + txHash?: string; + dustBalance: bigint; +} +export interface DustExportResult { + network: string; + dustPublicKey: string; + offset: number; + balance: bigint; + eventCount: number; + fromCache: boolean; + partial: boolean; + snapshot: string; +} +export interface UnshieldedView extends BalanceSummary { + fromCache: boolean; + fetchedAt: number; +} +export interface ReadOptions { + forceFresh?: boolean; + signal?: AbortSignal; + onStatus?: (s: string) => void; + onProgress?: (current: number, highest: number) => void; + log?: VerboseLog; +} +export interface DustBalance { + balance: bigint; + availableCoins: number; + ownedUtxoCount: number; + syncTime: Date; + fromCache: boolean; + eventsApplied: number; + lastAppliedEventId: number; + partial: boolean; + fetchedAt: number; +} +export interface WalletSyncHooks { + signal?: AbortSignal; + log?: VerboseLog; + onStatus?: (status: string) => void; + onSyncProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; +} +export interface ShieldedTransferParams extends WalletSyncHooks { + seed: Buffer; + network: NetworkName; + networkConfig: NetworkConfig; + recipient: string; + amount: bigint; + progress: Spinner; + insufficient: (availableNight: string) => string; + waitForDustToCover: boolean; + onSenderShieldedAddress?: (address: string) => void; +} +export interface PrepWallet { + seed: Buffer; + network: NetworkName; + networkConfig: NetworkConfig; + address: string; + signal?: AbortSignal; + onMessage: (message: string) => void; +} +export interface DAppConnectorCallbacks { + onPhaseStart?: (connectionId: string, method: string, phase: string) => void; + onPhaseComplete?: (connectionId: string, method: string, phase: string, durationMs: number) => void; +} +export interface DAppConnector { + handlers: Record; + revertPendingTxs(connectionId: string): Promise; + handOffPendingTx(connectionId: string, txHex: string): boolean; + takeOffer(connectionId: string, txHex: string): Promise; + cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; + hasPendingTxs(): boolean; + dispose(): void; +} +export interface OpenedConnector { + connector: DAppConnector; + stop(): Promise; +} +export interface ServedWalletSession { + waitForDust(): Promise; + saveState(): Promise; + connect(options: { + approvalOptions: ApprovalOptions; + feeLimits?: FeeLimits; + callbacks?: DAppConnectorCallbacks; + }): DAppConnector; +} +export interface EngineWallet { + unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + dustBalance(seed: Buffer, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + transfer(params: TransferParams): Promise; + airdrop(params: AirdropParams): Promise; + shieldedTransfer(params: ShieldedTransferParams): Promise; + registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; + exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options?: { + signal?: AbortSignal; + log?: VerboseLog; + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + }): Promise; + prepNightBalance(wallet: PrepWallet): Promise; + prepDust(wallet: PrepWallet, waitMs: number): Promise<{ + alreadyAvailable: boolean; + dustAvailable: boolean; + }>; + openConnector(options: { + seed: Buffer; + network: NetworkName; + networkConfig: NetworkConfig; + address: string; + syncMode: "full" | "lite"; + dustWaitMs?: number; + signal?: AbortSignal; + onMessage: (message: string) => void; + }): Promise; + serveWallet(options: { + seed: Buffer; + networkConfig: NetworkConfig; + network: NetworkName; + address: string; + syncMode: "full" | "lite"; + } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; +} +export interface Engine { + readonly set: SdkSet; + readonly keys: EngineKeys; + readonly ledger: EngineLedger; + readonly contracts: EngineContracts; + readonly readers: EngineReaders; + readonly wallet: EngineWallet; +} +export declare function sdkSetOf(network: NetworkName): SdkSet; +export type EngineLoader = (set: SdkSet) => Promise; +export declare class OtherSdkSetError extends Error { + readonly code = "OTHER_SDK_SET"; + readonly loadedSet: SdkSet; + readonly wantedSet: SdkSet; + constructor(loadedSet: SdkSet, wantedSet: SdkSet, message?: string); +} +export declare function setEngineLoader(next: EngineLoader): void; +export declare function engineFor(network: NetworkName): Promise; +export declare function preferEngineOf(network: NetworkName): void; +export declare function anyEngine(): Promise; +``` + +## `@kuiralabs/midnight-cli-core/lib/error-trim` + +```ts +export declare function trimAgentMessage(raw: string): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/errors` + +```ts +export declare class UsageError extends Error { + constructor(message: string); +} +export declare function isUsageError(err: unknown): err is UsageError; +export declare const CANCELLED_MESSAGE = "Operation cancelled"; +export declare class CancelledError extends Error { + readonly code = "CANCELLED"; + constructor(message?: string); +} +export declare class TransactionRefusedError extends Error { + readonly reason: string; + constructor(reason: string, options?: { + cause?: unknown; + }); +} +export declare class CommandFailedError extends Error { + readonly exitCode: number; + readonly result: Readonly>; + constructor(command: string, exitCode: number, result: Readonly>); +} +export declare function throwIfCancelled(signal: AbortSignal | undefined): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/exec-program` + +```ts +export interface ExecRun { + readonly signal: AbortSignal; + readonly timeoutMs?: number; + readonly onStderr?: (text: string) => void; +} +export type ExecRunner = (file: string, args: readonly string[], run: ExecRun) => Promise; +export declare class ProgramFailedError extends Error { + readonly command: string; + readonly exitCode: number | null; + readonly stderr: string; + readonly stdout: string; + constructor(command: string, exitCode: number | null, stderr: string, stdout: string); +} +export declare class ProgramTimedOutError extends Error { + readonly command: string; + constructor(command: string, timeoutMs: number); +} +export declare const execProgram: ExecRunner; +``` + +## `@kuiralabs/midnight-cli-core/lib/exit-codes` + +```ts +export declare const EXIT_SUCCESS = 0; +export declare const EXIT_GENERAL_ERROR = 1; +export declare const EXIT_INVALID_ARGS = 2; +export declare const EXIT_WALLET_NOT_FOUND = 3; +export declare const EXIT_NETWORK_ERROR = 4; +export declare const EXIT_INSUFFICIENT_BALANCE = 5; +export declare const EXIT_TX_REJECTED = 6; +export declare const EXIT_CANCELLED = 7; +export declare const ERROR_CODES: { + readonly INVALID_ARGS: "INVALID_ARGS"; + readonly WALLET_NOT_FOUND: "WALLET_NOT_FOUND"; + readonly NETWORK_ERROR: "NETWORK_ERROR"; + readonly INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE"; + readonly TX_REJECTED: "TX_REJECTED"; + readonly STALE_UTXO: "STALE_UTXO"; + readonly STALE_CACHE: "STALE_CACHE"; + readonly PROOF_TIMEOUT: "PROOF_TIMEOUT"; + readonly PROOF_FAILURE: "PROOF_FAILURE"; + readonly INVALID_DUST_PROOF: "INVALID_DUST_PROOF"; + readonly DUST_REQUIRED: "DUST_REQUIRED"; + readonly DUST_GENERATING: "DUST_GENERATING"; + readonly CHAIN_CLOCK_BEHIND: "CHAIN_CLOCK_BEHIND"; + readonly SYNC_TIMEOUT: "SYNC_TIMEOUT"; + readonly CANCELLED: "CANCELLED"; + readonly UNSUPPORTED_LEDGER: "UNSUPPORTED_LEDGER"; + readonly LOCALNET_UNAVAILABLE: "LOCALNET_UNAVAILABLE"; + readonly LOCAL_STACK_UNREACHABLE: "LOCAL_STACK_UNREACHABLE"; + readonly AMBIGUOUS_LOCAL_STACKS: "AMBIGUOUS_LOCAL_STACKS"; + readonly UNSUPPORTED_NODE: "UNSUPPORTED_NODE"; + readonly NO_ACCOUNT: "NO_ACCOUNT"; + readonly BLOCKFROST_PROJECT_ID_REQUIRED: "BLOCKFROST_PROJECT_ID_REQUIRED"; + readonly BLOCKFROST_PROJECT_ID_REJECTED: "BLOCKFROST_PROJECT_ID_REJECTED"; + readonly BLOCKFROST_LIMIT_REACHED: "BLOCKFROST_LIMIT_REACHED"; + readonly ENDPOINT_SHUT_DOWN: "ENDPOINT_SHUT_DOWN"; + readonly OTHER_SDK_SET: "OTHER_SDK_SET"; + readonly MIXED_SDK_LAYOUT: "MIXED_SDK_LAYOUT"; + readonly NOT_AN_OFFER: "NOT_AN_OFFER"; + readonly TERMS_MISMATCH: "TERMS_MISMATCH"; + readonly OFFER_EXPIRED: "OFFER_EXPIRED"; + readonly OFFER_COINS_IN_USE: "OFFER_COINS_IN_USE"; + readonly WRONG_PASSPHRASE: "WRONG_PASSPHRASE"; + readonly PASSPHRASE_REQUIRED: "PASSPHRASE_REQUIRED"; + readonly UNKNOWN: "UNKNOWN"; +}; +export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES]; +interface ClassifiedError { + exitCode: number; + errorCode: ErrorCode; +} +export declare function classifyError(err: Error): ClassifiedError; +export declare function humanizeNetworkError(message: string): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/fee-limits` + +```ts +export declare const SPECKS_PER_DUST: bigint; +export interface FeeLimits { + maxFeeSpecks: bigint; + maxPending: number; +} +export declare const DEFAULT_FEE_LIMITS: FeeLimits; +export declare function parseDustAmount(input: string, flag: string): bigint; +export declare function parseFeeLimits(maxFee: string | undefined, maxPending: string | undefined): FeeLimits; +export declare function feeLimitRefusal(feeSpecks: bigint, limits: FeeLimits): string | undefined; +export declare function pendingLimitRefusal(pendingCount: number, limits: FeeLimits): string | undefined; +``` + +## `@kuiralabs/midnight-cli-core/lib/json-output` + +```ts +import { type ErrorCode } from "./exit-codes.ts"; +export declare function writeJsonResult(data: Readonly>): void; +export declare function writeJsonError(err: Error, errorCode: ErrorCode, exitCode: number): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/keystore` + +```ts +export type SecretPurpose = "wallet" | "owner-key" | "keystore-check" | "account-key" | "owner-record" | "owner-roster" | "owner-device" | "private-state-password" | "account-backup" | "owner-devices" | "owner-device-read"; +export interface KeyedSecret { + v: 1; + iv: string; + tag: string; + ciphertext: string; +} +export interface SealedSecret { + v: 1; + kdf: "scrypt"; + n: number; + r: number; + p: number; + salt: string; + iv: string; + tag: string; + ciphertext: string; +} +export declare class WrongPassphraseError extends Error { + readonly code = "WRONG_PASSPHRASE"; + constructor(message?: string); +} +export declare class MalformedSecretError extends Error { + constructor(reason: string); +} +export declare function sealSecret(secret: Uint8Array, passphrase: string, purpose: SecretPurpose): SealedSecret; +export declare function isSealedSecret(value: unknown): value is SealedSecret; +export declare function openSecret(sealed: unknown, passphrase: string, purpose: SecretPurpose): Buffer; +export declare function freshDataKey(): Buffer; +export declare function sealWithKey(key: Uint8Array, secret: Uint8Array, purpose: SecretPurpose): KeyedSecret; +export declare function openWithKey(key: Uint8Array, sealed: unknown, purpose: SecretPurpose): Buffer; +``` + +## `@kuiralabs/midnight-cli-core/lib/network` + +```ts +import type { SdkSet } from "./engine.ts"; +export type NetworkName = "preprod" | "preview" | "stagenet" | "undeployed"; +export declare const LEDGER_9_FORK_VERSION = 2000000n; +export interface NetworkConfig { + indexer: string; + indexerWS: string; + node: string; + proofServer: string; + networkId: string; +} +export declare const SDK_SETS: readonly SdkSet[]; +export declare function defaultSdkSetOf(name: NetworkName): SdkSet; +export declare function networksOnSdkSet(set: SdkSet): NetworkName[]; +export declare function sdkSetOfNetwork(name: NetworkName): SdkSet; +export declare function isValidNetworkName(name: string): name is NetworkName; +export declare function getNetworkConfig(name: NetworkName): NetworkConfig; +export declare function getValidNetworkNames(): readonly string[]; +export declare function detectNetworkFromAddress(address: string): NetworkName | null; +interface TestcontainerPorts { + indexerPort?: number; + nodePort?: number; + proofServerPort?: number; +} +export interface LocalStackPorts { + node: number[]; + indexer: number[]; + proofServer: number[]; +} +export declare function parseLocalStacks(dockerPsOutput: string): LocalStackPorts; +export declare class AmbiguousLocalStacksError extends Error { + readonly code = "AMBIGUOUS_LOCAL_STACKS"; + constructor(found: LocalStackPorts); +} +export interface NeededComponents { + node: boolean; + indexer: boolean; + proofServer: boolean; +} +export declare function pickLocalStack(found: LocalStackPorts, need?: NeededComponents): TestcontainerPorts; +export declare function detectLocalStacks(): LocalStackPorts; +export interface ResolveNetworkConfigOptions { + given?: EndpointOverrides; + detect?: () => LocalStackPorts; + blockfrostProjectId?: string; +} +export declare function resolveNetworkConfig(name: NetworkName, options?: ResolveNetworkConfigOptions): NetworkConfig; +export declare function indexerHttpFromWs(wsUrl: string): string; +export interface EndpointOverrides { + proofServer?: string; + node?: string; + indexerWS?: string; +} +export declare function endpointFlags(e: EndpointOverrides): Record; +export declare function applyEndpointOverrides(config: NetworkConfig, flagOverrides: EndpointOverrides, networkName: NetworkName, configDir?: string): NetworkConfig; +``` + +## `@kuiralabs/midnight-cli-core/lib/network-id` + +```ts +import type { NetworkName } from "./network.ts"; +export type MidnightNetworkId = "preprod" | "preview" | "stagenet" | "undeployed"; +export declare function getNetworkId(networkIdStr: string): MidnightNetworkId; +export declare function networkIdForName(name: NetworkName): MidnightNetworkId; +``` + +## `@kuiralabs/midnight-cli-core/lib/notices` + +```ts +type NoticeSink = (line: string) => void; +export declare function setNoticeSink(next: NoticeSink | null): void; +export declare function notice(line: string): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/offer-envelope` + +```ts +import type { NetworkName } from "./network.ts"; +import { type OfferContents, type SwapTerms } from "./swap-offer.ts"; +export declare const OFFER_ENVELOPE_KIND = "midnight-swap-offer"; +export declare const OFFER_ENVELOPE_VERSION = 1; +export interface OfferEnvelope { + network: NetworkName; + id: string; + terms: SwapTerms; + expiresAt: Date; + tx: string; +} +export declare class OfferExpiredError extends Error { + readonly code = "OFFER_EXPIRED"; + constructor(id: string, expiresAt: Date); +} +export declare function encodeOfferEnvelope(envelope: OfferEnvelope): string; +export declare function decodeOfferEnvelope(text: string): OfferEnvelope; +export declare function assertEnvelopeMatches(envelope: OfferEnvelope, read: OfferContents): void; +export declare function assertOfferUnexpired(envelope: OfferEnvelope, now: Date): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/open-offers` + +```ts +import type { NetworkName } from "./network.ts"; +import type { SwapTerms } from "./swap-offer.ts"; +export interface OpenOffer { + id: string; + terms: SwapTerms; + nullifiers: string[]; + madeAt: Date; + expiresAt: Date; +} +export declare class OfferCoinsInUseError extends Error { + readonly code = "OFFER_COINS_IN_USE"; + readonly offerIds: string[]; + constructor(offerIds: string[]); +} +export declare function openOffersFile(network: NetworkName, walletAddress: string): string; +export declare function readOpenOffers(network: NetworkName, walletAddress: string): OpenOffer[]; +export declare function recordOpenOffer(network: NetworkName, walletAddress: string, offer: OpenOffer): void; +export declare function closeOpenOffers(network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[]; +export declare function assertSpendsNoOfferCoin(open: readonly OpenOffer[], spent: readonly string[], cancelling?: readonly string[]): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/payer` + +```ts +import { type ParsedArgs } from "./argv.ts"; +import { type EndpointOverrides, type NetworkConfig, type NetworkName } from "./network.ts"; +import type { Spinner } from "../ui/spinner.ts"; +import type { CallSdkWarnings } from "./sdk-warnings.ts"; +import type { WalletSession } from "./wallet-session.ts"; +export interface PayingTarget { + network: NetworkName; + networkConfig: NetworkConfig; + endpoints: EndpointOverrides; +} +export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string): PayingTarget; +export interface ServedWallet { + port: number; + stop: () => Promise; +} +export interface PayingFunds { + nightBalance: bigint; + dustBalance: bigint; +} +export interface Payer { + assertCanPay: (target: PayingTarget, wallet: string | undefined, progress: Spinner, signal: AbortSignal | undefined) => Promise; + serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; + connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options?: ConnectOptions) => Promise; +} +export interface ConnectOptions { + shielded?: boolean; +} +export interface CommandContext { + payer?: Payer; +} +export declare class NoPayerError extends Error { + readonly code = "NO_PAYER"; + constructor(command: string); +} +export declare function payerFor(command: string, context: CommandContext | undefined): Payer; +``` + +## `@kuiralabs/midnight-cli-core/lib/phase-tracker` + +```ts +export interface PhaseTiming { + phase: string; + durationMs: number; +} +export interface PhaseTracker { + start(phase: string): void; + complete(): void; + getTimings(): PhaseTiming[]; +} +export interface PhaseCallbacks { + onStart?: (phase: string) => void; + onComplete?: (phase: string, durationMs: number) => void; +} +export declare function createPhaseTracker(callbacks?: PhaseCallbacks): PhaseTracker; +``` + +## `@kuiralabs/midnight-cli-core/lib/prompter` + +```ts +export interface Prompter { + isInteractive(): boolean; + ask(question: string): Promise; + askSecret(question: string): Promise; +} +export declare class PromptBusyError extends Error { + constructor(); +} +export declare function setPrompter(next: Prompter | null): void; +export declare function currentPrompter(): Prompter | null; +``` + +## `@kuiralabs/midnight-cli-core/lib/reader-cache-files` + +```ts +export declare function dustCacheDir(network: string, cacheDir?: string): string; +export declare function getDustCachePath(network: string, pubkeyHex: string, cacheDir?: string): string; +export declare function clearDustDirectCache(network?: string, pubkeyHex?: string, cacheDir?: string): void; +export declare function getShieldedCachePath(network: string, pubkeyHex: string, cacheDir?: string): string; +export declare function clearShieldedDirectCache(network?: string, pubkeyHex?: string, cacheDir?: string): void; +export declare const nativeCheckpointName: (pubkeyHex: string) => string; +export declare function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, cacheDir?: string): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/resolve-network` + +```ts +import { type ParsedArgs } from "./argv.ts"; +import { type NetworkName, type NetworkConfig } from "./network.ts"; +import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV } from "./settings.ts"; +export interface NetworkResolutionContext { + args: ParsedArgs; + configDir?: string; +} +export declare function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName; +export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; +export declare function resolveBlockfrostProjectId(name: NetworkName, configDir?: string, env?: Record): string | undefined; +export declare function resolveNetwork(ctx: NetworkResolutionContext): { + name: NetworkName; + config: NetworkConfig; +}; +``` + +## `@kuiralabs/midnight-cli-core/lib/sdk-errors` + +```ts +export declare function isTransactionRejectedError(err: any): boolean; +export declare function isDustShortage(err: unknown): boolean; +export interface DustShortfall { + needed: bigint; + available: bigint; +} +export declare function withDustShortfall(error: E, shortfall: DustShortfall): E; +export declare function dustShortfallOf(err: unknown): DustShortfall | undefined; +export declare function isDustRelatedError(err: any): boolean; +export declare function isSdkInsufficientFundsError(err: any): boolean; +export declare function isColdStartRace(err: unknown): boolean; +export declare function nodeRefusalOf(err: unknown): string | undefined; +export declare function withNodeReason(err: Error): Error; +``` + +## `@kuiralabs/midnight-cli-core/lib/sdk-layout` + +```ts +export declare function resolvedPackageFolder(from: string, name: string): string | null; +export declare class MixedSdkLayoutError extends Error { + readonly code = "MIXED_SDK_LAYOUT"; + constructor(engine: string, wasmPackage: string, copies: string[]); +} +export declare function assertOneSdkCopy(engine: string, engineDir: string, packages: readonly string[], wasmPackages: readonly string[]): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/sdk-warnings` + +```ts +export type SdkWarningListener = (tag: string, message: string) => void; +export interface CallSdkWarnings { + listen(listener: SdkWarningListener | undefined): () => void; +} +export interface SdkWarningCall { + readonly id: number; + readonly warnings: CallSdkWarnings; +} +export interface SdkWarningRouter { + openCall(): SdkWarningCall; + isListening(): boolean; + route(callId: number | undefined, tag: string, message: string): void; +} +export declare function createSdkWarningRouter(): SdkWarningRouter; +export interface SdkWarningCalls { + run(run: (warnings: CallSdkWarnings) => Promise): Promise; +} +export declare function sdkWarningCallsOn(router: SdkWarningRouter): SdkWarningCalls; +export declare function sdkTransientWarning(value: unknown): { + tag: string; + message: string; +} | null; +``` + +## `@kuiralabs/midnight-cli-core/lib/settings` + +```ts +export declare const PASSPHRASE_ENV = "MN_PASSPHRASE"; +export declare const SEED_ENV = "MN_SEED"; +export declare const NO_LOCAL_DETECT_ENV = "MN_NO_LOCAL_DETECT"; +export declare const DUST_SYNC_BIN_ENV = "MN_DUST_SYNC_BIN"; +export declare const DISABLE_NATIVE_DUST_ENV = "MN_DISABLE_NATIVE_DUST"; +export declare const DUST_COLLAPSE_DISABLE_ENV = "MN_DISABLE_DUST_COLLAPSE"; +export declare const BLOCKFROST_PROJECT_ID_ENV = "MN_BLOCKFROST_PROJECT_ID"; +export declare const SHARED_BLOCKFROST_PROJECT_ID_ENV = "BLOCKFROST_PROJECT_ID"; +export interface Settings { + passphrase: string | undefined; + seed: string | undefined; + isLocalDetectOff: boolean; + dustSyncBin: string | undefined; + isNativeDustOff: boolean; + isDustCollapseOff: boolean; + blockfrostProjectId: string | undefined; + sharedBlockfrostProjectId: string | undefined; +} +export declare function settingsFromEnvironment(env: Record): Settings; +export declare function setSettingsSource(next: (() => Settings) | null): void; +export declare function settings(): Settings; +``` + +## `@kuiralabs/midnight-cli-core/lib/shielded-policy` + +```ts +import type { NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare function networkHasShielded(network: NetworkName): boolean; +export declare function shieldedSyncEnabled(network: NetworkName, force?: boolean): boolean; +export declare function shieldedDisabledReason(network: NetworkName): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/sign-data` + +```ts +export type SignDataEncoding = "hex" | "base64" | "text"; +export declare function decodeSignPayload(data: string, encoding: string): Uint8Array; +export declare function signedMessageBytes(payload: Uint8Array): Uint8Array; +``` + +## `@kuiralabs/midnight-cli-core/lib/sleep` + +```ts +export declare function sleep(ms: number, signal?: AbortSignal): Promise; +export declare function untilCancelled(work: Promise, signal?: AbortSignal): Promise; +``` + +## `@kuiralabs/midnight-cli-core/lib/state-root` + +```ts +export interface HostPaths { + stateRoot: string; + home: string; +} +export declare class NoStateRootError extends Error { + readonly code = "NO_STATE_ROOT"; + constructor(); +} +export declare function setHostPathsSource(next: (() => HostPaths) | null): void; +export declare function hostPaths(): HostPaths; +export declare function stateRoot(): string; +export declare function userHome(): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/swap-offer` + +```ts +export interface SwapLeg { + token: string; + amount: bigint; +} +export interface SwapTerms { + give: SwapLeg; + want: SwapLeg; +} +export interface OfferContents { + id: string; + terms: SwapTerms; + nullifiers: string[]; +} +export declare class NotAnOfferError extends Error { + readonly code = "NOT_AN_OFFER"; + constructor(reason: string, options?: { + cause?: unknown; + }); +} +export declare class TermsMismatchError extends Error { + readonly code = "TERMS_MISMATCH"; + readonly agreed: SwapTerms; + readonly offered: SwapTerms; + constructor(agreed: SwapTerms, offered: SwapTerms); +} +export declare function checkTerms(offered: SwapTerms, agreed: SwapTerms): void; +export declare function describeLeg(leg: SwapLeg): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/tx-serde` + +```ts +export declare function toHex(bytes: Uint8Array): string; +export declare function fromHex(hex: string): Uint8Array; +``` + +## `@kuiralabs/midnight-cli-core/lib/verbose` + +```ts +export type VerboseLog = (phase: string, message: string) => void; +export declare function verboseLine(phase: string, message: string): string; +``` + +## `@kuiralabs/midnight-cli-core/lib/wallet-cache` + +```ts +export interface WalletCacheData { + shielded: string; + unshielded: string; + dust: string; +} +export declare function cacheRootDir(cacheDir?: string): string; +export declare function networkCacheFolder(network: string): string; +export declare const CACHE_KEY_PREFIX_LENGTH = 20; +export declare function cacheKeyOf(addressOrKey: string): string; +export declare function getCachePath(address: string, network: string, cacheDir?: string): string; +export declare function loadWalletCache(address: string, network: string, cacheDir?: string): WalletCacheData | null; +export declare function saveWalletCache(address: string, network: string, facade: { + shielded: { + serializeState(): Promise; + }; + unshielded: { + serializeState(): Promise; + }; + dust: { + serializeState(): Promise; + }; +}, cacheDir?: string, chainId?: string): Promise; +export declare function validateWalletCacheChainId(network: string, currentChainId: string | null, cacheDir?: string): string[]; +export declare function clearWalletCache(address?: string, network?: string, cacheDir?: string): void; +``` + +## `@kuiralabs/midnight-cli-core/lib/wallet-session` + +```ts +import { type OpenedConnector, type TransactionDetail } from "./engine.ts"; +import type { NetworkConfig, NetworkName } from "./network.ts"; +import type { SwapLeg } from "./swap-offer.ts"; +import type { OpenOffer } from "./open-offers.ts"; +export interface WalletAddresses { + unshielded: string; + shielded: string; + shieldedCoinPublicKey: string; + shieldedEncryptionPublicKey: string; + dust: string; +} +export interface WalletBalances { + unshielded: Record; + shielded: Record; + dust: bigint; +} +export interface TokenAmount { + kind: "shielded" | "unshielded"; + type: string; + value: bigint; +} +export interface TokenPayment extends TokenAmount { + recipient: string; +} +export interface SignedData { + data: string; + signature: string; + verifyingKey: string; + scheme: string; +} +export interface WalletSession { + readonly network: NetworkName; + addresses(): Promise; + balances(): Promise; + balanceTransaction(tx: string): Promise; + swap(give: TokenAmount[], take: TokenPayment[]): Promise; + makeOffer(give: SwapLeg, want: SwapLeg): Promise; + takeOffer(tx: string): Promise; + cancelOffers(offers: readonly OpenOffer[]): Promise; + sign(data: string, encoding: "hex" | "base64" | "text"): Promise; + submit(tx: string): Promise; + readTransaction(tx: string, stage: "unsealed" | "sealed"): Promise; + close(): Promise; +} +export interface SessionReopening { + reopen: () => Promise; + onMessage?: (message: string) => void; + delayMs?: number; +} +export declare function sessionOver(network: NetworkName, opened: OpenedConnector, readTransaction: (tx: string, stage: "unsealed" | "sealed") => TransactionDetail[], reopening?: SessionReopening): WalletSession; +export interface OpenWalletSessionOptions { + seed: Buffer; + network: NetworkName; + networkConfig?: NetworkConfig; + forceShielded?: boolean; + dustWaitMs?: number; + signal?: AbortSignal; + onMessage?: (message: string) => void; +} +export declare function openWalletSession(options: OpenWalletSessionOptions): Promise; +``` + +## `@kuiralabs/midnight-cli-core/ui/colors` + +```ts +export declare const MIDNIGHT_BLUE = 17; +export declare const TEAL = 38; +export declare const PURPLE = 99; +export declare const WHITE_CODE = 15; +export declare const DIM_GRAY = 245; +export declare const RED_CODE = 196; +export declare const GREEN_CODE = 40; +export declare const YELLOW_CODE = 226; +export declare function isColorEnabled(): boolean; +export declare function fg(text: string, code: number): string; +export declare function bg(text: string, code: number): string; +export declare function bold(text: string): string; +export declare function dim(text: string): string; +export declare function teal(text: string): string; +export declare function purple(text: string): string; +export declare function red(text: string): string; +export declare function green(text: string): string; +export declare function yellow(text: string): string; +export declare function midnightBlue(text: string): string; +export declare function white(text: string): string; +export declare function gray(text: string): string; +``` + +## `@kuiralabs/midnight-cli-core/ui/format` + +```ts +export declare function header(title: string, width?: number): string; +export declare function divider(width?: number): string; +export declare function keyValue(key: string, value: string, padWidth?: number): string; +export declare function toNight(microNight: bigint): string; +export declare function formatNight(microNight: bigint): string; +export declare function toDust(specks: bigint): string; +export declare function roughDust(specks: bigint, up?: boolean): string; +export declare function formatDust(specks: bigint): string; +export declare function formatAddress(address: string, truncate?: boolean): string; +export declare function box(lines: string[], style?: "light" | "heavy", maxWidth?: number): string; +export declare function errorMessage(error: string, suggestion?: string): string; +export declare function usageMessage(message: string, suggestion?: string): string; +export declare function successMessage(msg: string, txHash?: string): string; +``` + +## `@kuiralabs/midnight-cli-core/ui/spinner` + +```ts +export interface Spinner { + update(message: string): void; + stop(finalMessage?: string): void; + fail(finalMessage?: string): void; + log(line: string): void; + clear(): void; +} +export type ProgressReport = (message: string) => void; +export declare function silentSpinner(report?: ProgressReport): Spinner; +export interface Progress { + start(message: string): Spinner; + silent(): Spinner; + active(): Spinner | null; +} +export declare function createProgress(report?: ProgressReport): Progress; +export declare function start(message: string, report?: ProgressReport, onEnd?: (spinner: Spinner) => void): Spinner; +export declare function trackElapsed(spinner: Spinner, baseMessage: string, promise: Promise): Promise; +export declare function withSpinner(message: string, fn: () => Promise): Promise; +``` + +## `@kuiralabs/midnight-cli-core/ui/terminal-prompter` + +```ts +import type { Readable, Writable } from "node:stream"; +import { type Prompter } from "../lib/prompter.ts"; +export interface TerminalIo { + input?: Readable & { + setRawMode?: (mode: boolean) => unknown; + isTTY?: boolean; + }; + output?: Writable; + isTTY?: boolean; +} +export declare function createTerminalPrompter(io?: TerminalIo): Prompter; +``` diff --git a/packages/engine-beta/api-report.md b/packages/engine-beta/api-report.md new file mode 100644 index 00000000..e0e023b3 --- /dev/null +++ b/packages/engine-beta/api-report.md @@ -0,0 +1,581 @@ +# API report: @kuiralabs/midnight-engine-beta + +Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-engine-beta` + +```ts +import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare const betaEngine: Engine; +``` + +## `@kuiralabs/midnight-engine-beta/addresses` + +```ts +import { ShieldedAddress, UnshieldedAddress } from "@midnightntwrk/wallet-sdk-address-format"; +import type { NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress; +export declare function decodeUnshieldedAddress(address: string, network: NetworkName): UnshieldedAddress; +export declare function assertAddress(address: string, kind: "shielded" | "unshielded", network: NetworkName): void; +``` + +## `@kuiralabs/midnight-engine-beta/airdrop` + +```ts +import { type TransferResult } from "./transfer.ts"; +import type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function airdropNight(params: AirdropParams): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/contract-providers` + +```ts +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function buildStateProvider(networkConfig: NetworkConfig): import("@midnight-ntwrk/midnight-js-indexer-public-data-provider").IndexerPublicDataProvider; +export declare function rawContractState(networkConfig: NetworkConfig, address: string): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/contract-scripts` + +```ts +import type { CallScript, DeployScript, ScriptParts, StateScript } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare const SCRIPT_PACKAGES: readonly [ + "@midnight-ntwrk/compact-js", + "@midnight-ntwrk/compact-runtime", + "@midnight-ntwrk/midnight-js-contracts", + "@midnight-ntwrk/midnight-js-http-client-proof-provider", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider", + "@midnight-ntwrk/midnight-js-level-private-state-provider", + "@midnight-ntwrk/midnight-js-network-id", + "@midnight-ntwrk/midnight-js-node-zk-config-provider", + "@midnight-ntwrk/midnight-js-types", + "@midnight-ntwrk/midnight-js-utils", + "ws" +]; +export declare function packageFolder(name: string): string | null; +export declare const PROVIDER_IMPORTS = "\nimport { Transaction } from '@midnight-ntwrk/midnight-js-types';\nimport { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils';\nimport { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';\nimport { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';\nimport { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';\nimport { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';\n"; +export declare function walletProviderCode(): string; +export declare function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string, parts: ScriptParts): string; +export declare function generateDeployScript(opts: DeployScript, parts: ScriptParts): string; +export declare function generateCallScript(opts: CallScript, parts: ScriptParts): string; +export declare function generateStateScript(opts: StateScript, parts: ScriptParts): string; +``` + +## `@kuiralabs/midnight-engine-beta/dapp-connector` + +```ts +import type { FacadeState, WalletEntry } from "@midnightntwrk/wallet-sdk-facade"; +import { type FacadeBundle } from "./facade.ts"; +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import type { ApprovalOptions } from "@kuiralabs/midnight-cli-core/lib/approval"; +import { type FeeLimits } from "@kuiralabs/midnight-cli-core/lib/fee-limits"; +import { type OpenOffer } from "@kuiralabs/midnight-cli-core/lib/open-offers"; +import { type SegmentResult } from "@kuiralabs/midnight-chain/lib/tx-segments"; +import type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; +export interface DAppConnectorOptions { + bundle: FacadeBundle; + networkConfig: NetworkConfig; + approvalOptions: ApprovalOptions; + feeLimits?: FeeLimits; + openOffers?: () => readonly OpenOffer[]; + callbacks?: DAppConnectorCallbacks; + initialState?: FacadeState; + isCurrent?: (state: FacadeState) => boolean; + dustWaitMs?: number; +} +export type TokenKindsToBalance = "all" | Array<"dust" | "shielded" | "unshielded">; +export { OPERATOR_REJECTED_MESSAGE } from "@kuiralabs/midnight-cli-core/lib/connector-api"; +export type HistoryEntry = { + txHash: string; + txStatus: { + status: "finalized"; + executionStatus: Record; + } | { + status: "pending"; + } | { + status: "discarded"; + }; +}; +export declare function toHistoryEntry(entry: WalletEntry, segments?: readonly SegmentResult[]): HistoryEntry; +export declare function signatureScheme(tag: string): "schnorr_bip340"; +export declare function createDAppConnector(options: DAppConnectorOptions): DAppConnector; +``` + +## `@kuiralabs/midnight-engine-beta/derivation` + +```ts +export declare function deriveShieldedSeed(seedBuffer: Buffer): Uint8Array; +export declare function deriveUnshieldedSeed(seedBuffer: Buffer): Uint8Array; +export declare function deriveDustSeed(seedBuffer: Buffer): Uint8Array; +``` + +## `@kuiralabs/midnight-engine-beta/derive-address` + +```ts +import { ShieldedAddress } from "@midnightntwrk/wallet-sdk-address-format"; +import { type NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare function deriveUnshieldedAddress(seedBuffer: Buffer, networkName: NetworkName, keyIndex?: number): string; +export declare function deriveAllAddresses(seedBuffer: Buffer, keyIndex?: number): Record; +export declare function deriveAllShieldedAddresses(seedBuffer: Buffer): Record; +export declare function deriveShieldedAddressString(seedBuffer: Buffer, networkName: NetworkName): string; +export declare function deriveShieldedAddress(seedBuffer: Buffer): ShieldedAddress; +``` + +## `@kuiralabs/midnight-engine-beta/dust-collapse` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface CollapseOutcome { + state: ledger.DustLocalState; + collapsed: boolean; + rangesCollapsed: number; + reason?: string; +} +export declare function computeForeignRanges(ownedIndices: Iterable, frontier: bigint): Array<[ + bigint, + bigint +]>; +export declare function collapseForeignGenerations(state: ledger.DustLocalState, ownedIndices: Iterable, frontier: bigint): CollapseOutcome; +``` + +## `@kuiralabs/midnight-engine-beta/dust-direct` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface DustRetention { + ownedGenerationIndices: number[]; + generationFrontier: number; +} +export interface DustDirectResult { + balance: bigint; + availableCoins: number; + eventCount: number; + ownedUtxoCount: number; + syncTime: Date; + state: ledger.DustLocalState; + retention: DustRetention; + lastAppliedEventId: number; + partial: boolean; +} +export interface DustDirectOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + timeoutMs?: number; + idleMs?: number; + initialSilenceMs?: number; + signal?: AbortSignal; + initialState?: ledger.DustLocalState; + startFromId?: number; + initialRetention?: DustRetention; + collapse?: boolean; +} +export declare function readDustBalanceDirect(dustSecretKey: ledger.DustSecretKey, indexerWS: string, options?: DustDirectOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/dust-direct-cache` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +import { type DustRetention } from "./dust-direct.ts"; +export interface DustCacheEntry { + state: ledger.DustLocalState; + lastAppliedEventId: number; + retention: DustRetention; +} +export declare function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string; +export declare function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string; +export declare function loadDustCache(network: string, pubkeyHex: string, cacheDir?: string): DustCacheEntry | null; +export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string, retention?: DustRetention): void; +export declare function validateDustCacheChainId(network: string, currentChainId: string | null, cacheDir?: string): string[]; +``` + +## `@kuiralabs/midnight-engine-beta/dust-export` + +```ts +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type WalletDataRepository } from "./wallet-data-repository.ts"; +import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export interface DustExportOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + signal?: AbortSignal; + repository?: WalletDataRepository; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + log?: VerboseLog; +} +export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options?: DustExportOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/dust-register` + +```ts +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/dust-sync-native` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; +export interface SidecarCheckpoint { + dust_state: string; + last_applied_event_id: number; + owned_generation_indices: number[]; + generation_frontier: number; + balance: string; + available_coins: number; + events_applied: number; + partial: boolean; +} +interface NativeFetchOptions { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + cacheDir?: string; +} +export declare function resolveSidecarBinary(): string | null; +export declare function platformPackageBinary(fromUrl: string): string | null; +export declare function nativeDustSyncAvailable(): boolean; +export declare function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): "existing" | "seed" | "fresh"; +export declare function runDustSyncNative(seed: Buffer, network: NetworkConfig, opts: NativeFetchOptions): Promise; +export declare function adaptResult(cp: SidecarCheckpoint): DustDirectResult; +``` + +## `@kuiralabs/midnight-engine-beta/dust-wallet` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +import { DustWallet as SdkDustWallet } from "@midnightntwrk/wallet-sdk-dust-wallet"; +import { Transacting } from "@midnightntwrk/wallet-sdk-dust-wallet/v1"; +type SdkTransacting = Transacting.TransactingCapabilityImplementation; +type RecipeArguments = Parameters; +type Recipe = ReturnType; +export declare class ConvergingDustTransacting extends Transacting.TransactingCapabilityImplementation { + #private; + computeBalancingRecipe(...args: RecipeArguments): Recipe; +} +export declare function DustWallet(configuration: Parameters[0]): ReturnType; +``` + +## `@kuiralabs/midnight-engine-beta/facade` + +```ts +import { type UnshieldedKeystore } from "@midnightntwrk/wallet-sdk-unshielded-wallet"; +import { WalletFacade, type FacadeState } from "@midnightntwrk/wallet-sdk-facade"; +import * as ledger from "@midnightntwrk/ledger-v9"; +import * as rx from "rxjs"; +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; +import { type DustCacheEntry } from "./dust-direct-cache.ts"; +import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +export type SyncMode = "full" | "lite" | "no-dust"; +export interface WalletSecretKeys { + shieldedSecretKeys: ledger.ZswapSecretKeys; + dustSecretKey: ledger.DustSecretKey; +} +export interface FacadeBundle { + facade: WalletFacade; + keystore: UnshieldedKeystore; + secretKeys: WalletSecretKeys; + keepAlive?: rx.Subscription; + restoredFromCache?: boolean; + indexerHttpUrl?: string; + indexerWsUrl?: string; + emptyStreams?: EmptyStreams; +} +export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, cache?: WalletCacheData | null, log?: VerboseLog): Promise; +export interface FacadeDustSnapshot { + publicKey: { + publicKey: string; + }; + state: string; + protocolVersion: string; + networkId: string; + offset?: string; +} +export declare function overlayDustDirectSnapshot(dustSnapshotJson: string, direct: Pick): string; +export interface EmptyStreams { + readonly zswap: boolean; + readonly dust: boolean; +} +export declare const NO_EMPTY_STREAMS: EmptyStreams; +export declare function isFacadeSynced(state: FacadeState, syncMode?: SyncMode, empty?: EmptyStreams): boolean; +export interface SyncOptions { + onProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + timeoutMs?: number; + syncMode?: SyncMode; + requireStrictSync?: boolean; + log?: VerboseLog; + signal?: AbortSignal; +} +export declare function startAndSyncFacade(bundle: FacadeBundle, options?: SyncOptions): Promise; +export declare class StaleCacheError extends Error { + readonly code = "STALE_CACHE"; + constructor(detail: string); +} +export declare function detectStaleCache(state: FacadeState): string | undefined; +export declare function waitForLiteSyncedState(bundle: FacadeBundle): Promise; +export declare function hasDustAvailable(state: FacadeState): boolean; +export declare function waitForDustAvailable(bundle: FacadeBundle, timeoutMs?: number, signal?: AbortSignal): Promise; +export declare function quickSync(bundle: FacadeBundle, syncMode?: SyncMode): Promise; +export declare function stopFacade(bundle: FacadeBundle): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/fee-only-check` + +```ts +import { Transaction, type Bindingish, type Proofish, type SignatureEnabled, type SignatureVerifyingKey } from "@midnightntwrk/ledger-v9"; +export type DAppTxStage = "unsealed" | "sealed"; +export type FeeCheckTransaction = Transaction; +export declare function readDAppTransaction(bytes: Uint8Array, stage: DAppTxStage): FeeCheckTransaction; +export declare function segmentsOf(tx: FeeCheckTransaction): Set; +export declare function expiredIntents(tx: FeeCheckTransaction, now: Date): Array<{ + segment: number; + ttl: Date; +}>; +export interface UnshieldedInputRef { + where: string; + owner: SignatureVerifyingKey; + signed: boolean; +} +export declare function unshieldedInputs(tx: FeeCheckTransaction): UnshieldedInputRef[]; +export declare function feeOnlyRefusals(tx: FeeCheckTransaction, walletKey: SignatureVerifyingKey): string[]; +``` + +## `@kuiralabs/midnight-engine-beta/index` + +```ts +import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare const betaEngine: Engine; +``` + +## `@kuiralabs/midnight-engine-beta/ledger-parameters` + +```ts +import type { BlockLimits } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function blockLimitsOf(parametersHex: string): BlockLimits; +``` + +## `@kuiralabs/midnight-engine-beta/offer-reader` + +```ts +import { type OfferContents } from "@kuiralabs/midnight-cli-core/lib/swap-offer"; +export declare function readOffer(txHex: string): OfferContents; +export declare function spentNullifiers(txHex: string): string[]; +``` + +## `@kuiralabs/midnight-engine-beta/raw-state` + +```ts +import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; +interface StateValueLike { + type(): "null" | "cell" | "map" | "array" | "boundedMerkleTree"; + asCell(): { + value: Uint8Array[]; + }; + asMap(): { + keys(): unknown[]; + } | undefined; + asArray(): StateValueLike[] | undefined; + asBoundedMerkleTree(): { + height: number; + root(): { + value: Uint8Array[]; + } | undefined; + } | undefined; +} +export declare function describeRawState(state: StateValueLike): RawStateValue; +``` + +## `@kuiralabs/midnight-engine-beta/shielded-direct` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface ShieldedDirectResult { + balance: bigint; + availableCoins: number; + tokens: ReadonlyMap; + eventCount: number; + state: ledger.ZswapLocalState; + lastAppliedEventId: number; + partial: boolean; +} +export interface ShieldedDirectOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + onCheckpoint?: (state: ledger.ZswapLocalState, lastAppliedEventId: number) => void; + timeoutMs?: number; + idleMs?: number; + initialSilenceMs?: number; + signal?: AbortSignal; + initialState?: ledger.ZswapLocalState; + startFromId?: number; +} +export declare function readShieldedBalanceDirect(secretKeys: ledger.ZswapSecretKeys, indexerWS: string, options?: ShieldedDirectOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/shielded-direct-cache` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface ShieldedCacheEntry { + state: ledger.ZswapLocalState; + lastAppliedEventId: number; +} +export declare function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string; +export declare function loadShieldedCache(network: string, pubkeyHex: string, cacheDir?: string, expectedChainId?: string): ShieldedCacheEntry | null; +export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string): void; +export type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options?: ShieldedCachedOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/sign-recipe` + +```ts +import type { Signature } from "@midnightntwrk/ledger-v9"; +import type { BalancingRecipe, WalletFacade } from "@midnightntwrk/wallet-sdk-facade"; +import { type FeeCheckTransaction } from "./fee-only-check.ts"; +export type SignSegment = (data: Uint8Array) => Promise; +export type UnshieldedSignatures = "none" | "all" | "some"; +export declare function unshieldedSignatures(tx: FeeCheckTransaction): UnshieldedSignatures; +export declare class PartlySignedTransactionError extends Error { + constructor(); +} +export declare class SignedTransactionNeedsUnshieldedError extends Error { + constructor(segments: number[]); +} +export declare function unshieldedImbalanceSegments(tx: FeeCheckTransaction): number[]; +export declare function assertSignable(tx: FeeCheckTransaction, balancesUnshielded: boolean): void; +export declare function signRecipe(facade: WalletFacade, recipe: BalancingRecipe, signSegment: SignSegment): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/transfer` + +```ts +import { UnshieldedAddress, type DustAddress } from "@midnightntwrk/wallet-sdk-address-format"; +import { type FacadeState, type UtxoWithMeta } from "@midnightntwrk/wallet-sdk-facade"; +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type FacadeBundle } from "./facade.ts"; +export declare function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress; +export { isDustRelatedError, isSdkInsufficientFundsError } from "@kuiralabs/midnight-cli-core/lib/sdk-errors"; +import type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function registerNightUtxos(bundle: FacadeBundle, nightUtxos: readonly UtxoWithMeta[], dustReceiverAddress: DustAddress, onStatus?: (status: string) => void): Promise; +export declare function ensureDust(bundle: FacadeBundle, onStatus?: (status: string) => void, syncedState?: FacadeState): Promise; +export declare function executeTransfer(params: TransferParams): Promise; +``` + +## `@kuiralabs/midnight-engine-beta/tx-inspect` + +```ts +import type { TransactionDetail } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function inspectTxHex(txHex: string, stage: "unsealed" | "sealed"): TransactionDetail[]; +``` + +## `@kuiralabs/midnight-engine-beta/wallet` + +```ts +import type { EngineWallet } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare const betaWallet: EngineWallet; +``` + +## `@kuiralabs/midnight-engine-beta/wallet-data-repository` + +```ts +import { Buffer } from "node:buffer"; +import * as ledger from "@midnightntwrk/ledger-v9"; +import type { NetworkConfig, NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type FacadeState } from "@midnightntwrk/wallet-sdk-facade"; +import { type FacadeBundle, type SyncMode } from "./facade.ts"; +import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; +import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subscription"; +import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; +import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; +import type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +export interface DustView extends DustBalance { + state: ledger.DustLocalState; +} +export interface FacadeLease { + bundle: FacadeBundle; + state: FacadeState; +} +export interface InvalidationScope { + network: NetworkConfig; + seed?: Buffer; + address?: string; + kinds?: ReadonlyArray<"dust" | "unshielded" | "facade">; +} +export interface FacadeOptions extends ReadOptions { + syncMode?: SyncMode; + requireStrictSync?: boolean; + readOnly?: boolean; + skipAutoSave?: boolean; + syncTimeoutMs?: number; + onSyncProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + onSyncWarning?: (tag: string, message: string) => void; + noPrime?: boolean; +} +export type TipFingerprint = string; +export interface RepoDeps { + now?: () => number; + fetchTip?: (network: NetworkConfig, signal?: AbortSignal) => Promise; + fetchUnshielded?: (address: string, network: NetworkConfig, onProgress?: (current: number, highest: number) => void, signal?: AbortSignal) => Promise; + fetchDust?: (seed: Buffer, network: NetworkConfig, opts: { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + cacheDir?: string; + log?: VerboseLog; + }) => Promise; + fetchChainId?: (nodeWsUrl: string) => Promise; + fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; + fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; + cacheDir?: string; +} +export declare class WalletDataRepository { + private readonly now; + private readonly fetchTip; + private readonly fetchUnshielded; + private readonly fetchDust; + private readonly fetchChainId; + private readonly fetchEventTip; + private readonly fetchProtocolVersion; + private readonly cacheDir; + private readonly dustMemo; + private readonly unshieldedMemo; + private readonly tipMemo; + constructor(deps?: RepoDeps); + private keepCachesOfThisIndexer; + walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise; + private freshWalletOnDustCheckpoint; + dust(seed: Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; + unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; + withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts?: FacadeOptions): Promise; + invalidate(scope: InvalidationScope): void; + resetTipMemo(): void; + private tryMemo; + private memoize; + private getTip; + private deleteByPrefix; +} +export declare function defaultRepository(): WalletDataRepository; +export declare function setDefaultRepository(repo: WalletDataRepository | null): void; +``` diff --git a/packages/engine-rc/api-report.md b/packages/engine-rc/api-report.md new file mode 100644 index 00000000..f9ef292a --- /dev/null +++ b/packages/engine-rc/api-report.md @@ -0,0 +1,591 @@ +# API report: @kuiralabs/midnight-engine-rc + +Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-engine-rc` + +```ts +import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare const rcEngine: Engine; +``` + +## `@kuiralabs/midnight-engine-rc/addresses` + +```ts +import { ShieldedAddress, UnshieldedAddress } from "@midnightntwrk/wallet-sdk/address-format"; +import type { NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress; +export declare function decodeUnshieldedAddress(address: string, network: NetworkName): UnshieldedAddress; +export declare function assertAddress(address: string, kind: "shielded" | "unshielded", network: NetworkName): void; +``` + +## `@kuiralabs/midnight-engine-rc/airdrop` + +```ts +import { type TransferResult } from "./transfer.ts"; +import type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function airdropNight(params: AirdropParams): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/contract-providers` + +```ts +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function buildStateProvider(networkConfig: NetworkConfig): import("@midnight-ntwrk/midnight-js-indexer-public-data-provider").IndexerPublicDataProvider; +export declare function rawContractState(networkConfig: NetworkConfig, address: string): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/contract-scripts` + +```ts +import type { CallScript, DeployScript, ScriptParts, StateScript } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare const SCRIPT_PACKAGES: readonly [ + "@midnight-ntwrk/compact-js", + "@midnight-ntwrk/compact-runtime", + "@midnight-ntwrk/midnight-js-contracts", + "@midnight-ntwrk/midnight-js-http-client-proof-provider", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider", + "@midnight-ntwrk/midnight-js-level-private-state-provider", + "@midnight-ntwrk/midnight-js-network-id", + "@midnight-ntwrk/midnight-js-node-zk-config-provider", + "@midnight-ntwrk/midnight-js-types", + "@midnight-ntwrk/midnight-js-utils", + "ws" +]; +export declare function packageFolder(name: string): string | null; +export declare const PROVIDER_IMPORTS = "\nimport { createWalletProvider, createMidnightProvider, Transaction } from '@midnight-ntwrk/midnight-js-types';\nimport { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils';\nimport { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';\nimport { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';\nimport { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';\nimport { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';\n"; +export declare function walletProviderCode(): string; +export declare function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string, parts: ScriptParts): string; +export declare function generateDeployScript(opts: DeployScript, parts: ScriptParts): string; +export declare function generateCallScript(opts: CallScript, parts: ScriptParts): string; +export declare function generateStateScript(opts: StateScript, parts: ScriptParts): string; +``` + +## `@kuiralabs/midnight-engine-rc/dapp-connector` + +```ts +import type { FacadeState, WalletEntry } from "@midnightntwrk/wallet-sdk/facade"; +import { type FacadeBundle } from "./facade.ts"; +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import type { ApprovalOptions } from "@kuiralabs/midnight-cli-core/lib/approval"; +import { type FeeLimits } from "@kuiralabs/midnight-cli-core/lib/fee-limits"; +import { type OpenOffer } from "@kuiralabs/midnight-cli-core/lib/open-offers"; +import { type SegmentResult } from "@kuiralabs/midnight-chain/lib/tx-segments"; +import type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; +export interface DAppConnectorOptions { + bundle: FacadeBundle; + networkConfig: NetworkConfig; + approvalOptions: ApprovalOptions; + feeLimits?: FeeLimits; + openOffers?: () => readonly OpenOffer[]; + callbacks?: DAppConnectorCallbacks; + initialState?: FacadeState; + isCurrent?: (state: FacadeState) => boolean; + dustWaitMs?: number; +} +export type TokenKindsToBalance = "all" | Array<"dust" | "shielded" | "unshielded">; +export { OPERATOR_REJECTED_MESSAGE } from "@kuiralabs/midnight-cli-core/lib/connector-api"; +export type HistoryEntry = { + txHash: string; + txStatus: { + status: "finalized"; + executionStatus: Record; + } | { + status: "pending"; + } | { + status: "discarded"; + }; +}; +export declare function toHistoryEntry(entry: WalletEntry, segments?: readonly SegmentResult[]): HistoryEntry; +export declare function signatureScheme(tag: string): "schnorr_bip340"; +export declare function createDAppConnector(options: DAppConnectorOptions): DAppConnector; +``` + +## `@kuiralabs/midnight-engine-rc/derivation` + +```ts +export declare function deriveShieldedSeed(seedBuffer: Buffer): Uint8Array; +export declare function deriveUnshieldedSeed(seedBuffer: Buffer): Uint8Array; +export declare function deriveDustSeed(seedBuffer: Buffer): Uint8Array; +``` + +## `@kuiralabs/midnight-engine-rc/derive-address` + +```ts +import { ShieldedAddress } from "@midnightntwrk/wallet-sdk/address-format"; +import { type NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +export declare function deriveUnshieldedAddress(seedBuffer: Buffer, networkName: NetworkName, keyIndex?: number): string; +export declare function deriveAllAddresses(seedBuffer: Buffer, keyIndex?: number): Record; +export declare function deriveAllShieldedAddresses(seedBuffer: Buffer): Record; +export declare function deriveShieldedAddressString(seedBuffer: Buffer, networkName: NetworkName): string; +export declare function deriveShieldedAddress(seedBuffer: Buffer): ShieldedAddress; +``` + +## `@kuiralabs/midnight-engine-rc/dust-collapse` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface CollapseOutcome { + state: ledger.DustLocalState; + collapsed: boolean; + rangesCollapsed: number; + reason?: string; +} +export declare function computeForeignRanges(ownedIndices: Iterable, frontier: bigint): Array<[ + bigint, + bigint +]>; +export declare function collapseForeignGenerations(state: ledger.DustLocalState, ownedIndices: Iterable, frontier: bigint): CollapseOutcome; +``` + +## `@kuiralabs/midnight-engine-rc/dust-direct` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface DustRetention { + ownedGenerationIndices: number[]; + generationFrontier: number; +} +export interface DustDirectResult { + balance: bigint; + availableCoins: number; + eventCount: number; + ownedUtxoCount: number; + syncTime: Date; + state: ledger.DustLocalState; + retention: DustRetention; + lastAppliedEventId: number; + partial: boolean; +} +export interface DustDirectOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + timeoutMs?: number; + idleMs?: number; + initialSilenceMs?: number; + signal?: AbortSignal; + initialState?: ledger.DustLocalState; + startFromId?: number; + initialRetention?: DustRetention; + collapse?: boolean; +} +export declare function readDustBalanceDirect(dustSecretKey: ledger.DustSecretKey, indexerWS: string, options?: DustDirectOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/dust-direct-cache` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +import { type DustRetention } from "./dust-direct.ts"; +export interface DustCacheEntry { + state: ledger.DustLocalState; + lastAppliedEventId: number; + retention: DustRetention; +} +export declare function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string; +export declare function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string; +export declare function loadDustCache(network: string, pubkeyHex: string, cacheDir?: string): DustCacheEntry | null; +export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string, retention?: DustRetention): void; +export declare function validateDustCacheChainId(network: string, currentChainId: string | null, cacheDir?: string): string[]; +``` + +## `@kuiralabs/midnight-engine-rc/dust-export` + +```ts +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type WalletDataRepository } from "./wallet-data-repository.ts"; +import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export interface DustExportOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + signal?: AbortSignal; + repository?: WalletDataRepository; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + log?: VerboseLog; +} +export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options?: DustExportOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/dust-register` + +```ts +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/dust-sync-native` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; +export interface SidecarCheckpoint { + dust_state: string; + last_applied_event_id: number; + owned_generation_indices: number[]; + generation_frontier: number; + balance: string; + available_coins: number; + events_applied: number; + partial: boolean; +} +interface NativeFetchOptions { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + cacheDir?: string; +} +export declare function resolveSidecarBinary(): string | null; +export declare function platformPackageBinary(fromUrl: string): string | null; +export declare function nativeDustSyncAvailable(): boolean; +export declare function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): "existing" | "seed" | "fresh"; +export declare function runDustSyncNative(seed: Buffer, network: NetworkConfig, opts: NativeFetchOptions): Promise; +export declare function adaptResult(cp: SidecarCheckpoint): DustDirectResult; +``` + +## `@kuiralabs/midnight-engine-rc/dust-wallet` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +import { DustWallet as SdkDustWallet } from "@midnightntwrk/wallet-sdk/dust"; +import { Transacting } from "@midnightntwrk/wallet-sdk/dust/v2"; +type SdkTransacting = Transacting.TransactingCapabilityImplementation; +type RecipeArguments = Parameters; +type Recipe = ReturnType; +export declare class ConvergingDustTransacting extends Transacting.TransactingCapabilityImplementation { + #private; + computeBalancingRecipe(...args: RecipeArguments): Recipe; +} +export declare function DustWallet(configuration: Parameters[0]): ReturnType; +``` + +## `@kuiralabs/midnight-engine-rc/facade` + +```ts +import { type UnshieldedKeystore } from "@midnightntwrk/wallet-sdk/unshielded"; +import { WalletFacade, type FacadeState } from "@midnightntwrk/wallet-sdk/facade"; +import { type WalletSeeds } from "@midnightntwrk/wallet-sdk/hd"; +import * as rx from "rxjs"; +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; +import { type DustCacheEntry } from "./dust-direct-cache.ts"; +import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +export type SyncMode = "full" | "lite" | "no-dust"; +interface SeedStartable { + startWithSeed(seed: Uint8Array): Promise; +} +export interface FacadeBundle { + facade: WalletFacade; + keystore: UnshieldedKeystore; + seeds: WalletSeeds; + seedStartable: { + shielded: SeedStartable; + dust: SeedStartable; + }; + keepAlive?: rx.Subscription; + restoredFromCache?: boolean; + indexerHttpUrl?: string; + indexerWsUrl?: string; + emptyStreams?: EmptyStreams; +} +export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, cache?: WalletCacheData | null, log?: VerboseLog): Promise; +export interface FacadeDustSnapshot { + publicKey: { + publicKey: string; + }; + state: string; + protocolVersion: string; + networkId: string; + offset?: string; +} +export declare function overlayDustDirectSnapshot(dustSnapshotJson: string, direct: Pick): string; +export interface EmptyStreams { + readonly zswap: boolean; + readonly dust: boolean; +} +export declare const NO_EMPTY_STREAMS: EmptyStreams; +export declare function isFacadeSynced(state: FacadeState, syncMode?: SyncMode, empty?: EmptyStreams): boolean; +export interface SyncOptions { + onProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + timeoutMs?: number; + syncMode?: SyncMode; + requireStrictSync?: boolean; + log?: VerboseLog; + signal?: AbortSignal; +} +export declare function startAndSyncFacade(bundle: FacadeBundle, options?: SyncOptions): Promise; +export declare class StaleCacheError extends Error { + readonly code = "STALE_CACHE"; + constructor(detail: string); +} +export declare function detectStaleCache(state: FacadeState): string | undefined; +export declare function waitForLiteSyncedState(bundle: FacadeBundle): Promise; +export declare function hasDustAvailable(state: FacadeState): boolean; +export declare function waitForDustAvailable(bundle: FacadeBundle, timeoutMs?: number, signal?: AbortSignal): Promise; +export declare function quickSync(bundle: FacadeBundle, syncMode?: SyncMode): Promise; +export declare function stopFacade(bundle: FacadeBundle): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/fee-only-check` + +```ts +import { Transaction, type Bindingish, type Proofish, type SignatureEnabled, type SignatureVerifyingKey } from "@midnightntwrk/ledger-v9"; +export type DAppTxStage = "unsealed" | "sealed"; +export type FeeCheckTransaction = Transaction; +export declare function readDAppTransaction(bytes: Uint8Array, stage: DAppTxStage): FeeCheckTransaction; +export declare function segmentsOf(tx: FeeCheckTransaction): Set; +export declare function expiredIntents(tx: FeeCheckTransaction, now: Date): Array<{ + segment: number; + ttl: Date; +}>; +export interface UnshieldedInputRef { + where: string; + owner: SignatureVerifyingKey; + signed: boolean; +} +export declare function unshieldedInputs(tx: FeeCheckTransaction): UnshieldedInputRef[]; +export declare function feeOnlyRefusals(tx: FeeCheckTransaction, walletKey: SignatureVerifyingKey): string[]; +``` + +## `@kuiralabs/midnight-engine-rc/fork-schedule` + +```ts +import { ProtocolVersion } from "@midnightntwrk/wallet-sdk"; +export declare const FORK_SCHEDULE: ProtocolVersion.ForkSchedule; +``` + +## `@kuiralabs/midnight-engine-rc/index` + +```ts +import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare const rcEngine: Engine; +``` + +## `@kuiralabs/midnight-engine-rc/ledger-parameters` + +```ts +import type { BlockLimits } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function blockLimitsOf(parametersHex: string): BlockLimits; +``` + +## `@kuiralabs/midnight-engine-rc/offer-reader` + +```ts +import { type OfferContents } from "@kuiralabs/midnight-cli-core/lib/swap-offer"; +export declare function readOffer(txHex: string): OfferContents; +export declare function spentNullifiers(txHex: string): string[]; +``` + +## `@kuiralabs/midnight-engine-rc/raw-state` + +```ts +import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; +interface StateValueLike { + type(): "null" | "cell" | "map" | "array" | "boundedMerkleTree"; + asCell(): { + value: Uint8Array[]; + }; + asMap(): { + keys(): unknown[]; + } | undefined; + asArray(): StateValueLike[] | undefined; + asBoundedMerkleTree(): { + height: number; + root(): { + value: Uint8Array[]; + } | undefined; + } | undefined; +} +export declare function describeRawState(state: StateValueLike): RawStateValue; +``` + +## `@kuiralabs/midnight-engine-rc/shielded-direct` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface ShieldedDirectResult { + balance: bigint; + availableCoins: number; + tokens: ReadonlyMap; + eventCount: number; + state: ledger.ZswapLocalState; + lastAppliedEventId: number; + partial: boolean; +} +export interface ShieldedDirectOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + onCheckpoint?: (state: ledger.ZswapLocalState, lastAppliedEventId: number) => void; + timeoutMs?: number; + idleMs?: number; + initialSilenceMs?: number; + signal?: AbortSignal; + initialState?: ledger.ZswapLocalState; + startFromId?: number; +} +export declare function readShieldedBalanceDirect(secretKeys: ledger.ZswapSecretKeys, indexerWS: string, options?: ShieldedDirectOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/shielded-direct-cache` + +```ts +import * as ledger from "@midnightntwrk/ledger-v9"; +export interface ShieldedCacheEntry { + state: ledger.ZswapLocalState; + lastAppliedEventId: number; +} +export declare function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string; +export declare function loadShieldedCache(network: string, pubkeyHex: string, cacheDir?: string, expectedChainId?: string): ShieldedCacheEntry | null; +export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string): void; +export type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options?: ShieldedCachedOptions): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/sign-recipe` + +```ts +import type { Signature } from "@midnightntwrk/ledger-v9"; +import type { BalancingRecipe, WalletFacade } from "@midnightntwrk/wallet-sdk/facade"; +import { type FeeCheckTransaction } from "./fee-only-check.ts"; +export type SignSegment = (data: Uint8Array) => Promise; +export type UnshieldedSignatures = "none" | "all" | "some"; +export declare function unshieldedSignatures(tx: FeeCheckTransaction): UnshieldedSignatures; +export declare class PartlySignedTransactionError extends Error { + constructor(); +} +export declare class SignedTransactionNeedsUnshieldedError extends Error { + constructor(segments: number[]); +} +export declare function unshieldedImbalanceSegments(tx: FeeCheckTransaction): number[]; +export declare function assertSignable(tx: FeeCheckTransaction, balancesUnshielded: boolean): void; +export declare function signRecipe(facade: WalletFacade, recipe: BalancingRecipe, signSegment: SignSegment): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/transfer` + +```ts +import { UnshieldedAddress, type DustAddress } from "@midnightntwrk/wallet-sdk/address-format"; +import { type FacadeState, type UtxoWithMeta } from "@midnightntwrk/wallet-sdk/facade"; +import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type FacadeBundle } from "./facade.ts"; +export declare function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress; +export { isDustRelatedError, isSdkInsufficientFundsError } from "@kuiralabs/midnight-cli-core/lib/sdk-errors"; +import type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function registerNightUtxos(bundle: FacadeBundle, nightUtxos: readonly UtxoWithMeta[], dustReceiverAddress: DustAddress, onStatus?: (status: string) => void): Promise; +export declare function ensureDust(bundle: FacadeBundle, onStatus?: (status: string) => void, syncedState?: FacadeState): Promise; +export declare function executeTransfer(params: TransferParams): Promise; +``` + +## `@kuiralabs/midnight-engine-rc/tx-inspect` + +```ts +import type { TransactionDetail } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare function inspectTxHex(txHex: string, stage: "unsealed" | "sealed"): TransactionDetail[]; +``` + +## `@kuiralabs/midnight-engine-rc/wallet` + +```ts +import type { EngineWallet } from "@kuiralabs/midnight-cli-core/lib/engine"; +export declare const rcWallet: EngineWallet; +``` + +## `@kuiralabs/midnight-engine-rc/wallet-data-repository` + +```ts +import { Buffer } from "node:buffer"; +import * as ledger from "@midnightntwrk/ledger-v9"; +import type { NetworkConfig, NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; +import { type FacadeState } from "@midnightntwrk/wallet-sdk/facade"; +import { type FacadeBundle, type SyncMode } from "./facade.ts"; +import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; +import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subscription"; +import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; +import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; +import type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +export interface DustView extends DustBalance { + state: ledger.DustLocalState; +} +export interface FacadeLease { + bundle: FacadeBundle; + state: FacadeState; +} +export interface InvalidationScope { + network: NetworkConfig; + seed?: Buffer; + address?: string; + kinds?: ReadonlyArray<"dust" | "unshielded" | "facade">; +} +export interface FacadeOptions extends ReadOptions { + syncMode?: SyncMode; + requireStrictSync?: boolean; + readOnly?: boolean; + skipAutoSave?: boolean; + syncTimeoutMs?: number; + onSyncProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + onSyncWarning?: (tag: string, message: string) => void; + noPrime?: boolean; +} +export type TipFingerprint = string; +export interface RepoDeps { + now?: () => number; + fetchTip?: (network: NetworkConfig, signal?: AbortSignal) => Promise; + fetchUnshielded?: (address: string, network: NetworkConfig, onProgress?: (current: number, highest: number) => void, signal?: AbortSignal) => Promise; + fetchDust?: (seed: Buffer, network: NetworkConfig, opts: { + startFromId: number; + initialState?: ledger.DustLocalState; + initialRetention?: DustRetention; + signal?: AbortSignal; + onProgress?: (applied: number, max: number) => void; + onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; + cacheDir?: string; + log?: VerboseLog; + }) => Promise; + fetchChainId?: (nodeWsUrl: string) => Promise; + fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; + fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; + cacheDir?: string; +} +export declare class WalletDataRepository { + private readonly now; + private readonly fetchTip; + private readonly fetchUnshielded; + private readonly fetchDust; + private readonly fetchChainId; + private readonly fetchEventTip; + private readonly fetchProtocolVersion; + private readonly cacheDir; + private readonly dustMemo; + private readonly unshieldedMemo; + private readonly tipMemo; + constructor(deps?: RepoDeps); + private keepCachesOfThisIndexer; + walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise; + private freshWalletOnDustCheckpoint; + dust(seed: Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; + unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; + withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts?: FacadeOptions): Promise; + invalidate(scope: InvalidationScope): void; + resetTipMemo(): void; + private tryMemo; + private memoize; + private getTip; + private deleteByPrefix; +} +export declare function defaultRepository(): WalletDataRepository; +export declare function setDefaultRepository(repo: WalletDataRepository | null): void; +``` diff --git a/scripts/api-report.d.mts b/scripts/api-report.d.mts new file mode 100644 index 00000000..2fd846a7 --- /dev/null +++ b/scripts/api-report.d.mts @@ -0,0 +1,7 @@ +// Types for what scripts/api-report.mjs exports when imported. +/** The public packages, by folder under packages/. */ +export const PUBLIC_PACKAGES: readonly string[]; +/** The report's path for the package in `dir` (a folder under packages/). */ +export function reportPath(dir: string): string; +/** The report of the package in `dir` (a folder under packages/). */ +export function apiReport(dir: string): string; diff --git a/scripts/api-report.mjs b/scripts/api-report.mjs new file mode 100644 index 00000000..808478fe --- /dev/null +++ b/scripts/api-report.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +// Each public package's API, as a report checked in beside it: every module a +// program can import through the package's exports map, with the declarations +// it exports (functions, types, classes, constants and their signatures), as +// TypeScript emits them, without comments. A change to an export shows in the +// report's diff, and the suite fails until the report is written again. +// +// Usage: +// node scripts/api-report.mjs write write each package's api-report.md +// node scripts/api-report.mjs check exit 1 when a report differs from the code +// Imported, it exports PUBLIC_PACKAGES and apiReport. + +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import ts from 'typescript'; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +/** The public packages, by folder under packages/. */ +export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta']; + +/** The report's path for the package in `dir` (a folder under packages/). */ +export function reportPath(dir) { + return join(ROOT, 'packages', dir, 'api-report.md'); +} + +/** + * The modules the exports map lets a program import, as [subpath, source file] + * pairs: a subpath pattern (`./*`) stands for every source module it matches. + */ +function entryModules(pkgDir, srcFiles) { + const pkg = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')); + const entries = new Map(); + for (const [subpath, target] of Object.entries(pkg.exports ?? {})) { + const source = typeof target === 'string' ? target : target['midnight-cli-source']; + if (typeof source !== 'string') throw new Error(`${pkg.name}: export ${subpath} names no source module`); + if (!subpath.includes('*')) { + entries.set(subpath, join(pkgDir, source)); + continue; + } + const [before, after] = source.split('*'); + const prefix = join(pkgDir, before); + for (const file of srcFiles) { + if (!file.startsWith(prefix) || !file.endsWith(after)) continue; + const stem = file.slice(prefix.length, file.length - after.length); + entries.set(subpath.replace('*', stem), file); + } + } + return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); +} + +/** The package's declarations, emitted in memory, by source file. */ +function emitDeclarations(pkgDir) { + const configPath = join(pkgDir, 'tsconfig.build.json'); + const parsed = ts.getParsedCommandLineOfConfigFile(configPath, { noEmit: false, emitDeclarationOnly: true, declaration: true, declarationMap: false, sourceMap: false }, { + ...ts.sys, + onUnRecoverableConfigFileDiagnostic: (d) => { throw new Error(ts.flattenDiagnosticMessageText(d.messageText, '\n')); }, + }); + const program = ts.createProgram({ rootNames: parsed.fileNames, options: parsed.options }); + const declarations = new Map(); + const outDir = parsed.options.outDir; + const rootDir = parsed.options.rootDir; + const result = program.emit(undefined, (fileName, text) => { + if (!fileName.endsWith('.d.ts')) return; + const source = join(rootDir, relative(outDir, fileName)).replace(/\.d\.ts$/, '.ts'); + declarations.set(source, text); + }, undefined, true); + const errors = result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); + if (errors.length > 0) throw new Error(ts.formatDiagnostics(errors, { getCanonicalFileName: (f) => f, getCurrentDirectory: () => pkgDir, getNewLine: () => '\n' })); + return { declarations, srcFiles: parsed.fileNames }; +} + +const printer = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed }); + +/** Declarations without comments, printed the same way whatever their source's layout. */ +function normalise(text) { + const file = ts.createSourceFile('x.d.ts', text, ts.ScriptTarget.ES2022, false, ts.ScriptKind.TS); + return printer.printFile(file).replace(/^export \{\};\n?/m, '').trim(); +} + +/** The report of the package in `dir` (a folder under packages/). */ +export function apiReport(dir) { + const pkgDir = join(ROOT, 'packages', dir); + const name = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')).name; + const { declarations, srcFiles } = emitDeclarations(pkgDir); + let report = `# API report: ${name}\n\nGenerated by \`node scripts/api-report.mjs write\` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand.\n`; + for (const [subpath, source] of entryModules(pkgDir, srcFiles)) { + const text = declarations.get(source); + if (text === undefined) throw new Error(`${name}: export ${subpath} has no declarations (${relative(ROOT, source)})`); + const body = normalise(text); + report += `\n## \`${name}${subpath === '.' ? '' : subpath.slice(1)}\`\n\n` + (body === '' ? '(exports nothing)\n' : '```ts\n' + body + '\n```\n'); + } + return report; +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + const mode = process.argv[2]; + if (mode !== 'write' && mode !== 'check') { + console.error('Usage: node scripts/api-report.mjs '); + process.exit(2); + } + let differs = 0; + for (const dir of PUBLIC_PACKAGES) { + const report = apiReport(dir); + const path = reportPath(dir); + if (mode === 'write') { + writeFileSync(path, report); + console.log(`wrote ${relative(ROOT, path)}`); + continue; + } + let current = ''; + try { current = readFileSync(path, 'utf8'); } catch { /* missing: differs */ } + if (current !== report) { + differs += 1; + console.error(`${relative(ROOT, path)} differs from the code: run node scripts/api-report.mjs write and review the diff`); + } + } + process.exit(differs === 0 ? 0 : 1); +} diff --git a/src/__tests__/api-report.test.ts b/src/__tests__/api-report.test.ts new file mode 100644 index 00000000..ddbad101 --- /dev/null +++ b/src/__tests__/api-report.test.ts @@ -0,0 +1,13 @@ +// Each public package's API report is the API its code has: a change to an +// export fails here until `node scripts/api-report.mjs write` writes the report +// again, so the change shows in review. + +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { PUBLIC_PACKAGES, apiReport, reportPath } from '../../scripts/api-report.mjs'; + +describe('the API reports', () => { + it.each([...PUBLIC_PACKAGES])('%s: the checked-in report is the code\'s API', (dir) => { + expect(readFileSync(reportPath(dir), 'utf8'), 'run node scripts/api-report.mjs write and review the diff').toBe(apiReport(dir)); + }, 120_000); +}); From 1d4b7c1ef5652579656adc970d79fff515406710 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 01:51:35 -0800 Subject: [PATCH 54/88] release 0.6.0-rc.12 mn tx status and receipts on the commands that submit. The chain package goes to 0.1.0-rc.1 for them, and both engines to 0.1.0-rc.1 for their chain dependency; core stays 0.1.0-rc.0. --- CHANGELOG.md | 6 ++++++ package-lock.json | 20 ++++++++++---------- package.json | 8 ++++---- packages/chain/package.json | 2 +- packages/engine-beta/package.json | 4 ++-- packages/engine-rc/package.json | 4 ++-- 6 files changed, 25 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77d5087b..8349215a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,17 @@ All notable changes to midnight-wallet-cli will be documented in this file. ## [Unreleased] +## [0.6.0-rc.12] - 2026-11-03 + ### Added - **`midnight tx status `: what became of a transaction**, from the indexer: its block (height, hash, time), the fee it paid in DUST (exact, and in specks), and its result (`SUCCESS`, `PARTIAL_SUCCESS` with each segment, or `FAILURE`). It takes the transaction's hash or any of its identifiers, which is what mn prints as `txHash` after a submit. The indexer lists only finalized transactions, so one it has is final; one it doesn't have is reported as `notFound` (not on chain yet, dropped, or never sent). `--wait` asks until it is listed, up to `--timeout` seconds (120 by default). MCP tool `midnight_tx_status`, read-only. - **Receipts in the results of the commands that submit.** `transfer`, `airdrop`, `dust register`, `swap take` and `swap cancel` wait up to 60 s for the indexer to list their transaction and add a `receipt` to their `--json` output (block, fee and result, as `tx status` gives them) and its block and fee to their text. If the indexer has not listed it by then, `receipt` is null and `receiptMissing` says why; the transaction is submitted either way. +### Packages + +- `@kuiralabs/midnight-chain` 0.1.0-rc.1 (adds the transaction status and receipts), and `@kuiralabs/midnight-engine-rc` and `-beta` 0.1.0-rc.1 (no change but their chain dependency). `@kuiralabs/midnight-cli-core` stays 0.1.0-rc.0. + ## [0.6.0-rc.11] - 2026-11-02 ### Added diff --git a/package-lock.json b/package-lock.json index 8d299bbd..ff0b7af8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.11", + "version": "0.6.0-rc.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.11", + "version": "0.6.0-rc.12", "license": "Apache-2.0", "workspaces": [ "packages/connector", @@ -18,10 +18,10 @@ "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", - "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-engine-beta": "0.1.0-rc.0", - "@kuiralabs/midnight-engine-rc": "0.1.0-rc.0", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", "@modelcontextprotocol/sdk": "^1.27.1", "@scure/bip39": "^2.0.1", "ws": "^8.19.0" @@ -5704,7 +5704,7 @@ }, "packages/chain": { "name": "@kuiralabs/midnight-chain", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", @@ -5747,10 +5747,10 @@ }, "packages/engine-beta": { "name": "@kuiralabs/midnight-engine-beta", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", @@ -6226,10 +6226,10 @@ }, "packages/engine-rc": { "name": "@kuiralabs/midnight-engine-rc", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", "@midnight-ntwrk/compact-runtime": "0.20.0", diff --git a/package.json b/package.json index 611bc30e..1e7c15b6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.11", + "version": "0.6.0-rc.12", "type": "module", "description": "Git-style CLI wallet for the Midnight blockchain", "license": "Apache-2.0", @@ -67,10 +67,10 @@ "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", - "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-engine-beta": "0.1.0-rc.0", - "@kuiralabs/midnight-engine-rc": "0.1.0-rc.0", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", "@modelcontextprotocol/sdk": "^1.27.1", "@scure/bip39": "^2.0.1", "ws": "^8.19.0" diff --git a/packages/chain/package.json b/packages/chain/package.json index 1a980520..5ce3f714 100644 --- a/packages/chain/package.json +++ b/packages/chain/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-chain", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "type": "module", "description": "Read-only network access for the Midnight CLI packages: node, indexer and proof-server readiness, chain id, tip, events and the ledger-version guard", "license": "Apache-2.0", diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index 0c394f23..17bc8238 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-engine-beta", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "type": "module", "description": "The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK 5.0 beta split packages, ledger 9 rc.3, midnight-js 5 beta): everything the CLI does with that SDK set, behind the engine interface", "license": "Apache-2.0", @@ -36,7 +36,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index 11747a11..b9c82f4b 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-engine-rc", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "type": "module", "description": "The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, ledger 9 rc, midnight-js 5 rc): everything the CLI does with that SDK set, behind the engine interface", "license": "Apache-2.0", @@ -36,7 +36,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", "@midnight-ntwrk/compact-runtime": "0.20.0", From 11a37bb55e64a1cd2466747f5307c053b2811a3e Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 02:19:24 -0800 Subject: [PATCH 55/88] The host: createHost, and the shell's built with it (3B, 1 of 7) A program creates a Host and passes it in: its settings, its paths, where its notices go, who answers its questions, where the SDK's warnings go, and slots, per-host state a library owns. The CLI and the MCP server now build theirs with createHost; until every library takes the host it is given, the module-level sources they still read are set from it, so nothing behaves differently. --- packages/cli-core/api-report.md | 31 ++++++++++++ packages/cli-core/src/lib/host.ts | 79 +++++++++++++++++++++++++++++++ scripts/check-layering.mjs | 2 +- src/__tests__/host.test.ts | 76 +++++++++++++++++++++++++++++ src/lib/cli-host.ts | 33 ++++++++----- src/mcp-server.ts | 7 +-- src/wallet.ts | 11 ++--- 7 files changed, 215 insertions(+), 24 deletions(-) create mode 100644 packages/cli-core/src/lib/host.ts create mode 100644 src/__tests__/host.test.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 3825b1e4..cd0f0959 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -1060,6 +1060,37 @@ export declare function feeLimitRefusal(feeSpecks: bigint, limits: FeeLimits): s export declare function pendingLimitRefusal(pendingCount: number, limits: FeeLimits): string | undefined; ``` +## `@kuiralabs/midnight-cli-core/lib/host` + +```ts +import type { HostPaths } from "./state-root.ts"; +import { type Settings } from "./settings.ts"; +import type { Prompter } from "./prompter.ts"; +import { type SdkWarningCalls } from "./sdk-warnings.ts"; +export interface HostSlot { + readonly name: string; + readonly init: () => T; +} +export declare function defineHostSlot(name: string, init: () => T): HostSlot; +export interface Host { + settings(): Settings; + paths(): HostPaths; + notice(line: string): void; + readonly prompter: Prompter | null; + readonly sdkWarnings: SdkWarningCalls; + slot(key: HostSlot): T; +} +export type Supplied = T | (() => T); +export interface HostOptions { + readonly paths?: Supplied; + readonly settings?: Supplied; + readonly notice?: (line: string) => void; + readonly prompter?: Prompter | null; + readonly sdkWarnings?: SdkWarningCalls; +} +export declare function createHost(options?: HostOptions): Host; +``` + ## `@kuiralabs/midnight-cli-core/lib/json-output` ```ts diff --git a/packages/cli-core/src/lib/host.ts b/packages/cli-core/src/lib/host.ts new file mode 100644 index 00000000..b99cfe76 --- /dev/null +++ b/packages/cli-core/src/lib/host.ts @@ -0,0 +1,79 @@ +// The host: what a program gives the libraries it runs. Its settings, its +// paths (the state root and the user's home), where its notices go, who +// answers its questions, where the SDK's warnings go, and the state the +// libraries keep for it (the slots). A program creates one and passes it in; +// two hosts in one process share nothing of it. +// +// mn's shell builds one at start, its MCP server one for all its calls. + +import type { HostPaths } from './state-root.ts'; +import { NoStateRootError } from './state-root.ts'; +import { settingsFromEnvironment, type Settings } from './settings.ts'; +import type { Prompter } from './prompter.ts'; +import { createSdkWarningRouter, sdkWarningCallsOn, type SdkWarningCalls } from './sdk-warnings.ts'; + +/** A piece of state a library keeps per host, named by the library that owns it. */ +export interface HostSlot { + readonly name: string; + readonly init: () => T; +} + +/** Names a piece of per-host state; `init` makes a host's first value. */ +export function defineHostSlot(name: string, init: () => T): HostSlot { + return Object.freeze({ name, init }); +} + +export interface Host { + /** The settings now. */ + settings(): Settings; + /** The state root and the user's home. Throws NoStateRootError when the host gave none. */ + paths(): HostPaths; + /** One line for the person, already formatted; dropped when the host takes none. */ + notice(line: string): void; + /** Who answers questions (a passphrase, an approval); null when nobody can. */ + readonly prompter: Prompter | null; + /** Where the SDK's warnings go, per call. */ + readonly sdkWarnings: SdkWarningCalls; + /** This host's value of a library's state, made on first use. */ + slot(key: HostSlot): T; +} + +/** A value, or a function giving the value now. */ +export type Supplied = T | (() => T); + +export interface HostOptions { + /** The state root and the user's home; without them, anything that keeps state refuses (NoStateRootError). */ + readonly paths?: Supplied; + /** The settings; every one unset when not given. */ + readonly settings?: Supplied; + /** Where notices go; dropped when not given. */ + readonly notice?: (line: string) => void; + /** Who answers questions; nobody when not given. */ + readonly prompter?: Prompter | null; + /** Where the SDK's warnings go; a router of the host's own when not given. */ + readonly sdkWarnings?: SdkWarningCalls; +} + +const UNSET: Settings = settingsFromEnvironment({}); + +const read = (supplied: Supplied): T => (typeof supplied === 'function' ? (supplied as () => T)() : supplied); + +export function createHost(options: HostOptions = {}): Host { + const slots = new Map, unknown>(); + const { paths, settings, notice, prompter = null } = options; + const sdkWarnings = options.sdkWarnings ?? sdkWarningCallsOn(createSdkWarningRouter()); + return { + settings: () => (settings === undefined ? UNSET : read(settings)), + paths: () => { + if (paths === undefined) throw new NoStateRootError(); + return read(paths); + }, + notice: (line) => notice?.(line), + prompter, + sdkWarnings, + slot(key: HostSlot): T { + if (!slots.has(key)) slots.set(key, key.init()); + return slots.get(key) as T; + }, + }; +} diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index e5dca5a6..02fac7a8 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -42,7 +42,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], diff --git a/src/__tests__/host.test.ts b/src/__tests__/host.test.ts new file mode 100644 index 00000000..d97022fb --- /dev/null +++ b/src/__tests__/host.test.ts @@ -0,0 +1,76 @@ +// The host a program creates and passes in: what it gives when told nothing, +// values or functions read when used, and state kept per host. + +import { describe, expect, it } from 'vitest'; +import { createHost, defineHostSlot } from '@kuiralabs/midnight-cli-core/lib/host'; +import { NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; + +describe('createHost', () => { + it('gives, when told nothing: every setting unset, no state root, notices dropped, nobody to ask', () => { + const host = createHost(); + expect(host.settings()).toEqual(settingsFromEnvironment({})); + expect(() => host.paths()).toThrow(NoStateRootError); + expect(() => host.notice('dropped')).not.toThrow(); + expect(host.prompter).toBeNull(); + }); + + it('takes values', () => { + const lines: string[] = []; + const prompter: Prompter = { isInteractive: () => false, ask: async () => null, askSecret: async () => null }; + const host = createHost({ + paths: { stateRoot: '/state', home: '/home' }, + settings: settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }), + notice: (line) => lines.push(line), + prompter, + }); + expect(host.paths()).toEqual({ stateRoot: '/state', home: '/home' }); + expect(host.settings().isLocalDetectOff).toBe(true); + host.notice('one'); + expect(lines).toEqual(['one']); + expect(host.prompter).toBe(prompter); + }); + + it('reads functions each time, so what they read can change', () => { + let root = '/a'; + const env: Record = {}; + const host = createHost({ paths: () => ({ stateRoot: root, home: '/home' }), settings: () => settingsFromEnvironment(env) }); + expect(host.paths().stateRoot).toBe('/a'); + root = '/b'; + env.MN_DISABLE_NATIVE_DUST = '1'; + expect(host.paths().stateRoot).toBe('/b'); + expect(host.settings().isNativeDustOff).toBe(true); + }); + + it('runs each call with its own SDK warnings when it is given no router', async () => { + const host = createHost(); + const seen = await host.sdkWarnings.run(async (warnings) => typeof warnings.listen); + expect(seen).toBe('function'); + }); +}); + +describe('host slots', () => { + const COUNTER = defineHostSlot('test counter', () => ({ n: 0 })); + + it('make a host\'s value on first use and keep it', () => { + const host = createHost(); + host.slot(COUNTER).n += 1; + host.slot(COUNTER).n += 1; + expect(host.slot(COUNTER).n).toBe(2); + }); + + it('are per host: two hosts in one process share nothing', () => { + const a = createHost(); + const b = createHost(); + a.slot(COUNTER).n = 5; + expect(b.slot(COUNTER).n).toBe(0); + }); + + it('are per slot, even with the same name', () => { + const other = defineHostSlot('test counter', () => ({ n: 9 })); + const host = createHost(); + host.slot(COUNTER).n = 1; + expect(host.slot(other).n).toBe(9); + }); +}); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 4c0a891e..75aafcdb 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -15,22 +15,29 @@ import { installSdkNoiseFilters } from './sdk-noise.ts'; import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { setPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from './installed-engines.ts'; -import type { SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -/** What the host gives its runners. */ -export interface CliHost { - /** Runs each call with its own SDK warnings. */ - readonly sdkWarnings: SdkWarningCalls; -} - -export function installCliHost(): CliHost { - const sdkWarnings = installSdkNoiseFilters(); - setNoticeSink((line) => process.stderr.write(line + '\n')); - setSettingsSource(() => settingsFromEnvironment(process.env)); - setHostPathsSource(() => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() })); +/** + * The CLI's host, or the MCP server's (`prompter` null: no terminal there). + * Until every library takes the host it is given, the module-level sources + * they still read are set from it. + */ +export function createCliHost({ prompter }: { prompter: Prompter | null }): Host { + const host = createHost({ + settings: () => settingsFromEnvironment(process.env), + paths: () => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() }), + notice: (line) => process.stderr.write(line + '\n'), + prompter, + sdkWarnings: installSdkNoiseFilters(), + }); + setNoticeSink(host.notice); + setSettingsSource(host.settings); + setHostPathsSource(host.paths); + setPrompter(host.prompter); setEngineLoader(loadInstalledEngine); - return { sdkWarnings }; + return host; } diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 4d07f380..1697607c 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -28,7 +28,8 @@ import { needsConfirmation } from '@kuiralabs/midnight-cli-core/lib/command-defi import { ensureHeapForSync } from './lib/heap-guard.ts'; import { assertNodeSupported } from './lib/node-version.ts'; import { hideProjectIdsInOutput } from './lib/output-redaction.ts'; -import { installCliHost, type CliHost } from './lib/cli-host.ts'; +import { createCliHost } from './lib/cli-host.ts'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { installedCommands } from './lib/installed-commands.ts'; import { skillCore, skillFull } from './lib/mcp/skills.ts'; @@ -47,7 +48,7 @@ const SKILL_LEGACY_URI = 'midnight-wallet://skill'; const confirmationStore = createConfirmationStore(); // What the host gives the tools' runs, once main() has installed it. -let host: CliHost | null = null; +let host: Host | null = null; // ── Server setup ──────────────────────────────────────────── @@ -220,7 +221,7 @@ async function main() { // Endpoint URLs can carry a Blockfrost project id: no response or log shows it. hideProjectIdsInOutput(); // What the tools' libraries get from their host, as the CLI gives them (no prompter: no terminal here). - host = installCliHost(); + host = createCliHost({ prompter: null }); // The server runs facades on demand (balance/transfer/etc.). A cold shielded // sync would overflow Node's default heap, so re-exec once at startup with // more headroom. No-op when launched via `mn --mcp` (already bumped) or when diff --git a/src/wallet.ts b/src/wallet.ts index db034a41..e2a76ac0 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -18,9 +18,8 @@ import { migrateOldWallet } from './lib/wallet-paths.ts'; import { ensureHeapForSync } from './lib/heap-guard.ts'; import { assertNodeSupported } from './lib/node-version.ts'; import { hideProjectIdsInOutput } from './lib/output-redaction.ts'; -import { setPrompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; -import { installCliHost } from './lib/cli-host.ts'; +import { createCliHost } from './lib/cli-host.ts'; // --mcp: start MCP server instead of CLI (for: npx midnight-wallet-cli --mcp) if (process.argv.includes('--mcp')) { @@ -69,11 +68,9 @@ if (needsWalletSdk) await ensureHeapForSync(); hideProjectIdsInOutput(); // What the libraries get from their host: the SDK noise filters, notices on -// stderr, settings from the environment, and the state root ~/.midnight. -const host = installCliHost(); - -// Libraries ask their questions (passphrase, approvals) at the terminal. -setPrompter(createTerminalPrompter()); +// stderr, settings from the environment, the state root ~/.midnight, and the +// terminal to ask their questions (passphrase, approvals) at. +const host = createCliHost({ prompter: createTerminalPrompter() }); // Auto-migrate old ~/.midnight/wallet.json → wallets/default.json (silent, one-time) migrateOldWallet(); From b3464ffc557d19a2c77a2b42a742370e9cf9f1ab Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 02:23:11 -0800 Subject: [PATCH 56/88] A call's context carries its host (3B, 2 of 7) createCallContext takes the host the call runs in: the call's configuration comes from it, and its verbose lines go through the host's notices. The CLI's dispatch and the MCP server's runs give their host; tests run with a test host (settings and the state root read from the environment when used). The behaviour snapshot now ignores a .DS_Store Finder leaves in a snapshot folder. --- packages/cli-core/api-report.md | 8 ++++-- packages/cli-core/src/lib/call-context.ts | 20 ++++++------- scripts/behaviour-snapshot.mjs | 3 +- src/__tests__/call-context.test.ts | 34 +++++++++++++++++------ src/__tests__/command-registry.test.ts | 3 +- src/__tests__/helpers/cli-call.ts | 7 ++++- src/__tests__/helpers/own-call.ts | 6 ++-- src/__tests__/helpers/test-host.ts | 18 ++++++++++++ src/__tests__/verbose-per-call.test.ts | 12 +++++--- src/lib/command-dispatch.ts | 10 ++++--- src/lib/run-command.ts | 14 +++++----- src/mcp-server.ts | 5 ++-- src/wallet.ts | 2 +- 13 files changed, 96 insertions(+), 46 deletions(-) create mode 100644 src/__tests__/helpers/test-host.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index cd0f0959..8698d48f 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -193,8 +193,9 @@ export declare function describeIndexerChange(network: string, change: IndexerCh ```ts import { type ParsedArgs } from "./argv.ts"; import type { Payer } from "./payer.ts"; -import { type Settings } from "./settings.ts"; -import { type HostPaths } from "./state-root.ts"; +import type { Settings } from "./settings.ts"; +import type { HostPaths } from "./state-root.ts"; +import type { Host } from "./host.ts"; import { type CallSdkWarnings } from "./sdk-warnings.ts"; import { type Progress, type ProgressReport } from "../ui/spinner.ts"; export interface CallOutput { @@ -219,6 +220,7 @@ export interface CallContext { readonly diagnostics: CallDiagnostics; readonly sdkWarnings: CallSdkWarnings; readonly config: CallConfig; + readonly host: Host; readonly payer?: Payer; readonly protectors?: readonly Protector[]; } @@ -231,8 +233,8 @@ export declare class SecondResultError extends Error { } export declare function callOutput(sink: CallOutput): CallOutput; export declare function callDiagnostics(verbose: boolean, write: (line: string) => void): CallDiagnostics; -export declare function hostCallConfig(): CallConfig; export interface CallParts { + readonly host: Host; readonly args: ParsedArgs; readonly signal: AbortSignal; readonly output: CallOutput; diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index 460de970..983a9615 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -16,9 +16,9 @@ import { CancelledError } from './errors.ts'; import { preferEngineOf } from './engine.ts'; import { resolveNetworkName } from './resolve-network.ts'; import type { Payer } from './payer.ts'; -import { settings, type Settings } from './settings.ts'; -import { hostPaths, type HostPaths } from './state-root.ts'; -import { notice } from './notices.ts'; +import type { Settings } from './settings.ts'; +import type { HostPaths } from './state-root.ts'; +import type { Host } from './host.ts'; import { verboseLine } from './verbose.ts'; import { createSdkWarningRouter, type CallSdkWarnings } from './sdk-warnings.ts'; import { createProgress, type Progress, type ProgressReport } from '../ui/spinner.ts'; @@ -67,6 +67,8 @@ export interface CallContext { readonly diagnostics: CallDiagnostics; readonly sdkWarnings: CallSdkWarnings; readonly config: CallConfig; + /** The host the call runs in: what its libraries are given. */ + readonly host: Host; /** What a command that submits a transaction pays with, when its caller gives one. */ readonly payer?: Payer; /** What `wallet protect` seals besides the wallets, when its caller gives them. */ @@ -114,13 +116,10 @@ export function callDiagnostics(verbose: boolean, write: (line: string) => void) }; } -/** The configuration the host gives now: its settings and its paths. */ -export function hostCallConfig(): CallConfig { - return { settings: settings(), paths: hostPaths() }; -} - /** What a runner gives a call; the rest of its context comes from the host. */ export interface CallParts { + /** The host the call runs in. */ + readonly host: Host; readonly args: ParsedArgs; readonly signal: AbortSignal; readonly output: CallOutput; @@ -138,9 +137,10 @@ export function createCallContext(parts: CallParts { @@ -78,20 +79,37 @@ describe("a call's diagnostics", () => { describe("a call's context", () => { const payer = { name: 'test payer' } as unknown as Payer; - it('holds its signal, --verbose, the payer and protectors given, and the configuration the host gives at its start', () => { + it('holds its signal, --verbose, the payer and protectors given, its host, and the configuration the host gives at its start', () => { const controller = new AbortController(); const { sink } = recordingSink(); - const ctx = createCallContext({ args: parseArgs(['balance', '--verbose']), signal: controller.signal, output: sink, payer, protectors: ['p'] }); + const host = createHost({ paths: { stateRoot: '/call-state', home: '/call-home' }, settings: settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }) }); + const ctx = createCallContext({ host, args: parseArgs(['balance', '--verbose']), signal: controller.signal, output: sink, payer, protectors: ['p'] }); expect(ctx.signal).toBe(controller.signal); expect(ctx.diagnostics.isVerbose).toBe(true); expect(ctx.payer).toBe(payer); expect(ctx.protectors).toEqual(['p']); - expect(ctx.config).toStrictEqual({ settings: settings(), paths: hostPaths() }); + expect(ctx.host).toBe(host); + expect(ctx.config).toStrictEqual({ settings: settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }), paths: { stateRoot: '/call-state', home: '/call-home' } }); + }); + + it("writes its verbose lines through its own host's notices", () => { + const { sink } = recordingSink(); + const lines: string[] = []; + const ctx = createCallContext({ host: createHost({ paths: { stateRoot: '/s', home: '/h' }, notice: (line) => lines.push(line) }), args: parseArgs(['balance', '--verbose']), signal: new AbortController().signal, output: sink }); + ctx.diagnostics.line('sync', 'started'); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain('started'); + }); + + it('gives two calls of two hosts each its own configuration', () => { + const { sink } = recordingSink(); + const call = (stateRoot: string) => createCallContext({ host: createHost({ paths: { stateRoot, home: '/h' } }), args: parseArgs(['info']), signal: new AbortController().signal, output: sink }); + expect([call('/a').config.paths.stateRoot, call('/b').config.paths.stateRoot]).toEqual(['/a', '/b']); }); it('has no payer or protectors when none are given', () => { const { sink } = recordingSink(); - const ctx = createCallContext({ args: parseArgs(['info']), signal: new AbortController().signal, output: sink }); + const ctx = createCallContext({ host: testHost(), args: parseArgs(['info']), signal: new AbortController().signal, output: sink }); expect('payer' in ctx).toBe(false); expect('protectors' in ctx).toBe(false); expect(ctx.diagnostics.isVerbose).toBe(false); @@ -100,7 +118,7 @@ describe("a call's context", () => { it('runs the handler and gives back the exit code it returns', async () => { const { sink } = recordingSink(); const args = parseArgs(['test', 'run']); - const ctx = createCallContext({ args, signal: new AbortController().signal, output: sink }); + const ctx = createCallContext({ host: testHost(), args, signal: new AbortController().signal, output: sink }); let given: CallContext | undefined; const outcome = await runHandler(async (_args, c) => { given = c; return { exitCode: 1 }; }, args, ctx); expect(outcome).toEqual({ exitCode: 1 }); @@ -112,7 +130,7 @@ describe("a call's context", () => { controller.abort(); const { seen, sink } = recordingSink(); const args = parseArgs(['info']); - const ctx = createCallContext({ args, signal: controller.signal, output: sink }); + const ctx = createCallContext({ host: testHost(), args, signal: controller.signal, output: sink }); let ran = false; await expect(runHandler(async (_a, c) => { ran = true; c.output.result({}); }, args, ctx)).rejects.toThrow(CancelledError); expect(ran).toBe(false); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 0e3150f5..8c497530 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -26,6 +26,7 @@ import { import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { CONFIRM_TOOL, listedTools } from '../lib/mcp/registry-tools.ts'; import { commandNeedsWalletSdk, dispatchCommand, type ShellProvisions } from '../lib/command-dispatch.ts'; +import { testHost } from './helpers/test-host.ts'; import { FULL_FLAG, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { CancelledError, isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError, EXIT_CANCELLED } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; @@ -110,7 +111,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => const provisions: ShellProvisions = { signal: controller.signal, output, - sdkWarnings: sdkWarningCallsOn(createSdkWarningRouter()), + host: testHost(), loadPayer: async () => payer, loadProtectors: async () => [protector], }; diff --git a/src/__tests__/helpers/cli-call.ts b/src/__tests__/helpers/cli-call.ts index 0cc5c0ed..52f0e36f 100644 --- a/src/__tests__/helpers/cli-call.ts +++ b/src/__tests__/helpers/cli-call.ts @@ -6,21 +6,26 @@ import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { createCallContext, runHandler, type CommandHandler, type CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { processOutput } from '../../lib/command-dispatch.ts'; import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { testHost } from './test-host.ts'; export interface CliCallOptions { /** The call's cancellation; none: it is never cancelled. */ signal?: AbortSignal; payer?: Payer; protectors?: readonly Protector[]; + /** The host the call runs in; a test host when not given. */ + host?: Host; } /** Runs `handler` with `args` as the CLI does, and returns the exit code it gives. */ export function cliCall( handler: CommandHandler, args: ParsedArgs, - { signal, payer, protectors }: CliCallOptions = {}, + { signal, payer, protectors, host }: CliCallOptions = {}, ): Promise { const ctx = createCallContext({ + host: host ?? testHost(), args, signal: signal ?? new AbortController().signal, output: processOutput, diff --git a/src/__tests__/helpers/own-call.ts b/src/__tests__/helpers/own-call.ts index 4801b8ce..228fd6d0 100644 --- a/src/__tests__/helpers/own-call.ts +++ b/src/__tests__/helpers/own-call.ts @@ -2,8 +2,8 @@ // outside any host: no host's filters report to it. import type { CommandRun } from '../../lib/run-command.ts'; -import { createSdkWarningRouter, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { testHost } from './test-host.ts'; -export function ownCall(run: Omit = {}): CommandRun { - return { ...run, sdkWarnings: sdkWarningCallsOn(createSdkWarningRouter()) }; +export function ownCall(run: Omit & { host?: CommandRun['host'] } = {}): CommandRun { + return { ...run, host: run.host ?? testHost() }; } diff --git a/src/__tests__/helpers/test-host.ts b/src/__tests__/helpers/test-host.ts new file mode 100644 index 00000000..6301cf51 --- /dev/null +++ b/src/__tests__/helpers/test-host.ts @@ -0,0 +1,18 @@ +// The host a test's calls run with: settings from the environment and the +// state root under the home directory, each read when used (tests change HOME +// and the environment as they go), notices dropped, nobody to ask, and SDK +// warnings of its own (no host's filters report to it). + +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { createHost, type Host, type HostOptions } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; + +export function testHost(overrides: HostOptions = {}): Host { + return createHost({ + settings: () => settingsFromEnvironment(process.env), + paths: () => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() }), + ...overrides, + }); +} diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index a96d70cf..21f15d95 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -18,6 +18,10 @@ import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import balanceCommand from '../commands/balance.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { ownCall } from './helpers/own-call.ts'; +import { testHost } from './helpers/test-host.ts'; + +// One host for every call, as the MCP server has: its notices are where verbose lines go. +const host = testHost({ notice: (line) => notices.push(line) }); // Nothing listens here: each call fails at its first connection, after its first diagnostic. const UNREACHABLE = ['--indexer-ws', 'ws://127.0.0.1:1/api/v4/graphql/ws', '--node', 'ws://127.0.0.1:1', '--proof-server', 'http://127.0.0.1:1']; @@ -48,8 +52,8 @@ afterEach(() => { describe('verbose, per call', () => { it('two balance calls at once, one --verbose: only the verbose one writes diagnostic lines', async () => { - const verboseCall = captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall()); - const quietCall = captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall()); + const verboseCall = captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall({ host })); + const quietCall = captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall({ host })); const outcomes = await Promise.allSettled([verboseCall, quietCall]); // Neither reaches an indexer; both fail, each with its own error. expect(outcomes.map((o) => o.status)).toEqual(['rejected', 'rejected']); @@ -58,11 +62,11 @@ describe('verbose, per call', () => { }); it('a call after a verbose one is quiet', async () => { - const verbose = await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall()).then(() => null, (err: unknown) => err); + const verbose = await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall({ host })).then(() => null, (err: unknown) => err); // It got as far as its first diagnostic, and failed connecting. expect(notices.some((line) => line.includes(`balance: address=${VERBOSE_ADDRESS}`))).toBe(true); notices = []; - const quiet = await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall()).then(() => null, (err: unknown) => err); + const quiet = await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall({ host })).then(() => null, (err: unknown) => err); // It got as far too, failing the same way, past where the verbose one wrote its diagnostic. expect(quiet).toBeInstanceOf(Error); expect((quiet as Error).message).toBe((verbose as Error).message.replace(VERBOSE_ADDRESS, QUIET_ADDRESS)); diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index 31d50a9f..fb4cf7ed 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -9,7 +9,8 @@ import type { CommandDefinition, CommandRegistry } from '@kuiralabs/midnight-cli import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { writeJsonResult } from '@kuiralabs/midnight-cli-core/lib/json-output'; import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { CallSdkWarnings, SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; import type { WalletProtector } from './wallet-protector.ts'; /** What the shell can give a handler: its call's signal and output, and, as its definition's `shell` field asks, the payer or protectors, loaded only then. */ @@ -17,8 +18,8 @@ export interface ShellProvisions { readonly signal: AbortSignal; /** Where the call's output goes; a definition's notice goes to its stderr, before the handler loads. */ readonly output: CallOutput; - /** The host's calls: each call runs in one, with its own SDK warnings. */ - readonly sdkWarnings: SdkWarningCalls; + /** The host the call runs in; each call runs in one of its calls, with its own SDK warnings. */ + readonly host: Host; readonly loadPayer: () => Promise; readonly loadProtectors: () => Promise; } @@ -51,6 +52,7 @@ export function findInstalledCommand(registry: CommandRegistry, name: string): C async function cliCallContext(definition: CommandDefinition, args: ParsedArgs, provisions: ShellProvisions, sdkWarnings: CallSdkWarnings): Promise> { const { payer, protectors } = definition.shell; return createCallContext({ + host: provisions.host, args, signal: provisions.signal, output: provisions.output, @@ -71,5 +73,5 @@ export async function dispatchCommand(registry: CommandRegistry, name: string, a if (definition.shell.unavailable !== undefined) throw new Error(definition.shell.unavailable); if (definition.shell.notice !== undefined) provisions.output.stderr(definition.shell.notice); const { default: handler } = await definition.load(); - return provisions.sdkWarnings.run(async (sdkWarnings) => runHandler(handler, args, await cliCallContext(definition, args, provisions, sdkWarnings))); + return provisions.host.sdkWarnings.run(async (sdkWarnings) => runHandler(handler, args, await cliCallContext(definition, args, provisions, sdkWarnings))); } diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index 3f4c12c2..78750b60 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -4,7 +4,7 @@ import { type ParsedArgs, MINIMAL_FLAG } from '@kuiralabs/midnight-cli-core/lib/argv'; import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; import { createCallContext, runHandler, type CommandHandler, type CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import type { SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { CommandFailedError } from '@kuiralabs/midnight-cli-core/lib/errors'; export interface CommandRun { @@ -15,11 +15,10 @@ export interface CommandRun { /** What a command that submits a transaction pays with. */ payer?: Payer; /** - * The calls the command runs in, which give it its own SDK warnings: the - * host's, so the host's filters report the SDK's warnings to this call. - * Required, so a host can't leave its calls without them unnoticed. + * The host the command runs in. Its calls give the command its own SDK + * warnings, so the host's filters report the SDK's warnings to this call. */ - sdkWarnings: SdkWarningCalls; + host: Host; } /** The server's stderr: where a call's text for the person goes, never the protocol channel on stdout. */ @@ -54,7 +53,7 @@ const serverStderr = (text: string): void => { process.stderr.write(text); }; export async function captureCommand( handler: CommandHandler, args: ParsedArgs, - { signal, onProgress, payer, sdkWarnings }: CommandRun, + { signal, onProgress, payer, host }: CommandRun, ): Promise> { let result: Record = {}; const output: CallOutput = { @@ -71,7 +70,8 @@ export async function captureCommand( let running = true; const report = onProgress === undefined ? undefined : (message: string): void => { if (running) onProgress(message); }; try { - const outcome = await sdkWarnings.run((warnings) => runHandler(handler, args, createCallContext({ + const outcome = await host.sdkWarnings.run((warnings) => runHandler(handler, args, createCallContext({ + host, args, signal: signal ?? new AbortController().signal, output, diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 1697607c..2bff4e67 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -159,14 +159,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { */ function toolCall(progressToken: ProgressToken | undefined, extra: RequestHandlerExtra): CommandRun { if (host === null) throw new Error('The MCP server took a call before its host was installed'); - const { sdkWarnings } = host; - if (progressToken === undefined) return { signal: extra.signal, payer: servePayer, sdkWarnings }; + if (progressToken === undefined) return { signal: extra.signal, payer: servePayer, host }; let progress = 0; let last: string | undefined; return { signal: extra.signal, payer: servePayer, - sdkWarnings, + host, onProgress: (message) => { if (message === last) return; last = message; diff --git a/src/wallet.ts b/src/wallet.ts index e2a76ac0..e036b251 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -98,7 +98,7 @@ async function run(): Promise { return dispatchCommand(installedCommands, command, args, { signal, output: processOutput, - sdkWarnings: host.sdkWarnings, + host, loadPayer: async () => (await import('./lib/serve-payer.ts')).servePayer, // wallet protect also seals grant's accounts, through the protector grant provides. loadProtectors: async () => [(await import('./lib/grant/account-protector.ts')).accountProtector], From d8835a2c5c9dbbe9b9de307ec34a78ae3441f890 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 03:06:37 -0800 Subject: [PATCH 57/88] Paths come from the host (3B, 3 of 7) No library or command reads the state root or the home from module state any more: commands take them from their call's host, library functions as a required parameter (a root, or the options an engine method already takes), and state-root.ts keeps only the HostPaths type and NoStateRootError. The paths source and its allowance go. A new test runs two hosts with different state roots in one process: their config, wallets, open swap offers and wallet caches stay apart. Tests that read or wrote the real ~/.midnight now use temp roots. Behaviour snapshot unchanged; suite 2564, beta 168; swap pass 30/30 and tx pass 25/25 on the scratch chain. --- packages/chain/src/commands/status.ts | 14 +- packages/chain/src/commands/tx.ts | 2 +- packages/cli-core/api-report.md | 89 +++++++----- packages/cli-core/src/commands/config.ts | 9 +- packages/cli-core/src/lib/cache-indexer.ts | 6 +- packages/cli-core/src/lib/call-context.ts | 3 +- packages/cli-core/src/lib/cli-config.ts | 26 ++-- .../cli-core/src/lib/command-definition.ts | 3 + packages/cli-core/src/lib/engine.ts | 42 ++++-- packages/cli-core/src/lib/network.ts | 14 +- packages/cli-core/src/lib/open-offers.ts | 27 ++-- packages/cli-core/src/lib/payer.ts | 12 +- .../cli-core/src/lib/reader-cache-files.ts | 54 +++---- packages/cli-core/src/lib/resolve-network.ts | 5 +- packages/cli-core/src/lib/state-root.ts | 32 +---- packages/cli-core/src/lib/wallet-cache.ts | 42 +++--- packages/cli-core/src/lib/wallet-session.ts | 13 +- packages/engine-beta/api-report.md | 38 ++--- packages/engine-beta/src/dust-direct-cache.ts | 12 +- packages/engine-beta/src/dust-export.ts | 13 +- packages/engine-beta/src/dust-register.ts | 3 +- packages/engine-beta/src/dust-sync-native.ts | 10 +- packages/engine-beta/src/facade.ts | 9 +- .../engine-beta/src/shielded-direct-cache.ts | 22 +-- packages/engine-beta/src/transfer.ts | 2 + .../engine-beta/src/wallet-data-repository.ts | 89 ++++++------ packages/engine-beta/src/wallet.ts | 36 ++--- packages/engine-rc/api-report.md | 38 ++--- packages/engine-rc/src/dust-direct-cache.ts | 12 +- packages/engine-rc/src/dust-export.ts | 13 +- packages/engine-rc/src/dust-register.ts | 3 +- packages/engine-rc/src/dust-sync-native.ts | 10 +- packages/engine-rc/src/facade.ts | 9 +- .../engine-rc/src/shielded-direct-cache.ts | 22 +-- packages/engine-rc/src/transfer.ts | 2 + .../engine-rc/src/wallet-data-repository.ts | 89 ++++++------ packages/engine-rc/src/wallet.ts | 36 ++--- scripts/check-process-safety.mjs | 1 - src/__tests__/balance-command.live.test.ts | 3 +- src/__tests__/cache-indexer.test.ts | 35 +++-- src/__tests__/chain-reset-clearing.test.ts | 13 +- src/__tests__/cli-config.test.ts | 28 ++-- src/__tests__/command-cancellation.test.ts | 4 +- src/__tests__/command-registry.test.ts | 3 +- src/__tests__/config-command.test.ts | 16 ++- src/__tests__/contract-deploy.test.ts | 7 +- src/__tests__/contract-runner.test.ts | 4 +- src/__tests__/contract-runtime-check.test.ts | 13 +- src/__tests__/dust-direct-cache.test.ts | 88 ++++++------ src/__tests__/dust-export.test.ts | 4 +- src/__tests__/dust-sync-native.test.ts | 4 +- src/__tests__/engine.test.ts | 33 +++-- src/__tests__/fixtures/record-swap-offer.ts | 7 +- src/__tests__/generate-command.test.ts | 33 ++--- src/__tests__/grant-prepare.test.ts | 2 +- src/__tests__/helpers/shell-settings.ts | 11 +- src/__tests__/host-paths.test.ts | 134 ++++++++++++++++++ src/__tests__/json-output.test.ts | 5 +- src/__tests__/localnet-cancellation.test.ts | 2 +- src/__tests__/localnet-command.test.ts | 6 +- src/__tests__/manual-command.test.ts | 6 +- src/__tests__/mcp-server-advice.test.ts | 15 +- src/__tests__/multi-wallet.test.ts | 51 +++---- src/__tests__/network-cancellation.test.ts | 4 +- src/__tests__/notices.test.ts | 2 +- src/__tests__/open-offers.test.ts | 32 ++--- src/__tests__/payer.test.ts | 15 +- .../prep-runner-cancellation.test.ts | 2 +- src/__tests__/provision-wallets.test.ts | 6 +- src/__tests__/seed-resolver.test.ts | 26 ++-- src/__tests__/serve-manager.test.ts | 14 +- src/__tests__/shielded-direct-cache.test.ts | 2 +- src/__tests__/state-root.test.ts | 61 ++++---- src/__tests__/swap-request.test.ts | 13 +- src/__tests__/transfer-request.test.ts | 2 +- src/__tests__/verbose-per-call.test.ts | 1 - src/__tests__/wallet-cache.test.ts | 73 +++++----- src/__tests__/wallet-config.test.ts | 2 +- src/__tests__/wallet-create.test.ts | 26 ++-- src/__tests__/wallet-data-repository.test.ts | 90 +++++------- .../wallet-state-to-restore.live.test.ts | 19 +-- src/commands/address.ts | 7 +- src/commands/airdrop.ts | 27 ++-- src/commands/balance.ts | 21 +-- src/commands/cache.ts | 21 +-- src/commands/contract.definition.ts | 16 ++- src/commands/contract.ts | 13 +- src/commands/dev.ts | 7 +- src/commands/dust.ts | 18 ++- src/commands/generate.ts | 9 +- src/commands/genesis-address.ts | 5 +- src/commands/grant.definition.ts | 5 +- src/commands/grant.ts | 12 +- src/commands/info.ts | 7 +- src/commands/inspect-cost.ts | 5 +- src/commands/localnet.ts | 12 +- src/commands/serve.ts | 9 +- src/commands/swap.definition.ts | 4 +- src/commands/swap.ts | 23 +-- src/commands/test.ts | 5 +- src/commands/transfer.definition.ts | 2 +- src/commands/transfer.ts | 22 +-- src/commands/wallet.definition.ts | 8 +- src/commands/wallet.ts | 41 +++--- src/lib/chain-caches.ts | 16 +-- src/lib/cli-host.ts | 2 - src/lib/contract/call.ts | 1 + src/lib/contract/deploy.ts | 1 + src/lib/contract/runner.ts | 16 ++- src/lib/contract/runtime-check.ts | 7 +- src/lib/dev/deploy.ts | 4 +- src/lib/dev/localnet-ready.ts | 5 +- src/lib/dev/provision-wallets.ts | 60 ++++---- src/lib/grant/account-records.ts | 6 +- src/lib/grant/account.ts | 18 +-- src/lib/grant/prepare.ts | 14 +- src/lib/localnet.ts | 42 +++--- src/lib/mcp/registry-tools.ts | 10 +- src/lib/mcp/server-advice.ts | 6 +- src/lib/passphrase.ts | 7 +- src/lib/seed-resolver.ts | 11 +- src/lib/serve-manager.ts | 12 +- src/lib/serve-payer.ts | 9 +- src/lib/swap/offers.ts | 36 ++--- src/lib/swap/request.ts | 10 +- src/lib/test/actions-runner.ts | 11 +- src/lib/test/browser-test.ts | 11 +- src/lib/test/prep-runner.ts | 27 ++-- src/lib/test/types.ts | 5 +- src/lib/transfer-request.ts | 22 +-- src/lib/wallet-can-pay.ts | 8 +- src/lib/wallet-config.ts | 72 +++++----- src/lib/wallet-create.ts | 17 +-- src/lib/wallet-paths.ts | 43 +++--- src/lib/wallet-protector.ts | 6 +- src/mcp-server.ts | 14 +- src/wallet.ts | 2 +- 137 files changed, 1430 insertions(+), 1179 deletions(-) create mode 100644 src/__tests__/host-paths.test.ts diff --git a/packages/chain/src/commands/status.ts b/packages/chain/src/commands/status.ts index 2d32ef75..1d54b184 100644 --- a/packages/chain/src/commands/status.ts +++ b/packages/chain/src/commands/status.ts @@ -143,14 +143,14 @@ async function fetchJson(path: string, signal: AbortSignal): Promise { return response.json() as Promise; } -async function tryDetectNetwork(args: ParsedArgs): Promise { +async function tryDetectNetwork(args: ParsedArgs, root: string): Promise { const flagNetwork = getFlag(args, 'network'); if (flagNetwork) return flagNetwork; // Check config file for default network try { const { loadCliConfig } = await import('@kuiralabs/midnight-cli-core/lib/cli-config'); - const config = loadCliConfig(); + const config = loadCliConfig(root); if (config.network && isValidNetworkName(config.network)) return config.network; } catch { // fall through @@ -297,10 +297,10 @@ async function probeExplorer(explorerUrl: string | null, signal: AbortSignal): P } /** The live probes of one network; a cancelled call's probes stop at once (their results then mean nothing). */ -async function runLocalProbes(networkName: string, signal: AbortSignal): Promise> { +async function runLocalProbes(networkName: string, root: string, signal: AbortSignal): Promise> { if (!isValidNetworkName(networkName)) return {}; - const netConfig = resolveNetworkConfig(networkName as NetworkName, { blockfrostProjectId: resolveBlockfrostProjectId(networkName as NetworkName) }); + const netConfig = resolveNetworkConfig(networkName as NetworkName, { blockfrostProjectId: resolveBlockfrostProjectId(networkName as NetworkName, root) }); const extra = EXTRA_ENDPOINTS[networkName]; if (!extra) return {}; @@ -384,7 +384,7 @@ export default async function statusCommand(args: ParsedArgs, ctx: CallContext): const watchMode = hasFlag(args, 'watch'); // Determine target network(s) first - const detected = (await tryDetectNetwork(args)) ?? 'preprod'; + const detected = (await tryDetectNetwork(args, ctx.config.paths.stateRoot)) ?? 'preprod'; // Fetch canary data + run local probes in parallel const spinner = ctx.progress.start('Checking network status...'); @@ -412,7 +412,7 @@ export default async function statusCommand(args: ParsedArgs, ctx: CallContext): return null; }), // Local probes per network - ...targetNetworks.map(name => runLocalProbes(name, ctx.signal)), + ...targetNetworks.map(name => runLocalProbes(name, ctx.config.paths.stateRoot, ctx.signal)), ]); // Cancelled: the probes stopped early, so what they found says nothing about the network. @@ -523,7 +523,7 @@ export default async function statusCommand(args: ParsedArgs, ctx: CallContext): fetchJson('/api/status', ctx.signal), fetchJson('/api/issues', ctx.signal), ]).catch(() => null), - ...targetNetworks.map(name => runLocalProbes(name, ctx.signal)), + ...targetNetworks.map(name => runLocalProbes(name, ctx.config.paths.stateRoot, ctx.signal)), ]); // Watching ended while this refresh ran: nothing to show. if (ctx.signal.aborted) return; diff --git a/packages/chain/src/commands/tx.ts b/packages/chain/src/commands/tx.ts index 3a9131a3..0962d7ca 100644 --- a/packages/chain/src/commands/tx.ts +++ b/packages/chain/src/commands/tx.ts @@ -27,7 +27,7 @@ export default async function txCommand(args: ParsedArgs, ctx: CallContext): Pro const ref = parseTxReference(given); const timeoutMs = timeoutMsOf(args); const jsonMode = hasFlag(args, 'json'); - const { name: network, config } = resolveNetwork({ args }); + const { name: network, config } = resolveNetwork({ args, configDir: ctx.config.paths.stateRoot }); const wait = hasFlag(args, 'wait'); const spinner = jsonMode ? ctx.progress.silent() : ctx.progress.start(wait ? 'Waiting for the indexer to list it...' : 'Asking the indexer...'); diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 8698d48f..e33cd904 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -184,7 +184,7 @@ export interface IndexerChange { current: string; removed: number; } -export declare function bindCachesToIndexer(network: string, indexerUrl: string, cacheDir?: string): IndexerChange | undefined; +export declare function bindCachesToIndexer(network: string, indexerUrl: string, root: string): IndexerChange | undefined; export declare function describeIndexerChange(network: string, change: IndexerChange): string; ``` @@ -269,14 +269,14 @@ export interface CliConfig { "indexer-ws"?: string; wallet?: string; } -export declare function loadCliConfig(configDir?: string): CliConfig; +export declare function loadCliConfig(configDir: string): CliConfig; export declare function getEndpointOverridesForNetwork(config: CliConfig, networkName: NetworkName): NetworkEndpointOverrides; export declare function getSdkSetOverride(config: CliConfig, networkName: NetworkName): SdkSet | undefined; export declare function getBlockfrostProjectId(config: CliConfig, networkName: NetworkName): string | undefined; -export declare function saveCliConfig(config: CliConfig, configDir?: string): void; -export declare function getConfigValue(key: string, configDir?: string, scope?: NetworkName): string; -export declare function setConfigValue(key: string, value: string, configDir?: string, scope?: NetworkName): void; -export declare function unsetConfigValue(key: string, configDir?: string, scope?: NetworkName): void; +export declare function saveCliConfig(config: CliConfig, configDir: string): void; +export declare function getConfigValue(key: string, configDir: string, scope?: NetworkName): string; +export declare function setConfigValue(key: string, value: string, configDir: string, scope?: NetworkName): void; +export declare function unsetConfigValue(key: string, configDir: string, scope?: NetworkName): void; export declare function getValidConfigKeys(): readonly string[]; ``` @@ -286,6 +286,7 @@ export declare function getValidConfigKeys(): readonly string[]; import { type ParsedArgs } from "./argv.ts"; import { type PackageGuidance } from "./agent-guidance.ts"; import type { CallContext, CommandOutcome } from "./call-context.ts"; +import type { Host } from "./host.ts"; export interface ParamSchema { readonly type: "string" | "boolean"; readonly enum?: readonly string[]; @@ -363,6 +364,7 @@ export interface ToolArgv { readonly defaultFlags?: Readonly>; } export interface ToolCheckCall { + readonly host: Host; argv(): ParsedArgs; run(args: ParsedArgs): Promise>; } @@ -744,9 +746,10 @@ export interface ShieldedCachedOptions { timeoutMs?: number; forceFresh?: boolean; chainId?: string; + root: string; } export interface EngineReaders { - shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options?: ShieldedCachedOptions): Promise; + shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options: ShieldedCachedOptions): Promise; } export interface BalanceSummary { balances: Map; @@ -771,6 +774,7 @@ export interface TransferParams { onSyncWarning?: (tag: string, message: string) => void; sdkWarnings: CallSdkWarnings; log?: VerboseLog; + root: string; } export interface TransferResult { txHash: string; @@ -789,6 +793,7 @@ export interface DustRegisterOptions { onSyncWarning?: (tag: string, message: string) => void; sdkWarnings: CallSdkWarnings; log?: VerboseLog; + root: string; } export interface DustRegistration { alreadyAvailable: boolean; @@ -816,6 +821,9 @@ export interface ReadOptions { onProgress?: (current: number, highest: number) => void; log?: VerboseLog; } +export interface CachedReadOptions extends ReadOptions { + root: string; +} export interface DustBalance { balance: bigint; availableCoins: number; @@ -836,6 +844,7 @@ export interface WalletSyncHooks { } export interface ShieldedTransferParams extends WalletSyncHooks { seed: Buffer; + root: string; network: NetworkName; networkConfig: NetworkConfig; recipient: string; @@ -847,6 +856,7 @@ export interface ShieldedTransferParams extends WalletSyncHooks { } export interface PrepWallet { seed: Buffer; + root: string; network: NetworkName; networkConfig: NetworkConfig; address: string; @@ -881,12 +891,13 @@ export interface ServedWalletSession { } export interface EngineWallet { unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; - dustBalance(seed: Buffer, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + dustBalance(seed: Buffer, networkConfig: NetworkConfig, options: CachedReadOptions): Promise; transfer(params: TransferParams): Promise; airdrop(params: AirdropParams): Promise; shieldedTransfer(params: ShieldedTransferParams): Promise; registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; - exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options?: { + exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { + root: string; signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; @@ -898,6 +909,7 @@ export interface EngineWallet { }>; openConnector(options: { seed: Buffer; + root: string; network: NetworkName; networkConfig: NetworkConfig; address: string; @@ -908,6 +920,7 @@ export interface EngineWallet { }): Promise; serveWallet(options: { seed: Buffer; + root: string; networkConfig: NetworkConfig; network: NetworkName; address: string; @@ -922,7 +935,7 @@ export interface Engine { readonly readers: EngineReaders; readonly wallet: EngineWallet; } -export declare function sdkSetOf(network: NetworkName): SdkSet; +export declare function sdkSetOf(network: NetworkName, root: string): SdkSet; export type EngineLoader = (set: SdkSet) => Promise; export declare class OtherSdkSetError extends Error { readonly code = "OTHER_SDK_SET"; @@ -931,8 +944,8 @@ export declare class OtherSdkSetError extends Error { constructor(loadedSet: SdkSet, wantedSet: SdkSet, message?: string); } export declare function setEngineLoader(next: EngineLoader): void; -export declare function engineFor(network: NetworkName): Promise; -export declare function preferEngineOf(network: NetworkName): void; +export declare function engineFor(network: NetworkName, root: string): Promise; +export declare function preferEngineOf(network: NetworkName, root: string): void; export declare function anyEngine(): Promise; ``` @@ -1152,8 +1165,8 @@ export interface NetworkConfig { } export declare const SDK_SETS: readonly SdkSet[]; export declare function defaultSdkSetOf(name: NetworkName): SdkSet; -export declare function networksOnSdkSet(set: SdkSet): NetworkName[]; -export declare function sdkSetOfNetwork(name: NetworkName): SdkSet; +export declare function networksOnSdkSet(set: SdkSet, root: string): NetworkName[]; +export declare function sdkSetOfNetwork(name: NetworkName, root: string): SdkSet; export declare function isValidNetworkName(name: string): name is NetworkName; export declare function getNetworkConfig(name: NetworkName): NetworkConfig; export declare function getValidNetworkNames(): readonly string[]; @@ -1193,7 +1206,7 @@ export interface EndpointOverrides { indexerWS?: string; } export declare function endpointFlags(e: EndpointOverrides): Record; -export declare function applyEndpointOverrides(config: NetworkConfig, flagOverrides: EndpointOverrides, networkName: NetworkName, configDir?: string): NetworkConfig; +export declare function applyEndpointOverrides(config: NetworkConfig, flagOverrides: EndpointOverrides, networkName: NetworkName, configDir: string): NetworkConfig; ``` ## `@kuiralabs/midnight-cli-core/lib/network-id` @@ -1254,10 +1267,10 @@ export declare class OfferCoinsInUseError extends Error { readonly offerIds: string[]; constructor(offerIds: string[]); } -export declare function openOffersFile(network: NetworkName, walletAddress: string): string; -export declare function readOpenOffers(network: NetworkName, walletAddress: string): OpenOffer[]; -export declare function recordOpenOffer(network: NetworkName, walletAddress: string, offer: OpenOffer): void; -export declare function closeOpenOffers(network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[]; +export declare function openOffersFile(root: string, network: NetworkName, walletAddress: string): string; +export declare function readOpenOffers(root: string, network: NetworkName, walletAddress: string): OpenOffer[]; +export declare function recordOpenOffer(root: string, network: NetworkName, walletAddress: string, offer: OpenOffer): void; +export declare function closeOpenOffers(root: string, network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[]; export declare function assertSpendsNoOfferCoin(open: readonly OpenOffer[], spent: readonly string[], cancelling?: readonly string[]): void; ``` @@ -1271,10 +1284,11 @@ import type { CallSdkWarnings } from "./sdk-warnings.ts"; import type { WalletSession } from "./wallet-session.ts"; export interface PayingTarget { network: NetworkName; + root: string; networkConfig: NetworkConfig; endpoints: EndpointOverrides; } -export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string): PayingTarget; +export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string): PayingTarget; export interface ServedWallet { port: number; stop: () => Promise; @@ -1338,13 +1352,13 @@ export declare function currentPrompter(): Prompter | null; ## `@kuiralabs/midnight-cli-core/lib/reader-cache-files` ```ts -export declare function dustCacheDir(network: string, cacheDir?: string): string; -export declare function getDustCachePath(network: string, pubkeyHex: string, cacheDir?: string): string; -export declare function clearDustDirectCache(network?: string, pubkeyHex?: string, cacheDir?: string): void; -export declare function getShieldedCachePath(network: string, pubkeyHex: string, cacheDir?: string): string; -export declare function clearShieldedDirectCache(network?: string, pubkeyHex?: string, cacheDir?: string): void; +export declare function dustCacheDir(network: string, root: string): string; +export declare function getDustCachePath(network: string, pubkeyHex: string, root: string): string; +export declare function clearDustDirectCache(network: string | undefined, pubkeyHex: string | undefined, root: string): void; +export declare function getShieldedCachePath(network: string, pubkeyHex: string, root: string): string; +export declare function clearShieldedDirectCache(network: string | undefined, pubkeyHex: string | undefined, root: string): void; export declare const nativeCheckpointName: (pubkeyHex: string) => string; -export declare function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, cacheDir?: string): void; +export declare function clearNativeDustCheckpoint(network: string | undefined, pubkeyHex: string | undefined, root: string): void; ``` ## `@kuiralabs/midnight-cli-core/lib/resolve-network` @@ -1355,11 +1369,11 @@ import { type NetworkName, type NetworkConfig } from "./network.ts"; import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV } from "./settings.ts"; export interface NetworkResolutionContext { args: ParsedArgs; - configDir?: string; + configDir: string; } export declare function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName; export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; -export declare function resolveBlockfrostProjectId(name: NetworkName, configDir?: string, env?: Record): string | undefined; +export declare function resolveBlockfrostProjectId(name: NetworkName, configDir: string, env?: Record): string | undefined; export declare function resolveNetwork(ctx: NetworkResolutionContext): { name: NetworkName; config: NetworkConfig; @@ -1483,10 +1497,6 @@ export declare class NoStateRootError extends Error { readonly code = "NO_STATE_ROOT"; constructor(); } -export declare function setHostPathsSource(next: (() => HostPaths) | null): void; -export declare function hostPaths(): HostPaths; -export declare function stateRoot(): string; -export declare function userHome(): string; ``` ## `@kuiralabs/midnight-cli-core/lib/swap-offer` @@ -1543,12 +1553,12 @@ export interface WalletCacheData { unshielded: string; dust: string; } -export declare function cacheRootDir(cacheDir?: string): string; -export declare function networkCacheFolder(network: string): string; +export declare function cacheRootDir(root: string): string; +export declare function networkCacheFolder(network: string, root: string): string; export declare const CACHE_KEY_PREFIX_LENGTH = 20; export declare function cacheKeyOf(addressOrKey: string): string; -export declare function getCachePath(address: string, network: string, cacheDir?: string): string; -export declare function loadWalletCache(address: string, network: string, cacheDir?: string): WalletCacheData | null; +export declare function getCachePath(address: string, network: string, root: string): string; +export declare function loadWalletCache(address: string, network: string, root: string): WalletCacheData | null; export declare function saveWalletCache(address: string, network: string, facade: { shielded: { serializeState(): Promise; @@ -1559,9 +1569,9 @@ export declare function saveWalletCache(address: string, network: string, facade dust: { serializeState(): Promise; }; -}, cacheDir?: string, chainId?: string): Promise; -export declare function validateWalletCacheChainId(network: string, currentChainId: string | null, cacheDir?: string): string[]; -export declare function clearWalletCache(address?: string, network?: string, cacheDir?: string): void; +}, root: string, chainId?: string): Promise; +export declare function validateWalletCacheChainId(network: string, currentChainId: string | null, root: string): string[]; +export declare function clearWalletCache(address: string | undefined, network: string | undefined, root: string): void; ``` ## `@kuiralabs/midnight-cli-core/lib/wallet-session` @@ -1620,6 +1630,7 @@ export declare function sessionOver(network: NetworkName, opened: OpenedConnecto export interface OpenWalletSessionOptions { seed: Buffer; network: NetworkName; + root: string; networkConfig?: NetworkConfig; forceShielded?: boolean; dustWaitMs?: number; diff --git a/packages/cli-core/src/commands/config.ts b/packages/cli-core/src/commands/config.ts index 5cbc3d46..fec050a6 100644 --- a/packages/cli-core/src/commands/config.ts +++ b/packages/cli-core/src/commands/config.ts @@ -33,16 +33,17 @@ export default async function configCommand(args: ParsedArgs, ctx: CallContext): throw new UsageError(`Invalid network: "${networkFlag}"\nValid networks: ${getValidNetworkNames().join(', ')}`); } const scope = networkFlag as NetworkName | undefined; + const root = ctx.config.paths.stateRoot; if (action === 'get') { - const value = getConfigValue(key, undefined, scope); + const value = getConfigValue(key, root, scope); if (hasFlag(args, 'json')) { ctx.output.result({ action: 'get', key, value }); return; } ctx.output.stdout(value + '\n'); } else if (action === 'unset') { - unsetConfigValue(key, undefined, scope); + unsetConfigValue(key, root, scope); const displayValue = key === 'network' ? '(default)' : '(removed)'; if (hasFlag(args, 'json')) { ctx.output.result({ action: 'unset', key, value: displayValue }); @@ -54,9 +55,9 @@ export default async function configCommand(args: ParsedArgs, ctx: CallContext): if (value === undefined) { throw new UsageError(`Missing value for config set.\nUsage: midnight config set ${key} `); } - setConfigValue(key, value, undefined, scope); + setConfigValue(key, value, root, scope); // A project id is a secret: what was set is said the way `config get` shows it. - const shown = key === 'blockfrost-project-id' ? getConfigValue(key, undefined, scope) : value; + const shown = key === 'blockfrost-project-id' ? getConfigValue(key, root, scope) : value; if (hasFlag(args, 'json')) { ctx.output.result({ action: 'set', key, value: shown }); return; diff --git a/packages/cli-core/src/lib/cache-indexer.ts b/packages/cli-core/src/lib/cache-indexer.ts index 85fc6d83..072e12a8 100644 --- a/packages/cli-core/src/lib/cache-indexer.ts +++ b/packages/cli-core/src/lib/cache-indexer.ts @@ -43,13 +43,13 @@ export interface IndexerChange { } /** - * Makes `network`'s cache directory belong to the indexer at `indexerUrl`. + * Makes `network`'s cache directory, under the state root `root`, belong to the indexer at `indexerUrl`. * Returns what was removed when its state came from another indexer, and * undefined when it already belonged to this one or held nothing. */ -export function bindCachesToIndexer(network: string, indexerUrl: string, cacheDir?: string): IndexerChange | undefined { +export function bindCachesToIndexer(network: string, indexerUrl: string, root: string): IndexerChange | undefined { const current = indexerIdentity(indexerUrl); - const dir = join(cacheRootDir(cacheDir), networkCacheFolder(network)); + const dir = join(cacheRootDir(root), networkCacheFolder(network, root)); const marker = join(dir, MARKER); const recorded = existsSync(marker) ? readFileSync(marker, 'utf-8').trim() : undefined; diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index 983a9615..0a92f429 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -150,7 +150,8 @@ export function createCallContext(parts: CallParts(handler: CommandHandler, args: ParsedArgs, ctx: CallContext): Promise { if (ctx.signal.aborted) throw new CancelledError(); try { - preferEngineOf(resolveNetworkName({ args })); + const root = ctx.config.paths.stateRoot; + preferEngineOf(resolveNetworkName({ args, configDir: root }), root); } catch { /* an invalid --network: the command says so */ } return handler(args, ctx); } diff --git a/packages/cli-core/src/lib/cli-config.ts b/packages/cli-core/src/lib/cli-config.ts index 83634cf7..1b5433f8 100644 --- a/packages/cli-core/src/lib/cli-config.ts +++ b/packages/cli-core/src/lib/cli-config.ts @@ -5,7 +5,6 @@ import { blockfrostNetworks, checkProjectId, maskProjectId, networkOfProjectId } import { type NetworkName, SDK_SETS, getValidNetworkNames, isValidNetworkName } from './network.ts'; import type { SdkSet } from './engine.ts'; import { UsageError } from './errors.ts'; -import { stateRoot } from './state-root.ts'; /** Endpoint overrides for one network. Keys mirror the flag/config names. */ export interface NetworkEndpointOverrides { @@ -73,18 +72,13 @@ function isValidUrl(value: string): boolean { return /^(https?|wss?):\/\/\S+/.test(value); } -function getConfigDir(configDir?: string): string { - return configDir ?? stateRoot(); +function getConfigPath(configDir: string): string { + return path.join(configDir, DEFAULT_CONFIG_FILENAME); } -function getConfigPath(configDir?: string): string { - return path.join(getConfigDir(configDir), DEFAULT_CONFIG_FILENAME); -} - -function ensureConfigDir(configDir?: string): void { - const dir = getConfigDir(configDir); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); +function ensureConfigDir(configDir: string): void { + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true, mode: DIR_MODE }); } } @@ -92,7 +86,7 @@ function ensureConfigDir(configDir?: string): void { * Load CLI config from ~/.midnight/config.json. * Returns defaults if the file doesn't exist. */ -export function loadCliConfig(configDir?: string): CliConfig { +export function loadCliConfig(configDir: string): CliConfig { const configPath = getConfigPath(configDir); if (!fs.existsSync(configPath)) { @@ -193,7 +187,7 @@ export function getBlockfrostProjectId(config: CliConfig, networkName: NetworkNa * Save CLI config to ~/.midnight/config.json. * Creates the directory if it doesn't exist. */ -export function saveCliConfig(config: CliConfig, configDir?: string): void { +export function saveCliConfig(config: CliConfig, configDir: string): void { ensureConfigDir(configDir); const configPath = getConfigPath(configDir); fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n', { mode: FILE_MODE }); @@ -204,7 +198,7 @@ export function saveCliConfig(config: CliConfig, configDir?: string): void { * Endpoint keys are network-scoped: returns the value that applies to the * currently configured network (scoped entry first, then the legacy flat key). */ -export function getConfigValue(key: string, configDir?: string, scope?: NetworkName): string { +export function getConfigValue(key: string, configDir: string, scope?: NetworkName): string { const canonical = resolveConfigKey(key); const config = loadCliConfig(configDir); assertScopeApplies(canonical, scope); @@ -261,7 +255,7 @@ function migrateFlatEndpointsToScope(config: CliConfig, networkName: NetworkName * two can't diverge. Switching `network` first migrates legacy flat endpoint * keys into the old network's scope — they were set while using it. */ -export function setConfigValue(key: string, value: string, configDir?: string, scope?: NetworkName): void { +export function setConfigValue(key: string, value: string, configDir: string, scope?: NetworkName): void { const canonical = resolveConfigKey(key); const config = loadCliConfig(configDir); assertScopeApplies(canonical, scope); @@ -319,7 +313,7 @@ export function setConfigValue(key: string, value: string, configDir?: string, s * legacy flat key (so one unset reliably clears whatever was applying). * For other optional keys: removes the key entirely. */ -export function unsetConfigValue(key: string, configDir?: string, scope?: NetworkName): void { +export function unsetConfigValue(key: string, configDir: string, scope?: NetworkName): void { const canonical = resolveConfigKey(key); const config = loadCliConfig(configDir); assertScopeApplies(canonical, scope); diff --git a/packages/cli-core/src/lib/command-definition.ts b/packages/cli-core/src/lib/command-definition.ts index b4737e96..67396e09 100644 --- a/packages/cli-core/src/lib/command-definition.ts +++ b/packages/cli-core/src/lib/command-definition.ts @@ -14,6 +14,7 @@ import { getValidNetworkNames } from './network.ts'; import { FULL_FLAG, type ParsedArgs } from './argv.ts'; import { type PackageGuidance, type ToolsTableRow, assertDistinctPlaces } from './agent-guidance.ts'; import type { CallContext, CommandOutcome } from './call-context.ts'; +import type { Host } from './host.ts'; /** A parameter as an MCP tool's schema shows it to an agent. */ export interface ParamSchema { @@ -141,6 +142,8 @@ export interface ToolArgv { /** What a tool's check gets besides the call's parameters. */ export interface ToolCheckCall { + /** The host the tool runs in: its paths are where the check reads the wallets and config. */ + readonly host: Host; /** The command's argv for the call, as the tool would run it; a fresh copy each time. */ argv(): ParsedArgs; /** Runs the tool's command with `args`, as the tool runs it (same cancellation), and returns its JSON result. */ diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 5c70bd3e..2816dd7b 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -171,12 +171,14 @@ export interface ShieldedCachedOptions { forceFresh?: boolean; /** Current chain genesis hash — stored on save and checked on load (chain-reset guard). */ chainId?: string; + /** The state root the cache lives under. */ + root: string; } /** mn's own readers of a wallet's chain state, beside the SDK's wallet. */ export interface EngineReaders { /** The shielded NIGHT balance of a seed on a network, reading (and extending) its cache. */ - shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options?: ShieldedCachedOptions): Promise; + shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options: ShieldedCachedOptions): Promise; } // ── The wallet ── @@ -214,6 +216,8 @@ export interface TransferParams { sdkWarnings: CallSdkWarnings; /** The call's verbose lines. */ log?: VerboseLog; + /** The state root the wallet's caches live under. */ + root: string; } export interface TransferResult { @@ -242,6 +246,8 @@ export interface DustRegisterOptions { sdkWarnings: CallSdkWarnings; /** The call's verbose lines. */ log?: VerboseLog; + /** The state root the wallet's caches live under. */ + root: string; } export interface DustRegistration { @@ -297,6 +303,12 @@ export interface ReadOptions { log?: VerboseLog; } +/** A read that keeps its cache under a state root. */ +export interface CachedReadOptions extends ReadOptions { + /** The state root the cache lives under. */ + root: string; +} + /** A wallet's Dust, as mn's reader found it. */ export interface DustBalance { balance: bigint; @@ -341,6 +353,8 @@ export interface WalletSyncHooks { /** A shielded payment of NIGHT from a seed's wallet. */ export interface ShieldedTransferParams extends WalletSyncHooks { seed: Buffer; + /** The state root the wallet's caches and open offers live under. */ + root: string; network: NetworkName; networkConfig: NetworkConfig; /** The recipient's shielded address on `network`. */ @@ -360,6 +374,8 @@ export interface ShieldedTransferParams extends WalletSyncHooks { /** A wallet a test's preparation checks, by its seed and its saved address. */ export interface PrepWallet { seed: Buffer; + /** The state root the wallet's caches live under. */ + root: string; network: NetworkName; networkConfig: NetworkConfig; address: string; @@ -409,7 +425,7 @@ export interface EngineWallet { /** The unshielded balance of an address, through mn's cache. */ unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; /** A seed's Dust, through mn's reader and its cache. */ - dustBalance(seed: Buffer, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + dustBalance(seed: Buffer, networkConfig: NetworkConfig, options: CachedReadOptions): Promise; /** An unshielded payment of NIGHT. */ transfer(params: TransferParams): Promise; /** NIGHT from the genesis wallet (a local chain only). */ @@ -419,15 +435,15 @@ export interface EngineWallet { /** Registers a seed's NIGHT for Dust, unless it has Dust already. */ registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; /** A seed's Dust as a snapshot another wallet restores from. */ - exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options?: { signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void }): Promise; + exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { root: string; signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void }): Promise; /** A test wallet's unshielded NIGHT after a quick sync; its state is saved when it holds some. */ prepNightBalance(wallet: PrepWallet): Promise; /** Makes sure a test wallet has Dust, registering and then waiting up to `waitMs` for it. */ prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAvailable: boolean; dustAvailable: boolean }>; /** The connector over a seed's wallet, synced and its Dust ready, for a command of mn's own. */ - openConnector(options: { seed: Buffer; network: NetworkName; networkConfig: NetworkConfig; address: string; syncMode: 'full' | 'lite'; dustWaitMs?: number; signal?: AbortSignal; onMessage: (message: string) => void }): Promise; + openConnector(options: { seed: Buffer; root: string; network: NetworkName; networkConfig: NetworkConfig; address: string; syncMode: 'full' | 'lite'; dustWaitMs?: number; signal?: AbortSignal; onMessage: (message: string) => void }): Promise; /** Syncs a seed's wallet strictly for mn serve and runs `serve` with it; the wallet stops when `serve` ends. */ - serveWallet(options: { seed: Buffer; networkConfig: NetworkConfig; network: NetworkName; address: string; syncMode: 'full' | 'lite' } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; + serveWallet(options: { seed: Buffer; root: string; networkConfig: NetworkConfig; network: NetworkName; address: string; syncMode: 'full' | 'lite' } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; } /** One SDK set, as mn uses it. */ @@ -440,9 +456,9 @@ export interface Engine { readonly wallet: EngineWallet; } -/** The SDK set a network runs on, as the network table names it. */ -export function sdkSetOf(network: NetworkName): SdkSet { - return sdkSetOfNetwork(network); +/** The SDK set a network runs on, as the network table and the config under the state root `root` name it. */ +export function sdkSetOf(network: NetworkName, root: string): SdkSet { + return sdkSetOfNetwork(network, root); } /** Loads the engine for an SDK set: the host's, which knows the engines it ships. */ @@ -490,14 +506,14 @@ function loadEngine(set: SdkSet): Promise { }); } -/** The engine for a network's SDK set, loaded on first use. */ -export function engineFor(network: NetworkName): Promise { - return loadEngine(sdkSetOf(network)); +/** The engine for a network's SDK set (by the config under the state root `root`), loaded on first use. */ +export function engineFor(network: NetworkName, root: string): Promise { + return loadEngine(sdkSetOf(network, root)); } /** The network a call is for, whose set work every set does alike loads while no engine is loaded. */ -export function preferEngineOf(network: NetworkName): void { - preferred = sdkSetOf(network); +export function preferEngineOf(network: NetworkName, root: string): void { + preferred = sdkSetOf(network, root); } /** diff --git a/packages/cli-core/src/lib/network.ts b/packages/cli-core/src/lib/network.ts index 9a705202..4676eddf 100644 --- a/packages/cli-core/src/lib/network.ts +++ b/packages/cli-core/src/lib/network.ts @@ -71,14 +71,14 @@ export function defaultSdkSetOf(name: NetworkName): SdkSet { return NETWORK_SDK_SETS[name]; } -/** The networks that run on `set` now. */ -export function networksOnSdkSet(set: SdkSet): NetworkName[] { - return VALID_NETWORK_NAMES.filter((name) => sdkSetOfNetwork(name) === set); +/** The networks that run on `set` now, by the config under the state root `root`. */ +export function networksOnSdkSet(set: SdkSet, root: string): NetworkName[] { + return VALID_NETWORK_NAMES.filter((name) => sdkSetOfNetwork(name, root) === set); } -/** The SDK set a network runs on: the one `midnight config set sdk-set` gave it, else the table's. */ -export function sdkSetOfNetwork(name: NetworkName): SdkSet { - return getSdkSetOverride(loadCliConfig(), name) ?? NETWORK_SDK_SETS[name]; +/** The SDK set a network runs on: the one `midnight config set sdk-set` gave it under the state root `root`, else the table's. */ +export function sdkSetOfNetwork(name: NetworkName, root: string): SdkSet { + return getSdkSetOverride(loadCliConfig(root), name) ?? NETWORK_SDK_SETS[name]; } const VALID_NETWORK_NAMES: readonly NetworkName[] = ['preprod', 'preview', 'stagenet', 'undeployed'] as const; @@ -283,7 +283,7 @@ export function applyEndpointOverrides( config: NetworkConfig, flagOverrides: EndpointOverrides, networkName: NetworkName, - configDir?: string, + configDir: string, ): NetworkConfig { const cliConfig = loadCliConfig(configDir); const scoped = getEndpointOverridesForNetwork(cliConfig, networkName); diff --git a/packages/cli-core/src/lib/open-offers.ts b/packages/cli-core/src/lib/open-offers.ts index 7685eb5e..b83c017b 100644 --- a/packages/cli-core/src/lib/open-offers.ts +++ b/packages/cli-core/src/lib/open-offers.ts @@ -7,7 +7,6 @@ import { join } from 'node:path'; import { readJsonIfPresent, writeJsonDurably } from './durable-file.ts'; -import { stateRoot } from './state-root.ts'; import type { NetworkName } from './network.ts'; import type { SwapLeg, SwapTerms } from './swap-offer.ts'; @@ -34,17 +33,17 @@ export class OfferCoinsInUseError extends Error { interface StoredLeg { token: string; amount: string } interface StoredOffer { id: string; terms: { give: StoredLeg; want: StoredLeg }; nullifiers: string[]; madeAt: string; expiresAt: string } -/** The file holding a wallet's open offers on a network; the wallet by its unshielded address there. */ -export function openOffersFile(network: NetworkName, walletAddress: string): string { - return join(stateRoot(), 'swap-offers', network, `${walletAddress}.json`); +/** The file under the state root `root` holding a wallet's open offers on a network; the wallet by its unshielded address there. */ +export function openOffersFile(root: string, network: NetworkName, walletAddress: string): string { + return join(root, 'swap-offers', network, `${walletAddress}.json`); } const leg = (stored: StoredLeg): SwapLeg => ({ token: stored.token, amount: BigInt(stored.amount) }); const stored = (l: SwapLeg): StoredLeg => ({ token: l.token, amount: l.amount.toString() }); /** The wallet's open offers on the network. */ -export function readOpenOffers(network: NetworkName, walletAddress: string): OpenOffer[] { - const file = readJsonIfPresent<{ offers: StoredOffer[] }>(openOffersFile(network, walletAddress)); +export function readOpenOffers(root: string, network: NetworkName, walletAddress: string): OpenOffer[] { + const file = readJsonIfPresent<{ offers: StoredOffer[] }>(openOffersFile(root, network, walletAddress)); return (file?.offers ?? []).map((o) => ({ id: o.id, terms: { give: leg(o.terms.give), want: leg(o.terms.want) }, @@ -54,8 +53,8 @@ export function readOpenOffers(network: NetworkName, walletAddress: string): Ope })); } -function writeOpenOffers(network: NetworkName, walletAddress: string, offers: OpenOffer[]): void { - writeJsonDurably(openOffersFile(network, walletAddress), { +function writeOpenOffers(root: string, network: NetworkName, walletAddress: string, offers: OpenOffer[]): void { + writeJsonDurably(openOffersFile(root, network, walletAddress), { offers: offers.map((o) => ({ id: o.id, terms: { give: stored(o.terms.give), want: stored(o.terms.want) }, @@ -67,16 +66,16 @@ function writeOpenOffers(network: NetworkName, walletAddress: string, offers: Op } /** Records an offer the wallet made. */ -export function recordOpenOffer(network: NetworkName, walletAddress: string, offer: OpenOffer): void { - const offers = readOpenOffers(network, walletAddress).filter((o) => o.id !== offer.id); - writeOpenOffers(network, walletAddress, [...offers, offer]); +export function recordOpenOffer(root: string, network: NetworkName, walletAddress: string, offer: OpenOffer): void { + const offers = readOpenOffers(root, network, walletAddress).filter((o) => o.id !== offer.id); + writeOpenOffers(root, network, walletAddress, [...offers, offer]); } /** Closes the wallet's offers with these ids (taken or cancelled); the ones it had. */ -export function closeOpenOffers(network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[] { - const offers = readOpenOffers(network, walletAddress); +export function closeOpenOffers(root: string, network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[] { + const offers = readOpenOffers(root, network, walletAddress); const closing = offers.filter((o) => ids.includes(o.id)); - if (closing.length > 0) writeOpenOffers(network, walletAddress, offers.filter((o) => !ids.includes(o.id))); + if (closing.length > 0) writeOpenOffers(root, network, walletAddress, offers.filter((o) => !ids.includes(o.id))); return closing; } diff --git a/packages/cli-core/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts index 1963d50e..7d5d7ca2 100644 --- a/packages/cli-core/src/lib/payer.ts +++ b/packages/cli-core/src/lib/payer.ts @@ -13,6 +13,8 @@ import type { WalletSession } from './wallet-session.ts'; /** The network a command acts on, with its endpoints resolved. */ export interface PayingTarget { network: NetworkName; + /** The state root the command's config, wallets and caches live under. */ + root: string; networkConfig: NetworkConfig; /** The endpoints given as flags, which a server started for the command must use too. */ endpoints: EndpointOverrides; @@ -22,9 +24,10 @@ export interface PayingTarget { * --network, else the network set with `midnight config set network`, else * undeployed (as every other command), then explicit endpoint flags over the * defaults. Without endpoint flags, `undeployed` resolves to whatever local - * stack docker shows, which is ambiguous when more than one runs. + * stack docker shows, which is ambiguous when more than one runs. The saved + * network and endpoints are the config's under the state root `root`. */ -export function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string): PayingTarget { +export function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string): PayingTarget { const network = getFlag(args, 'network'); const endpoints: EndpointOverrides = { node: getFlag(args, 'node'), @@ -33,9 +36,10 @@ export function resolvePayingTarget(args: ParsedArgs, command: string, subcomman }; const { name, config: networkConfig } = resolveNetwork({ args: { command, subcommand, positionals: [], flags: { ...(network ? { network } : {}), ...endpointFlags(endpoints) } }, + configDir: root, }); - applyEndpointOverrides(networkConfig, endpoints, name); - return { network: name, networkConfig, endpoints }; + applyEndpointOverrides(networkConfig, endpoints, name, root); + return { network: name, root, networkConfig, endpoints }; } /** A wallet served over the DApp connector's WebSocket, for a script in another process to pay through. */ diff --git a/packages/cli-core/src/lib/reader-cache-files.ts b/packages/cli-core/src/lib/reader-cache-files.ts index bea25e16..663880a9 100644 --- a/packages/cli-core/src/lib/reader-cache-files.ts +++ b/packages/cli-core/src/lib/reader-cache-files.ts @@ -6,20 +6,20 @@ import { existsSync, readdirSync, unlinkSync } from 'node:fs'; import { join } from 'node:path'; import { cacheKeyOf, cacheRootDir, networkCacheFolder } from './wallet-cache.ts'; -/** The folder of a network's reader caches. */ -export function dustCacheDir(network: string, cacheDir?: string): string { - const base = cacheRootDir(cacheDir); - return join(base, networkCacheFolder(network)); +/** The folder of a network's reader caches under the state root `root`. */ +export function dustCacheDir(network: string, root: string): string { + const base = cacheRootDir(root); + return join(base, networkCacheFolder(network, root)); } /** The Dust reader's cache file for a network and Dust public key. */ export function getDustCachePath( network: string, pubkeyHex: string, - cacheDir?: string, + root: string, ): string { const prefix = cacheKeyOf(pubkeyHex); - return join(dustCacheDir(network, cacheDir), `dust-${prefix}.json`); + return join(dustCacheDir(network, root), `dust-${prefix}.json`); } /** @@ -29,14 +29,14 @@ export function getDustCachePath( * - (neither) → all dust-* files across all networks */ export function clearDustDirectCache( - network?: string, - pubkeyHex?: string, - cacheDir?: string, + network: string | undefined, + pubkeyHex: string | undefined, + root: string, ): void { - const base = cacheRootDir(cacheDir); + const base = cacheRootDir(root); if (network && pubkeyHex) { - const path = getDustCachePath(network, pubkeyHex, cacheDir); + const path = getDustCachePath(network, pubkeyHex, root); try { unlinkSync(path); } catch { /* not found is ok */ } return; } @@ -53,7 +53,7 @@ export function clearDustDirectCache( }; if (network) { - wipeNetworkDir(dustCacheDir(network, cacheDir)); + wipeNetworkDir(dustCacheDir(network, root)); return; } @@ -65,19 +65,19 @@ export function clearDustDirectCache( } catch { /* best-effort */ } } -function shieldedCacheDir(network: string, cacheDir?: string): string { - const base = cacheRootDir(cacheDir); - return join(base, networkCacheFolder(network)); +function shieldedCacheDir(network: string, root: string): string { + const base = cacheRootDir(root); + return join(base, networkCacheFolder(network, root)); } /** The shielded reader's cache file for a network and coin public key. */ export function getShieldedCachePath( network: string, pubkeyHex: string, - cacheDir?: string, + root: string, ): string { const prefix = cacheKeyOf(pubkeyHex); - return join(shieldedCacheDir(network, cacheDir), `shielded-${prefix}.json`); + return join(shieldedCacheDir(network, root), `shielded-${prefix}.json`); } /** @@ -87,14 +87,14 @@ export function getShieldedCachePath( * - (neither) → all shielded-* files across all networks */ export function clearShieldedDirectCache( - network?: string, - pubkeyHex?: string, - cacheDir?: string, + network: string | undefined, + pubkeyHex: string | undefined, + root: string, ): void { - const base = cacheRootDir(cacheDir); + const base = cacheRootDir(root); if (network && pubkeyHex) { - const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + const path = getShieldedCachePath(network, pubkeyHex, root); try { unlinkSync(path); } catch { /* not found is ok */ } return; } @@ -111,7 +111,7 @@ export function clearShieldedDirectCache( }; if (network) { - wipeNetworkDir(shieldedCacheDir(network, cacheDir)); + wipeNetworkDir(shieldedCacheDir(network, root)); return; } @@ -132,10 +132,10 @@ export const nativeCheckpointName = (pubkeyHex: string): string => `dust-native- * (neither) → all. Called from `mn cache clear` so clearing the cache also forces * a fresh native sync (and drops a stale checkpoint after a chain reset). */ -export function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, cacheDir?: string): void { - const base = cacheRootDir(cacheDir); +export function clearNativeDustCheckpoint(network: string | undefined, pubkeyHex: string | undefined, root: string): void { + const base = cacheRootDir(root); if (network && pubkeyHex) { - try { unlinkSync(join(base, networkCacheFolder(network), nativeCheckpointName(pubkeyHex))); } catch { /* not found is ok */ } + try { unlinkSync(join(base, networkCacheFolder(network, root), nativeCheckpointName(pubkeyHex))); } catch { /* not found is ok */ } return; } const wipeDir = (dir: string) => { @@ -148,7 +148,7 @@ export function clearNativeDustCheckpoint(network?: string, pubkeyHex?: string, } } catch { /* best-effort */ } }; - if (network) { wipeDir(join(base, networkCacheFolder(network))); return; } + if (network) { wipeDir(join(base, networkCacheFolder(network, root))); return; } if (!existsSync(base)) return; try { for (const net of readdirSync(base)) wipeDir(join(base, net)); } catch { /* best-effort */ } } diff --git a/packages/cli-core/src/lib/resolve-network.ts b/packages/cli-core/src/lib/resolve-network.ts index ccf8072e..78be4c86 100644 --- a/packages/cli-core/src/lib/resolve-network.ts +++ b/packages/cli-core/src/lib/resolve-network.ts @@ -18,7 +18,8 @@ import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV, settings } export interface NetworkResolutionContext { args: ParsedArgs; - configDir?: string; + /** The state root whose config.json holds the saved network and endpoints. */ + configDir: string; } /** @@ -60,7 +61,7 @@ export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; */ export function resolveBlockfrostProjectId( name: NetworkName, - configDir?: string, + configDir: string, env: Record = { [BLOCKFROST_PROJECT_ID_ENV]: settings().blockfrostProjectId, [SHARED_BLOCKFROST_PROJECT_ID_ENV]: settings().sharedBlockfrostProjectId, diff --git a/packages/cli-core/src/lib/state-root.ts b/packages/cli-core/src/lib/state-root.ts index d4a8c102..1e627a4f 100644 --- a/packages/cli-core/src/lib/state-root.ts +++ b/packages/cli-core/src/lib/state-root.ts @@ -1,8 +1,7 @@ // Where mn keeps its state, as the host says: the shell's is ~/.midnight, a -// consumer's is its own. Each owner builds its paths under this -// root; no library computes a path from the home directory itself. The source -// is read as each path is built, so a host that changes HOME mid-run (the test -// run does) is followed. With no source, a library refuses instead of guessing. +// consumer's is its own. Each owner builds its paths under the root it is +// given (host.paths()); no library computes a path from the home directory +// itself. A host that gave no paths refuses instead of guessing. export interface HostPaths { /** The state root: config, wallets, keystore, caches, localnet, accounts. */ @@ -14,31 +13,8 @@ export interface HostPaths { export class NoStateRootError extends Error { readonly code = 'NO_STATE_ROOT'; constructor() { - super('No state root: the host gave mn no place to keep its state (setHostPathsSource).'); + super('No state root: the host gave mn no place to keep its state (createHost paths).'); this.name = 'NoStateRootError'; Object.setPrototypeOf(this, NoStateRootError.prototype); } } - -let source: (() => HostPaths) | null = null; - -/** Where the host's paths come from from now on; null for none. */ -export function setHostPathsSource(next: (() => HostPaths) | null): void { - source = next; -} - -/** The paths the host gives now: its state root and the user's home. */ -export function hostPaths(): HostPaths { - if (source === null) throw new NoStateRootError(); - return source(); -} - -/** The state root the host gave. */ -export function stateRoot(): string { - return hostPaths().stateRoot; -} - -/** The user's home the host gave. */ -export function userHome(): string { - return hostPaths().home; -} diff --git a/packages/cli-core/src/lib/wallet-cache.ts b/packages/cli-core/src/lib/wallet-cache.ts index b9315d10..7afd9457 100644 --- a/packages/cli-core/src/lib/wallet-cache.ts +++ b/packages/cli-core/src/lib/wallet-cache.ts @@ -6,7 +6,6 @@ import { join, dirname } from 'node:path'; import { randomBytes } from 'node:crypto'; import { CACHE_VERSION, CACHE_DIR_NAME, DIR_MODE, FILE_MODE } from './constants.ts'; -import { stateRoot } from './state-root.ts'; import { defaultSdkSetOf, isValidNetworkName, sdkSetOfNetwork } from './network.ts'; export interface WalletCacheData { @@ -30,19 +29,20 @@ interface CacheFile { wallets: WalletCacheData; } -/** The cache folder: `cacheDir` when given, else the state root's. Every wallet cache, the Dust and shielded ones and the indexer marker included, lives under it. */ -export function cacheRootDir(cacheDir?: string): string { - return cacheDir ?? join(stateRoot(), CACHE_DIR_NAME); +/** The cache folder under the state root `root`. Every wallet cache, the Dust and shielded ones and the indexer marker included, lives under it. */ +export function cacheRootDir(root: string): string { + return join(root, CACHE_DIR_NAME); } /** * A network's folder under the cache folder: the network's name, or * `.` while `midnight config set sdk-set` runs it on another SDK - * set, so one set never reads the state the other wrote. + * set, so one set never reads the state the other wrote. The set is the one + * the config under the state root `root` gives. */ -export function networkCacheFolder(network: string): string { +export function networkCacheFolder(network: string, root: string): string { if (!isValidNetworkName(network)) return network; - const set = sdkSetOfNetwork(network); + const set = sdkSetOfNetwork(network, root); return set === defaultSdkSetOf(network) ? network : `${network}.${set}`; } @@ -58,10 +58,10 @@ export function cacheKeyOf(addressOrKey: string): string { * Derive the cache file path for a given address and network. * Path: //.json */ -export function getCachePath(address: string, network: string, cacheDir?: string): string { - const base = cacheRootDir(cacheDir); +export function getCachePath(address: string, network: string, root: string): string { + const base = cacheRootDir(root); const prefix = cacheKeyOf(address); - return join(base, networkCacheFolder(network), `${prefix}.json`); + return join(base, networkCacheFolder(network, root), `${prefix}.json`); } /** @@ -71,9 +71,9 @@ export function getCachePath(address: string, network: string, cacheDir?: string export function loadWalletCache( address: string, network: string, - cacheDir?: string, + root: string, ): WalletCacheData | null { - const path = getCachePath(address, network, cacheDir); + const path = getCachePath(address, network, root); if (!existsSync(path)) return null; @@ -115,7 +115,7 @@ export async function saveWalletCache( address: string, network: string, facade: { shielded: { serializeState(): Promise }; unshielded: { serializeState(): Promise }; dust: { serializeState(): Promise } }, - cacheDir?: string, + root: string, chainId?: string, ): Promise { const [shielded, unshielded, dust] = await Promise.all([ @@ -133,7 +133,7 @@ export async function saveWalletCache( ...(chainId ? { chainId } : {}), }; - const path = getCachePath(address, network, cacheDir); + const path = getCachePath(address, network, root); const dir = dirname(path); // Ensure directory exists @@ -166,13 +166,13 @@ export async function saveWalletCache( export function validateWalletCacheChainId( network: string, currentChainId: string | null, - cacheDir?: string, + root: string, ): string[] { // Caller fetches the chain's current genesis hash once and passes it in. if (!currentChainId) return []; // node unreachable — skip validation - const base = cacheRootDir(cacheDir); - const dir = join(base, networkCacheFolder(network)); + const base = cacheRootDir(root); + const dir = join(base, networkCacheFolder(network, root)); if (!existsSync(dir)) return []; const wiped: string[] = []; @@ -201,19 +201,19 @@ export function validateWalletCacheChainId( * If only network is provided, delete all caches for that network. * If neither is provided, delete all caches. */ -export function clearWalletCache(address?: string, network?: string, cacheDir?: string): void { - const base = cacheRootDir(cacheDir); +export function clearWalletCache(address: string | undefined, network: string | undefined, root: string): void { + const base = cacheRootDir(root); if (address && network) { // Delete specific cache file - const path = getCachePath(address, network, cacheDir); + const path = getCachePath(address, network, root); try { unlinkSync(path); } catch { /* not found is ok */ } return; } if (network) { // Delete all caches for a network - const dir = join(base, networkCacheFolder(network)); + const dir = join(base, networkCacheFolder(network, root)); if (!existsSync(dir)) return; try { for (const file of readdirSync(dir)) { diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index ad6813b2..b3f9e75c 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -221,6 +221,8 @@ export interface OpenWalletSessionOptions { /** The wallet's seed: 64 bytes from a mnemonic, or 32 raw. */ seed: Buffer; network: NetworkName; + /** The state root the wallet's config and caches live under. */ + root: string; /** The network's endpoints; when absent, as a command without endpoint flags resolves them (the saved config, then the defaults). */ networkConfig?: NetworkConfig; /** Whether to sync the shielded wallet; off where the network has no shielded faucet, unless forced. */ @@ -235,17 +237,18 @@ export interface OpenWalletSessionOptions { /** * Opens a seed's wallet on a network: synced, its Dust ready. The host must - * have installed its engine loader, settings and state root first, as the CLI - * does at start. + * have installed its engine loader and settings first, as the CLI does at + * start. */ export async function openWalletSession(options: OpenWalletSessionOptions): Promise { - const { seed, network, signal } = options; + const { seed, network, root, signal } = options; throwIfCancelled(signal); const networkConfig = options.networkConfig - ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } } }).config; - const engine = await engineFor(network); + ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } }, configDir: root }).config; + const engine = await engineFor(network, root); const open = () => engine.wallet.openConnector({ seed, + root, network, networkConfig, address: engine.keys.unshieldedAddress(seed, network), diff --git a/packages/engine-beta/api-report.md b/packages/engine-beta/api-report.md index e0e023b3..99f49256 100644 --- a/packages/engine-beta/api-report.md +++ b/packages/engine-beta/api-report.md @@ -188,9 +188,9 @@ export interface DustCacheEntry { } export declare function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string; export declare function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadDustCache(network: string, pubkeyHex: string, cacheDir?: string): DustCacheEntry | null; -export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string, retention?: DustRetention): void; -export declare function validateDustCacheChainId(network: string, currentChainId: string | null, cacheDir?: string): string[]; +export declare function loadDustCache(network: string, pubkeyHex: string, root: string): DustCacheEntry | null; +export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, root: string, chainId?: string, retention?: DustRetention): void; +export declare function validateDustCacheChainId(network: string, currentChainId: string | null, root: string): string[]; ``` ## `@kuiralabs/midnight-engine-beta/dust-export` @@ -202,13 +202,14 @@ import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustExportOptions { + root: string; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; repository?: WalletDataRepository; - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; log?: VerboseLog; } -export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options?: DustExportOptions): Promise; +export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options: DustExportOptions): Promise; ``` ## `@kuiralabs/midnight-engine-beta/dust-register` @@ -242,7 +243,7 @@ interface NativeFetchOptions { initialRetention?: DustRetention; signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; - cacheDir?: string; + root: string; } export declare function resolveSidecarBinary(): string | null; export declare function platformPackageBinary(fromUrl: string): string | null; @@ -294,7 +295,7 @@ export interface FacadeBundle { indexerWsUrl?: string; emptyStreams?: EmptyStreams; } -export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, cache?: WalletCacheData | null, log?: VerboseLog): Promise; +export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, cache?: WalletCacheData | null, log?: VerboseLog): Promise; export interface FacadeDustSnapshot { publicKey: { publicKey: string; @@ -434,11 +435,11 @@ export interface ShieldedCacheEntry { lastAppliedEventId: number; } export declare function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadShieldedCache(network: string, pubkeyHex: string, cacheDir?: string, expectedChainId?: string): ShieldedCacheEntry | null; -export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string): void; +export declare function loadShieldedCache(network: string, pubkeyHex: string, root: string, expectedChainId?: string): ShieldedCacheEntry | null; +export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, root: string, chainId?: string): void; export type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; import type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options?: ShieldedCachedOptions): Promise; +export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options: ShieldedCachedOptions): Promise; ``` ## `@kuiralabs/midnight-engine-beta/sign-recipe` @@ -504,8 +505,8 @@ import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subsc import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; -import type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustView extends DustBalance { state: ledger.DustLocalState; } @@ -515,11 +516,12 @@ export interface FacadeLease { } export interface InvalidationScope { network: NetworkConfig; + root: string; seed?: Buffer; address?: string; kinds?: ReadonlyArray<"dust" | "unshielded" | "facade">; } -export interface FacadeOptions extends ReadOptions { +export interface FacadeOptions extends CachedReadOptions { syncMode?: SyncMode; requireStrictSync?: boolean; readOnly?: boolean; @@ -542,13 +544,12 @@ export interface RepoDeps { signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - cacheDir?: string; + root: string; log?: VerboseLog; }) => Promise; fetchChainId?: (nodeWsUrl: string) => Promise; fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; - cacheDir?: string; } export declare class WalletDataRepository { private readonly now; @@ -558,17 +559,16 @@ export declare class WalletDataRepository { private readonly fetchChainId; private readonly fetchEventTip; private readonly fetchProtocolVersion; - private readonly cacheDir; private readonly dustMemo; private readonly unshieldedMemo; private readonly tipMemo; constructor(deps?: RepoDeps); private keepCachesOfThisIndexer; - walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise; + walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise; private freshWalletOnDustCheckpoint; - dust(seed: Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; + dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise; unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; - withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts?: FacadeOptions): Promise; + withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts: FacadeOptions): Promise; invalidate(scope: InvalidationScope): void; resetTipMemo(): void; private tryMemo; diff --git a/packages/engine-beta/src/dust-direct-cache.ts b/packages/engine-beta/src/dust-direct-cache.ts index 09f30bbc..7bda17bb 100644 --- a/packages/engine-beta/src/dust-direct-cache.ts +++ b/packages/engine-beta/src/dust-direct-cache.ts @@ -73,9 +73,9 @@ export function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string { export function loadDustCache( network: string, pubkeyHex: string, - cacheDir?: string, + root: string, ): DustCacheEntry | null { - const path = getDustCachePath(network, pubkeyHex, cacheDir); + const path = getDustCachePath(network, pubkeyHex, root); if (!existsSync(path)) return null; try { @@ -111,7 +111,7 @@ export function saveDustCache( pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, - cacheDir?: string, + root: string, chainId?: string, retention: DustRetention = EMPTY_RETENTION, ): void { @@ -127,7 +127,7 @@ export function saveDustCache( ...(chainId ? { chainId } : {}), }; - const path = getDustCachePath(network, pubkeyHex, cacheDir); + const path = getDustCachePath(network, pubkeyHex, root); const dir = dirname(path); if (!existsSync(dir)) { @@ -153,13 +153,13 @@ export function saveDustCache( export function validateDustCacheChainId( network: string, currentChainId: string | null, - cacheDir?: string, + root: string, ): string[] { // Caller fetches the chain's current genesis hash once and passes it in. // A null hash (node unreachable) skips validation — proceed best-effort. if (!currentChainId) return []; - const dir = dustCacheDir(network, cacheDir); + const dir = dustCacheDir(network, root); if (!existsSync(dir)) return []; const wiped: string[] = []; diff --git a/packages/engine-beta/src/dust-export.ts b/packages/engine-beta/src/dust-export.ts index dca16597..b4611179 100644 --- a/packages/engine-beta/src/dust-export.ts +++ b/packages/engine-beta/src/dust-export.ts @@ -27,6 +27,8 @@ export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export interface DustExportOptions { + /** The state root the Dust cache lives under. */ + root: string; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; /** Injectable for tests; defaults to the process-wide repository. */ @@ -37,14 +39,14 @@ export interface DustExportOptions { * The default touches the node relay (building a facade opens its API-WS), so * tests stub this to stay offline. */ - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; /** The call's verbose lines. */ log?: VerboseLog; } /** Build a fresh facade from keys and read its base (empty) dust snapshot. */ -async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, log?: VerboseLog): Promise { - const bundle = await buildFacade(seedBuffer, networkConfig, null, log); +async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog): Promise { + const bundle = await buildFacade(seedBuffer, networkConfig, root, null, log); try { return await (bundle.facade as unknown as { dust: { serializeState(): Promise }; @@ -69,18 +71,19 @@ export async function exportDustSnapshot( seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, - options: DustExportOptions = {}, + options: DustExportOptions, ): Promise { const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); const repo = options.repository ?? defaultRepository(); const view = await repo.dust(seedBuffer, networkConfig, { + root: options.root, signal: options.signal, onProgress: options.onProgress, log: options.log, }); - const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.log); + const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.root, options.log); // Overlay whenever at least one event has been folded in. For a wallet with no // dust events yet (lastAppliedEventId -1) the fresh base snapshot is already the diff --git a/packages/engine-beta/src/dust-register.ts b/packages/engine-beta/src/dust-register.ts index 5b149356..4d30bfaf 100644 --- a/packages/engine-beta/src/dust-register.ts +++ b/packages/engine-beta/src/dust-register.ts @@ -14,7 +14,7 @@ export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight- export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { - const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log } = options; + const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root } = options; const stopListening = sdkWarnings.listen(onSyncWarning); try { const { result, dustBalance } = await defaultRepository().withFacade( @@ -35,6 +35,7 @@ export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, o return { result, dustBalance: finalState.dust.balance(new Date()) }; }, { + root, syncMode: 'lite', requireStrictSync: true, signal, diff --git a/packages/engine-beta/src/dust-sync-native.ts b/packages/engine-beta/src/dust-sync-native.ts index d648988d..8779b2f9 100644 --- a/packages/engine-beta/src/dust-sync-native.ts +++ b/packages/engine-beta/src/dust-sync-native.ts @@ -41,8 +41,8 @@ interface NativeFetchOptions { initialRetention?: DustRetention; signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; - /** The wallet's cache folder (the state root's when absent): the checkpoint lives beside the other Dust caches. */ - cacheDir?: string; + /** The state root: the checkpoint lives beside the other Dust caches under it. */ + root: string; } /** @@ -125,8 +125,8 @@ function readCheckpointCursor(path: string): number { /** The sidecar's checkpoint file for a Dust key, beside the other Dust caches. */ -function nativeCheckpointPath(networkName: string, pubkeyHex: string, cacheDir?: string): string { - const dir = join(cacheRootDir(cacheDir), networkCacheFolder(networkName)); +function nativeCheckpointPath(networkName: string, pubkeyHex: string, root: string): string { + const dir = join(cacheRootDir(root), networkCacheFolder(networkName, root)); if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE }); return join(dir, nativeCheckpointName(pubkeyHex)); } @@ -150,7 +150,7 @@ export function runDustSyncNative( const networkName = network.networkId.toLowerCase(); const pubkeyHex = dustPublicKeyHexFromSeed(seed); - const out = nativeCheckpointPath(networkName, pubkeyHex, opts.cacheDir); + const out = nativeCheckpointPath(networkName, pubkeyHex, opts.root); // Resume selection (out == resume file; the sidecar reads it once at start, // then overwrites it with its own checkpoints — kill-safe at this path): diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts index 4e13b031..80c08532 100644 --- a/packages/engine-beta/src/facade.ts +++ b/packages/engine-beta/src/facade.ts @@ -72,13 +72,15 @@ export interface FacadeBundle { * * When `cache` is provided, wallets are restored from serialized state * instead of starting fresh — the SDK then only syncs new transactions - * since the last checkpoint. + * since the last checkpoint, with the Dust checkpoint kept under the state + * root `root` bridged in when it is ahead. * * Its diagnostics go to `log`, the call's verbose lines. */ export async function buildFacade( seedBuffer: Buffer, networkConfig: NetworkConfig, + root: string, cache?: WalletCacheData | null, log?: VerboseLog, ): Promise { @@ -129,7 +131,7 @@ export async function buildFacade( // register) benefit from the indexer-direct reader's checkpoint without // re-implementing the whole transaction flow. const dustPublicKey = secretKeys.dustSecretKey.publicKey; - const effectiveCache = cache ? maybeBridgeDustCache(cache, networkConfig, dustPublicKey, log) : null; + const effectiveCache = cache ? maybeBridgeDustCache(cache, networkConfig, dustPublicKey, root, log) : null; // Attempt cache restore — fall back to fresh build on any deserialization error. let restoredFromCache = false; @@ -226,12 +228,13 @@ function maybeBridgeDustCache( cache: WalletCacheData, networkConfig: NetworkConfig, dustPublicKey: ledger.DustPublicKey, + root: string, log?: VerboseLog, ): WalletCacheData { try { const networkName = networkConfig.networkId.toLowerCase(); const pubkeyHex = dustPublicKeyHex(dustPublicKey); - const direct = loadDustCache(networkName, pubkeyHex); + const direct = loadDustCache(networkName, pubkeyHex, root); if (!direct) return cache; // Only overlay when dust-direct is AHEAD of the facade cache's own offset — a prior diff --git a/packages/engine-beta/src/shielded-direct-cache.ts b/packages/engine-beta/src/shielded-direct-cache.ts index f27e9199..40f4c6f4 100644 --- a/packages/engine-beta/src/shielded-direct-cache.ts +++ b/packages/engine-beta/src/shielded-direct-cache.ts @@ -62,10 +62,10 @@ export function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string { export function loadShieldedCache( network: string, pubkeyHex: string, - cacheDir?: string, + root: string, expectedChainId?: string, ): ShieldedCacheEntry | null { - const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + const path = getShieldedCachePath(network, pubkeyHex, root); if (!existsSync(path)) return null; try { @@ -92,7 +92,7 @@ export function saveShieldedCache( pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, - cacheDir?: string, + root: string, chainId?: string, ): void { const data: ShieldedCacheFile = { @@ -105,7 +105,7 @@ export function saveShieldedCache( ...(chainId ? { chainId } : {}), }; - const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + const path = getShieldedCachePath(network, pubkeyHex, root); const dir = dirname(path); if (!existsSync(dir)) { @@ -137,17 +137,17 @@ export async function readShieldedBalanceCached( seedBuffer: Buffer, network: string, indexerWS: string, - options: ShieldedCachedOptions = {}, + options: ShieldedCachedOptions, ): Promise { const secretKeys = ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(seedBuffer)); const pubkeyHex = secretKeys.coinPublicKey; // State resumed from another indexer's event ids would replay the wrong events. - bindCachesToIndexer(network, indexerWS); - let cached = options.forceFresh ? null : loadShieldedCache(network, pubkeyHex, undefined, options.chainId); + bindCachesToIndexer(network, indexerWS, options.root); + let cached = options.forceFresh ? null : loadShieldedCache(network, pubkeyHex, options.root, options.chainId); // A cursor past the chain's latest event: the chain was reset under the cache. if (cached && isCursorBeyondTip(cached.lastAppliedEventId, await fetchEventTip(indexerWS, 'zswap'))) { - clearShieldedDirectCache(network, pubkeyHex); + clearShieldedDirectCache(network, pubkeyHex, options.root); cached = null; } const startFromId = cached ? cached.lastAppliedEventId + 1 : 0; @@ -161,16 +161,16 @@ export async function readShieldedBalanceCached( // Persist after each chunk so a Ctrl+C / kill during a cold ~70s sync // doesn't lose progress — the next call resumes from the last checkpoint. onCheckpoint: (state, lastAppliedEventId) => { - try { saveShieldedCache(network, pubkeyHex, state, lastAppliedEventId, undefined, options.chainId); } catch { /* best-effort */ } + try { saveShieldedCache(network, pubkeyHex, state, lastAppliedEventId, options.root, options.chainId); } catch { /* best-effort */ } }, }); // Only write if we advanced or this is a first sync. If we had a cache and zero // new events arrived, leave the on-disk file untouched. if (result.lastAppliedEventId >= 0) { - saveShieldedCache(network, pubkeyHex, result.state, result.lastAppliedEventId, undefined, options.chainId); + saveShieldedCache(network, pubkeyHex, result.state, result.lastAppliedEventId, options.root, options.chainId); } else if (!cached) { - saveShieldedCache(network, pubkeyHex, result.state, -1, undefined, options.chainId); + saveShieldedCache(network, pubkeyHex, result.state, -1, options.root, options.chainId); } return { diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index 20e93074..aa670349 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -436,6 +436,7 @@ export async function executeTransfer(params: TransferParams): Promise void; /** Repo passes a callback to persist incremental progress during long syncs. */ onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - /** The cache folder the repository keeps; the native sidecar keeps its checkpoint there. */ - cacheDir?: string; + /** The state root of the caches; the native sidecar keeps its checkpoint beside them. */ + root: string; /** The call's verbose lines. */ log?: VerboseLog; }, @@ -144,8 +146,6 @@ export interface RepoDeps { fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; /** Chain protocol-version fetcher (ledger-9-only guard). Default: indexer `block { protocolVersion }`. */ fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; - /** Override cache directory (tests use a tmp dir). */ - cacheDir?: string; } // ── Implementation ──────────────────────────────────────── @@ -191,7 +191,6 @@ export class WalletDataRepository { private readonly fetchChainId: NonNullable; private readonly fetchEventTip: NonNullable; private readonly fetchProtocolVersion: NonNullable; - private readonly cacheDir: string | undefined; private readonly dustMemo = new Map>(); private readonly unshieldedMemo = new Map>(); @@ -205,7 +204,6 @@ export class WalletDataRepository { this.fetchChainId = deps.fetchChainId ?? getChainGenesisHash; this.fetchEventTip = deps.fetchEventTip ?? fetchEventTip; this.fetchProtocolVersion = deps.fetchProtocolVersion ?? fetchProtocolVersion; - this.cacheDir = deps.cacheDir; } /** @@ -213,8 +211,8 @@ export class WalletDataRepository { * state read from another indexer is dropped before it is loaded, and the * caller is told why this sync is a full one. */ - private keepCachesOfThisIndexer(networkName: string, network: NetworkConfig, onStatus?: (s: string) => void): void { - const change = bindCachesToIndexer(networkName, network.indexerWS, this.cacheDir); + private keepCachesOfThisIndexer(networkName: string, network: NetworkConfig, root: string, onStatus?: (s: string) => void): void { + const change = bindCachesToIndexer(networkName, network.indexerWS, root); if (change) onStatus?.(describeIndexerChange(networkName, change)); } @@ -229,18 +227,19 @@ export class WalletDataRepository { /** * The saved state a wallet restores from: its own, else a new wallet's on * the Dust checkpoint (see freshWalletOnDustCheckpoint). Null builds it from - * its keys. Every facade mn starts for writing starts from this. Building - * that new wallet's diagnostics go to `log`. + * its keys. Every facade mn starts for writing starts from this; both are + * read under the state root `root`. Building that new wallet's diagnostics + * go to `log`. */ - async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise { - return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, this.cacheDir) - ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, log); + async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, root) + ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, root, log); } - private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise { - const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), this.cacheDir); + private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), root); if (!checkpoint || checkpoint.lastAppliedEventId < 0) return null; - const fresh = await buildFacade(seed, network, null, log); + const fresh = await buildFacade(seed, network, root, null, log); try { const { shielded, unshielded, dust } = fresh.facade as unknown as Record<'shielded' | 'unshielded' | 'dust', { serializeState(): Promise }>; const [shieldedState, unshieldedState, dustState] = await Promise.all([shielded.serializeState(), unshielded.serializeState(), dust.serializeState()]); @@ -252,7 +251,7 @@ export class WalletDataRepository { // ── Reads ───────────────────────────────────────── - async dust(seed: Buffer, network: NetworkConfig, opts: ReadOptions = {}): Promise { + async dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise { const networkName = networkNameOf(network); await assertLedgerSupported(networkName, network, this.fetchProtocolVersion, opts.signal); const pubkeyHex = dustPublicKeyHexFromSeed(seed); @@ -268,15 +267,15 @@ export class WalletDataRepository { // stale-chain dust files, and persist the same hash on every save so the // guard has something to compare on the next run. const currentChainId = await this.fetchChainId(network.node).catch(() => null); - validateDustCacheChainId(networkName, currentChainId, this.cacheDir); - this.keepCachesOfThisIndexer(networkName, network, opts.onStatus); + validateDustCacheChainId(networkName, currentChainId, opts.root); + this.keepCachesOfThisIndexer(networkName, network, opts.root, opts.onStatus); const chainId = currentChainId ?? undefined; - let cached = opts.forceFresh ? null : loadDustCache(networkName, pubkeyHex, this.cacheDir); + let cached = opts.forceFresh ? null : loadDustCache(networkName, pubkeyHex, opts.root); // A cursor past the chain's latest event: the chain was reset under the // cache (the genesis check above can't tell when the hash is reused). if (cached && isCursorBeyondTip(cached.lastAppliedEventId, await this.fetchEventTip(network.indexerWS, 'dust'))) { - clearDustDirectCache(networkName, pubkeyHex, this.cacheDir); + clearDustDirectCache(networkName, pubkeyHex, opts.root); cached = null; } const startedFromCache = cached !== null; @@ -302,7 +301,7 @@ export class WalletDataRepository { ); result = await this.fetchDust(seed, network, { - cacheDir: this.cacheDir, + root: opts.root, startFromId, initialState: cached?.state, initialRetention: cached?.retention, @@ -320,7 +319,7 @@ export class WalletDataRepository { // Persist after each chunk so a Ctrl+C / process kill / SIGTERM // doesn't lose 100k events of work. onCheckpoint: (state, lastAppliedEventId, retention) => { - try { saveDustCache(networkName, pubkeyHex, state, lastAppliedEventId, this.cacheDir, chainId, retention); } catch { /* best-effort */ } + try { saveDustCache(networkName, pubkeyHex, state, lastAppliedEventId, opts.root, chainId, retention); } catch { /* best-effort */ } }, }); @@ -331,7 +330,7 @@ export class WalletDataRepository { ? result.lastAppliedEventId : (cached?.lastAppliedEventId ?? -1); if (result.lastAppliedEventId >= 0 || !cached) { - try { saveDustCache(networkName, pubkeyHex, result.state, lastAppliedEventId, this.cacheDir, chainId, result.retention); } catch { /* best-effort */ } + try { saveDustCache(networkName, pubkeyHex, result.state, lastAppliedEventId, opts.root, chainId, result.retention); } catch { /* best-effort */ } } totalEventsApplied += result.eventCount; @@ -340,7 +339,7 @@ export class WalletDataRepository { if (stalledWindows >= DUST_STALLED_WINDOWS || this.now() - startedAt >= DUST_SYNC_BUDGET_MS) break; // Reload for the next iteration so cached.state is the latest checkpoint. - cached = loadDustCache(networkName, pubkeyHex, this.cacheDir); + cached = loadDustCache(networkName, pubkeyHex, opts.root); } if (!result) throw new Error('Dust sync exhausted retries without producing a result'); @@ -414,7 +413,7 @@ export class WalletDataRepository { seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, - opts: FacadeOptions = {}, + opts: FacadeOptions, ): Promise { const syncMode = opts.syncMode ?? 'full'; const requireStrictSync = opts.requireStrictSync ?? true; @@ -429,8 +428,8 @@ export class WalletDataRepository { await assertLedgerSupported(networkName, network, this.fetchProtocolVersion, opts.signal); const currentChainId = await this.fetchChainId(network.node).catch(() => null); - validateWalletCacheChainId(networkName, currentChainId, this.cacheDir); - this.keepCachesOfThisIndexer(networkName, network, opts.onStatus); + validateWalletCacheChainId(networkName, currentChainId, opts.root); + this.keepCachesOfThisIndexer(networkName, network, opts.root, opts.onStatus); const chainId = currentChainId ?? undefined; // ── Pre-prime the dust-direct cache for write-mode borrowers ── @@ -439,7 +438,7 @@ export class WalletDataRepository { // near-tip. Read-only borrowers skip it. if (writeMode && !opts.noPrime && !opts.forceFresh) { try { - await this.dust(seed, network, { signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch (err) { // Pre-prime is best-effort — the actual sync below will re-attempt // anyway. Surface the error only via onSyncWarning if anyone cares. @@ -462,8 +461,8 @@ export class WalletDataRepository { throwIfCancelled(opts.signal); const cacheBeforeBuild = opts.forceFresh ? null - : await this.walletStateToRestore(seed, network, networkName, opts.log); - bundle = await buildFacade(seed, network, cacheBeforeBuild, opts.log); + : await this.walletStateToRestore(seed, network, networkName, opts.root, opts.log); + bundle = await buildFacade(seed, network, opts.root, cacheBeforeBuild, opts.log); try { syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, @@ -481,12 +480,12 @@ export class WalletDataRepository { opts.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); await stopFacade(bundle).catch(() => {}); bundle = undefined; - clearWalletCache(address, networkName, this.cacheDir); - clearDustDirectCache(networkName, dustPublicKeyHexFromSeed(seed), this.cacheDir); + clearWalletCache(address, networkName, opts.root); + clearDustDirectCache(networkName, dustPublicKeyHexFromSeed(seed), opts.root); // Re-prime the dust cache so the next attempt restores from a // current checkpoint instead of a full SDK resync. try { - await this.dust(seed, network, { signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch { /* best-effort */ } continue; } @@ -494,7 +493,7 @@ export class WalletDataRepository { if (attempt < SYNC_MAX_ATTEMPTS && String(err?.message ?? '').includes('timed out')) { // Save partial sync progress to cache before retrying so the next // attempt resumes from the latest event id. - try { await saveWalletCache(address, networkName, bundle.facade, this.cacheDir, chainId); } catch { /* best-effort */ } + try { await saveWalletCache(address, networkName, bundle.facade, opts.root, chainId); } catch { /* best-effort */ } opts.onStatus?.(`Sync timed out, retrying (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); await stopFacade(bundle).catch(() => {}); bundle = undefined; @@ -530,8 +529,8 @@ export class WalletDataRepository { bundle = undefined; await new Promise((r) => setTimeout(r, COLD_START_DELAY_MS)); throwIfCancelled(opts.signal); - const retryCache = loadWalletCache(address, networkName, this.cacheDir); - bundle = await buildFacade(seed, network, retryCache, opts.log); + const retryCache = loadWalletCache(address, networkName, opts.root); + bundle = await buildFacade(seed, network, opts.root, retryCache, opts.log); syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, onSyncDetail: opts.onSyncDetail, @@ -544,9 +543,9 @@ export class WalletDataRepository { } if (!opts.skipAutoSave) { - try { await saveWalletCache(address, networkName, bundle.facade, this.cacheDir, chainId); } catch { /* best-effort */ } + try { await saveWalletCache(address, networkName, bundle.facade, opts.root, chainId); } catch { /* best-effort */ } } - if (!opts.readOnly) this.invalidate({ network, seed }); + if (!opts.readOnly) this.invalidate({ network, root: opts.root, seed }); return result; } finally { await cleanup(); @@ -577,7 +576,7 @@ export class WalletDataRepository { if (kinds.includes('facade') && scope.seed) { const address = deriveUnshieldedAddress(scope.seed, networkName); - try { clearWalletCache(address, networkName, this.cacheDir); } catch { /* best-effort */ } + try { clearWalletCache(address, networkName, scope.root); } catch { /* best-effort */ } } } @@ -678,7 +677,7 @@ function defaultDustFetcher( signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - cacheDir?: string; + root: string; log?: VerboseLog; }, ): Promise { @@ -737,7 +736,7 @@ export function defaultRepository(): WalletDataRepository { return defaultRepo; } -/** Test/diagnostic: replace the process singleton (e.g. with a different `cacheDir`). */ +/** Test/diagnostic: replace the process singleton (e.g. with different fetchers). */ export function setDefaultRepository(repo: WalletDataRepository | null): void { defaultRepo = repo; } diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index 103f7cba..369e2d4c 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -35,7 +35,7 @@ import { createDAppConnector } from './dapp-connector.ts'; const HOUR_MS = 60 * 60 * 1000; async function shieldedTransfer(params: ShieldedTransferParams): Promise { - const { seed, network, networkConfig, amount, progress, signal } = params; + const { seed, root, network, networkConfig, amount, progress, signal } = params; const networkId = getNetworkId(networkConfig.networkId); const nightToken = ledger.unshieldedToken().raw; const receiverAddress = decodeShieldedAddress(params.recipient, network); @@ -76,7 +76,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise const finalized = await bundle.facade.finalizeRecipe(signed); // Spending an open swap offer's coins would cancel it: refused. - const open = readOpenOffers(network, deriveUnshieldedAddress(seed, network)); + const open = readOpenOffers(root, network, deriveUnshieldedAddress(seed, network)); if (open.length > 0) { try { assertSpendsNoOfferCoin(open, spentNullifiers(Buffer.from(finalized.serialize()).toString('hex'))); @@ -98,6 +98,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise return String(txId); }, { + root, syncMode: 'full', log: params.log, requireStrictSync: true, @@ -111,8 +112,8 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise /** The wallet a test's preparation checks, built from its saved state and synced quickly (no shielded sync). */ async function syncedPrepWallet(wallet: PrepWallet, reportSync: boolean, beforeSync?: () => void) { - bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS); - const bundle = await buildFacade(wallet.seed, wallet.networkConfig, loadWalletCache(wallet.address, wallet.network)); + bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS, wallet.root); + const bundle = await buildFacade(wallet.seed, wallet.networkConfig, wallet.root, loadWalletCache(wallet.address, wallet.network, wallet.root)); try { beforeSync?.(); const state = await startAndSyncFacade(bundle, { @@ -142,7 +143,7 @@ async function prepNightBalance(wallet: PrepWallet): Promise { try { const balance = state.unshielded.balances[ledger.unshieldedToken().raw] ?? 0n; if (balance > 0n) { - try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade, wallet.root); } catch { /* best-effort */ } } return balance; } finally { @@ -158,7 +159,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv const result = await ensureDust(bundle, (status) => wallet.onMessage(`Dust: ${status}`)); if (result.alreadyAvailable) { wallet.onMessage('Dust already available'); - try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade, wallet.root); } catch { /* best-effort */ } return { alreadyAvailable: true, dustAvailable: true }; } @@ -168,7 +169,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv const dustAvailable = hasDustAvailable(await waitForDustAvailable(bundle, waitMs, wallet.signal)); if (dustAvailable) { wallet.onMessage('Dust is available'); - try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade, wallet.root); } catch { /* best-effort */ } } return { alreadyAvailable: false, dustAvailable }; } finally { @@ -177,7 +178,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv } const openConnector: EngineWallet['openConnector'] = async (options): Promise => { - const { seed, network, networkConfig, address, syncMode, signal, onMessage } = options; + const { seed, root, network, networkConfig, address, syncMode, signal, onMessage } = options; // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig, undefined, signal); // A failure before the connector is handed back stops what was started, so @@ -187,7 +188,7 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise isFacadeSynced(state, syncMode, built.emptyStreams), dustWaitMs: options.dustWaitMs, - openOffers: () => readOpenOffers(network, address), + openOffers: () => readOpenOffers(root, network, address), callbacks: { onPhaseStart: (_connId, _method, phase) => { onMessage(`${phase}...`); @@ -259,7 +260,7 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise { - const { seed, networkConfig, network, address, syncMode } = options; + const { seed, root, networkConfig, network, address, syncMode } = options; // The repository owns validating the caches, priming Dust, building the // facade, syncing (with retries) and stopping it. Its save is skipped: mn // serve saves only when no transaction is pending, since the SDK drops @@ -272,7 +273,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { return hasDustAvailable(lastState); }, async saveState() { - try { await saveWalletCache(address, network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(address, network, bundle.facade, root); } catch { /* best-effort */ } }, connect: ({ approvalOptions, feeLimits, callbacks }) => createDAppConnector({ bundle, @@ -284,11 +285,12 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { // one that is synced by the rule the sync used. initialState: lastState, isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), - openOffers: () => readOpenOffers(network, address), + openOffers: () => readOpenOffers(root, network, address), }), }; return serve(session); }, { + root, syncMode, // serve accepts write requests from dApps — must be strictly synced. requireStrictSync: true, diff --git a/packages/engine-rc/api-report.md b/packages/engine-rc/api-report.md index f9ef292a..f37d4d91 100644 --- a/packages/engine-rc/api-report.md +++ b/packages/engine-rc/api-report.md @@ -188,9 +188,9 @@ export interface DustCacheEntry { } export declare function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string; export declare function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadDustCache(network: string, pubkeyHex: string, cacheDir?: string): DustCacheEntry | null; -export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string, retention?: DustRetention): void; -export declare function validateDustCacheChainId(network: string, currentChainId: string | null, cacheDir?: string): string[]; +export declare function loadDustCache(network: string, pubkeyHex: string, root: string): DustCacheEntry | null; +export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, root: string, chainId?: string, retention?: DustRetention): void; +export declare function validateDustCacheChainId(network: string, currentChainId: string | null, root: string): string[]; ``` ## `@kuiralabs/midnight-engine-rc/dust-export` @@ -202,13 +202,14 @@ import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustExportOptions { + root: string; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; repository?: WalletDataRepository; - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; log?: VerboseLog; } -export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options?: DustExportOptions): Promise; +export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options: DustExportOptions): Promise; ``` ## `@kuiralabs/midnight-engine-rc/dust-register` @@ -242,7 +243,7 @@ interface NativeFetchOptions { initialRetention?: DustRetention; signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; - cacheDir?: string; + root: string; } export declare function resolveSidecarBinary(): string | null; export declare function platformPackageBinary(fromUrl: string): string | null; @@ -297,7 +298,7 @@ export interface FacadeBundle { indexerWsUrl?: string; emptyStreams?: EmptyStreams; } -export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, cache?: WalletCacheData | null, log?: VerboseLog): Promise; +export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, cache?: WalletCacheData | null, log?: VerboseLog): Promise; export interface FacadeDustSnapshot { publicKey: { publicKey: string; @@ -444,11 +445,11 @@ export interface ShieldedCacheEntry { lastAppliedEventId: number; } export declare function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadShieldedCache(network: string, pubkeyHex: string, cacheDir?: string, expectedChainId?: string): ShieldedCacheEntry | null; -export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, cacheDir?: string, chainId?: string): void; +export declare function loadShieldedCache(network: string, pubkeyHex: string, root: string, expectedChainId?: string): ShieldedCacheEntry | null; +export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, root: string, chainId?: string): void; export type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; import type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options?: ShieldedCachedOptions): Promise; +export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options: ShieldedCachedOptions): Promise; ``` ## `@kuiralabs/midnight-engine-rc/sign-recipe` @@ -514,8 +515,8 @@ import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subsc import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; -import type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustView extends DustBalance { state: ledger.DustLocalState; } @@ -525,11 +526,12 @@ export interface FacadeLease { } export interface InvalidationScope { network: NetworkConfig; + root: string; seed?: Buffer; address?: string; kinds?: ReadonlyArray<"dust" | "unshielded" | "facade">; } -export interface FacadeOptions extends ReadOptions { +export interface FacadeOptions extends CachedReadOptions { syncMode?: SyncMode; requireStrictSync?: boolean; readOnly?: boolean; @@ -552,13 +554,12 @@ export interface RepoDeps { signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - cacheDir?: string; + root: string; log?: VerboseLog; }) => Promise; fetchChainId?: (nodeWsUrl: string) => Promise; fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; - cacheDir?: string; } export declare class WalletDataRepository { private readonly now; @@ -568,17 +569,16 @@ export declare class WalletDataRepository { private readonly fetchChainId; private readonly fetchEventTip; private readonly fetchProtocolVersion; - private readonly cacheDir; private readonly dustMemo; private readonly unshieldedMemo; private readonly tipMemo; constructor(deps?: RepoDeps); private keepCachesOfThisIndexer; - walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise; + walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise; private freshWalletOnDustCheckpoint; - dust(seed: Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; + dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise; unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; - withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts?: FacadeOptions): Promise; + withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts: FacadeOptions): Promise; invalidate(scope: InvalidationScope): void; resetTipMemo(): void; private tryMemo; diff --git a/packages/engine-rc/src/dust-direct-cache.ts b/packages/engine-rc/src/dust-direct-cache.ts index 09f30bbc..7bda17bb 100644 --- a/packages/engine-rc/src/dust-direct-cache.ts +++ b/packages/engine-rc/src/dust-direct-cache.ts @@ -73,9 +73,9 @@ export function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string { export function loadDustCache( network: string, pubkeyHex: string, - cacheDir?: string, + root: string, ): DustCacheEntry | null { - const path = getDustCachePath(network, pubkeyHex, cacheDir); + const path = getDustCachePath(network, pubkeyHex, root); if (!existsSync(path)) return null; try { @@ -111,7 +111,7 @@ export function saveDustCache( pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, - cacheDir?: string, + root: string, chainId?: string, retention: DustRetention = EMPTY_RETENTION, ): void { @@ -127,7 +127,7 @@ export function saveDustCache( ...(chainId ? { chainId } : {}), }; - const path = getDustCachePath(network, pubkeyHex, cacheDir); + const path = getDustCachePath(network, pubkeyHex, root); const dir = dirname(path); if (!existsSync(dir)) { @@ -153,13 +153,13 @@ export function saveDustCache( export function validateDustCacheChainId( network: string, currentChainId: string | null, - cacheDir?: string, + root: string, ): string[] { // Caller fetches the chain's current genesis hash once and passes it in. // A null hash (node unreachable) skips validation — proceed best-effort. if (!currentChainId) return []; - const dir = dustCacheDir(network, cacheDir); + const dir = dustCacheDir(network, root); if (!existsSync(dir)) return []; const wiped: string[] = []; diff --git a/packages/engine-rc/src/dust-export.ts b/packages/engine-rc/src/dust-export.ts index dca16597..b4611179 100644 --- a/packages/engine-rc/src/dust-export.ts +++ b/packages/engine-rc/src/dust-export.ts @@ -27,6 +27,8 @@ export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export interface DustExportOptions { + /** The state root the Dust cache lives under. */ + root: string; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; /** Injectable for tests; defaults to the process-wide repository. */ @@ -37,14 +39,14 @@ export interface DustExportOptions { * The default touches the node relay (building a facade opens its API-WS), so * tests stub this to stay offline. */ - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; /** The call's verbose lines. */ log?: VerboseLog; } /** Build a fresh facade from keys and read its base (empty) dust snapshot. */ -async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, log?: VerboseLog): Promise { - const bundle = await buildFacade(seedBuffer, networkConfig, null, log); +async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog): Promise { + const bundle = await buildFacade(seedBuffer, networkConfig, root, null, log); try { return await (bundle.facade as unknown as { dust: { serializeState(): Promise }; @@ -69,18 +71,19 @@ export async function exportDustSnapshot( seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, - options: DustExportOptions = {}, + options: DustExportOptions, ): Promise { const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); const repo = options.repository ?? defaultRepository(); const view = await repo.dust(seedBuffer, networkConfig, { + root: options.root, signal: options.signal, onProgress: options.onProgress, log: options.log, }); - const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.log); + const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.root, options.log); // Overlay whenever at least one event has been folded in. For a wallet with no // dust events yet (lastAppliedEventId -1) the fresh base snapshot is already the diff --git a/packages/engine-rc/src/dust-register.ts b/packages/engine-rc/src/dust-register.ts index 5b149356..4d30bfaf 100644 --- a/packages/engine-rc/src/dust-register.ts +++ b/packages/engine-rc/src/dust-register.ts @@ -14,7 +14,7 @@ export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight- export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { - const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log } = options; + const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root } = options; const stopListening = sdkWarnings.listen(onSyncWarning); try { const { result, dustBalance } = await defaultRepository().withFacade( @@ -35,6 +35,7 @@ export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, o return { result, dustBalance: finalState.dust.balance(new Date()) }; }, { + root, syncMode: 'lite', requireStrictSync: true, signal, diff --git a/packages/engine-rc/src/dust-sync-native.ts b/packages/engine-rc/src/dust-sync-native.ts index d648988d..8779b2f9 100644 --- a/packages/engine-rc/src/dust-sync-native.ts +++ b/packages/engine-rc/src/dust-sync-native.ts @@ -41,8 +41,8 @@ interface NativeFetchOptions { initialRetention?: DustRetention; signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; - /** The wallet's cache folder (the state root's when absent): the checkpoint lives beside the other Dust caches. */ - cacheDir?: string; + /** The state root: the checkpoint lives beside the other Dust caches under it. */ + root: string; } /** @@ -125,8 +125,8 @@ function readCheckpointCursor(path: string): number { /** The sidecar's checkpoint file for a Dust key, beside the other Dust caches. */ -function nativeCheckpointPath(networkName: string, pubkeyHex: string, cacheDir?: string): string { - const dir = join(cacheRootDir(cacheDir), networkCacheFolder(networkName)); +function nativeCheckpointPath(networkName: string, pubkeyHex: string, root: string): string { + const dir = join(cacheRootDir(root), networkCacheFolder(networkName, root)); if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: DIR_MODE }); return join(dir, nativeCheckpointName(pubkeyHex)); } @@ -150,7 +150,7 @@ export function runDustSyncNative( const networkName = network.networkId.toLowerCase(); const pubkeyHex = dustPublicKeyHexFromSeed(seed); - const out = nativeCheckpointPath(networkName, pubkeyHex, opts.cacheDir); + const out = nativeCheckpointPath(networkName, pubkeyHex, opts.root); // Resume selection (out == resume file; the sidecar reads it once at start, // then overwrites it with its own checkpoints — kill-safe at this path): diff --git a/packages/engine-rc/src/facade.ts b/packages/engine-rc/src/facade.ts index a04852fe..14454a2f 100644 --- a/packages/engine-rc/src/facade.ts +++ b/packages/engine-rc/src/facade.ts @@ -71,13 +71,15 @@ export interface FacadeBundle { * * When `cache` is provided, wallets are restored from serialized state * instead of starting fresh — the SDK then only syncs new transactions - * since the last checkpoint. + * since the last checkpoint, with the Dust checkpoint kept under the state + * root `root` bridged in when it is ahead. * * Its diagnostics go to `log`, the call's verbose lines. */ export async function buildFacade( seedBuffer: Buffer, networkConfig: NetworkConfig, + root: string, cache?: WalletCacheData | null, log?: VerboseLog, ): Promise { @@ -136,7 +138,7 @@ export async function buildFacade( // register) benefit from the indexer-direct reader's checkpoint without // re-implementing the whole transaction flow. const dustPublicKey = ledger.DustSecretKey.fromSeed(seeds.dust).publicKey; - const effectiveCache = cache ? maybeBridgeDustCache(cache, networkConfig, dustPublicKey, log) : null; + const effectiveCache = cache ? maybeBridgeDustCache(cache, networkConfig, dustPublicKey, root, log) : null; // Attempt cache restore — fall back to fresh build on any deserialization error. let restoredFromCache = false; @@ -257,12 +259,13 @@ function maybeBridgeDustCache( cache: WalletCacheData, networkConfig: NetworkConfig, dustPublicKey: ledger.DustPublicKey, + root: string, log?: VerboseLog, ): WalletCacheData { try { const networkName = networkConfig.networkId.toLowerCase(); const pubkeyHex = dustPublicKeyHex(dustPublicKey); - const direct = loadDustCache(networkName, pubkeyHex); + const direct = loadDustCache(networkName, pubkeyHex, root); if (!direct) return cache; // Only overlay when dust-direct is AHEAD of the facade cache's own offset — a prior diff --git a/packages/engine-rc/src/shielded-direct-cache.ts b/packages/engine-rc/src/shielded-direct-cache.ts index f27e9199..40f4c6f4 100644 --- a/packages/engine-rc/src/shielded-direct-cache.ts +++ b/packages/engine-rc/src/shielded-direct-cache.ts @@ -62,10 +62,10 @@ export function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string { export function loadShieldedCache( network: string, pubkeyHex: string, - cacheDir?: string, + root: string, expectedChainId?: string, ): ShieldedCacheEntry | null { - const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + const path = getShieldedCachePath(network, pubkeyHex, root); if (!existsSync(path)) return null; try { @@ -92,7 +92,7 @@ export function saveShieldedCache( pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, - cacheDir?: string, + root: string, chainId?: string, ): void { const data: ShieldedCacheFile = { @@ -105,7 +105,7 @@ export function saveShieldedCache( ...(chainId ? { chainId } : {}), }; - const path = getShieldedCachePath(network, pubkeyHex, cacheDir); + const path = getShieldedCachePath(network, pubkeyHex, root); const dir = dirname(path); if (!existsSync(dir)) { @@ -137,17 +137,17 @@ export async function readShieldedBalanceCached( seedBuffer: Buffer, network: string, indexerWS: string, - options: ShieldedCachedOptions = {}, + options: ShieldedCachedOptions, ): Promise { const secretKeys = ledger.ZswapSecretKeys.fromSeed(deriveShieldedSeed(seedBuffer)); const pubkeyHex = secretKeys.coinPublicKey; // State resumed from another indexer's event ids would replay the wrong events. - bindCachesToIndexer(network, indexerWS); - let cached = options.forceFresh ? null : loadShieldedCache(network, pubkeyHex, undefined, options.chainId); + bindCachesToIndexer(network, indexerWS, options.root); + let cached = options.forceFresh ? null : loadShieldedCache(network, pubkeyHex, options.root, options.chainId); // A cursor past the chain's latest event: the chain was reset under the cache. if (cached && isCursorBeyondTip(cached.lastAppliedEventId, await fetchEventTip(indexerWS, 'zswap'))) { - clearShieldedDirectCache(network, pubkeyHex); + clearShieldedDirectCache(network, pubkeyHex, options.root); cached = null; } const startFromId = cached ? cached.lastAppliedEventId + 1 : 0; @@ -161,16 +161,16 @@ export async function readShieldedBalanceCached( // Persist after each chunk so a Ctrl+C / kill during a cold ~70s sync // doesn't lose progress — the next call resumes from the last checkpoint. onCheckpoint: (state, lastAppliedEventId) => { - try { saveShieldedCache(network, pubkeyHex, state, lastAppliedEventId, undefined, options.chainId); } catch { /* best-effort */ } + try { saveShieldedCache(network, pubkeyHex, state, lastAppliedEventId, options.root, options.chainId); } catch { /* best-effort */ } }, }); // Only write if we advanced or this is a first sync. If we had a cache and zero // new events arrived, leave the on-disk file untouched. if (result.lastAppliedEventId >= 0) { - saveShieldedCache(network, pubkeyHex, result.state, result.lastAppliedEventId, undefined, options.chainId); + saveShieldedCache(network, pubkeyHex, result.state, result.lastAppliedEventId, options.root, options.chainId); } else if (!cached) { - saveShieldedCache(network, pubkeyHex, result.state, -1, undefined, options.chainId); + saveShieldedCache(network, pubkeyHex, result.state, -1, options.root, options.chainId); } return { diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index 61d00eae..3ee7d20f 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -435,6 +435,7 @@ export async function executeTransfer(params: TransferParams): Promise void; /** Repo passes a callback to persist incremental progress during long syncs. */ onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - /** The cache folder the repository keeps; the native sidecar keeps its checkpoint there. */ - cacheDir?: string; + /** The state root of the caches; the native sidecar keeps its checkpoint beside them. */ + root: string; /** The call's verbose lines. */ log?: VerboseLog; }, @@ -143,8 +145,6 @@ export interface RepoDeps { fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; /** Chain protocol-version fetcher (ledger-9-only guard). Default: indexer `block { protocolVersion }`. */ fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; - /** Override cache directory (tests use a tmp dir). */ - cacheDir?: string; } // ── Implementation ──────────────────────────────────────── @@ -190,7 +190,6 @@ export class WalletDataRepository { private readonly fetchChainId: NonNullable; private readonly fetchEventTip: NonNullable; private readonly fetchProtocolVersion: NonNullable; - private readonly cacheDir: string | undefined; private readonly dustMemo = new Map>(); private readonly unshieldedMemo = new Map>(); @@ -204,7 +203,6 @@ export class WalletDataRepository { this.fetchChainId = deps.fetchChainId ?? getChainGenesisHash; this.fetchEventTip = deps.fetchEventTip ?? fetchEventTip; this.fetchProtocolVersion = deps.fetchProtocolVersion ?? fetchProtocolVersion; - this.cacheDir = deps.cacheDir; } /** @@ -212,8 +210,8 @@ export class WalletDataRepository { * state read from another indexer is dropped before it is loaded, and the * caller is told why this sync is a full one. */ - private keepCachesOfThisIndexer(networkName: string, network: NetworkConfig, onStatus?: (s: string) => void): void { - const change = bindCachesToIndexer(networkName, network.indexerWS, this.cacheDir); + private keepCachesOfThisIndexer(networkName: string, network: NetworkConfig, root: string, onStatus?: (s: string) => void): void { + const change = bindCachesToIndexer(networkName, network.indexerWS, root); if (change) onStatus?.(describeIndexerChange(networkName, change)); } @@ -228,18 +226,19 @@ export class WalletDataRepository { /** * The saved state a wallet restores from: its own, else a new wallet's on * the Dust checkpoint (see freshWalletOnDustCheckpoint). Null builds it from - * its keys. Every facade mn starts for writing starts from this. Building - * that new wallet's diagnostics go to `log`. + * its keys. Every facade mn starts for writing starts from this; both are + * read under the state root `root`. Building that new wallet's diagnostics + * go to `log`. */ - async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise { - return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, this.cacheDir) - ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, log); + async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, root) + ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, root, log); } - private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, log?: VerboseLog): Promise { - const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), this.cacheDir); + private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), root); if (!checkpoint || checkpoint.lastAppliedEventId < 0) return null; - const fresh = await buildFacade(seed, network, null, log); + const fresh = await buildFacade(seed, network, root, null, log); try { const { shielded, unshielded, dust } = fresh.facade as unknown as Record<'shielded' | 'unshielded' | 'dust', { serializeState(): Promise }>; const [shieldedState, unshieldedState, dustState] = await Promise.all([shielded.serializeState(), unshielded.serializeState(), dust.serializeState()]); @@ -251,7 +250,7 @@ export class WalletDataRepository { // ── Reads ───────────────────────────────────────── - async dust(seed: Buffer, network: NetworkConfig, opts: ReadOptions = {}): Promise { + async dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise { const networkName = networkNameOf(network); await assertLedgerSupported(networkName, network, this.fetchProtocolVersion, opts.signal); const pubkeyHex = dustPublicKeyHexFromSeed(seed); @@ -267,15 +266,15 @@ export class WalletDataRepository { // stale-chain dust files, and persist the same hash on every save so the // guard has something to compare on the next run. const currentChainId = await this.fetchChainId(network.node).catch(() => null); - validateDustCacheChainId(networkName, currentChainId, this.cacheDir); - this.keepCachesOfThisIndexer(networkName, network, opts.onStatus); + validateDustCacheChainId(networkName, currentChainId, opts.root); + this.keepCachesOfThisIndexer(networkName, network, opts.root, opts.onStatus); const chainId = currentChainId ?? undefined; - let cached = opts.forceFresh ? null : loadDustCache(networkName, pubkeyHex, this.cacheDir); + let cached = opts.forceFresh ? null : loadDustCache(networkName, pubkeyHex, opts.root); // A cursor past the chain's latest event: the chain was reset under the // cache (the genesis check above can't tell when the hash is reused). if (cached && isCursorBeyondTip(cached.lastAppliedEventId, await this.fetchEventTip(network.indexerWS, 'dust'))) { - clearDustDirectCache(networkName, pubkeyHex, this.cacheDir); + clearDustDirectCache(networkName, pubkeyHex, opts.root); cached = null; } const startedFromCache = cached !== null; @@ -301,7 +300,7 @@ export class WalletDataRepository { ); result = await this.fetchDust(seed, network, { - cacheDir: this.cacheDir, + root: opts.root, startFromId, initialState: cached?.state, initialRetention: cached?.retention, @@ -319,7 +318,7 @@ export class WalletDataRepository { // Persist after each chunk so a Ctrl+C / process kill / SIGTERM // doesn't lose 100k events of work. onCheckpoint: (state, lastAppliedEventId, retention) => { - try { saveDustCache(networkName, pubkeyHex, state, lastAppliedEventId, this.cacheDir, chainId, retention); } catch { /* best-effort */ } + try { saveDustCache(networkName, pubkeyHex, state, lastAppliedEventId, opts.root, chainId, retention); } catch { /* best-effort */ } }, }); @@ -330,7 +329,7 @@ export class WalletDataRepository { ? result.lastAppliedEventId : (cached?.lastAppliedEventId ?? -1); if (result.lastAppliedEventId >= 0 || !cached) { - try { saveDustCache(networkName, pubkeyHex, result.state, lastAppliedEventId, this.cacheDir, chainId, result.retention); } catch { /* best-effort */ } + try { saveDustCache(networkName, pubkeyHex, result.state, lastAppliedEventId, opts.root, chainId, result.retention); } catch { /* best-effort */ } } totalEventsApplied += result.eventCount; @@ -339,7 +338,7 @@ export class WalletDataRepository { if (stalledWindows >= DUST_STALLED_WINDOWS || this.now() - startedAt >= DUST_SYNC_BUDGET_MS) break; // Reload for the next iteration so cached.state is the latest checkpoint. - cached = loadDustCache(networkName, pubkeyHex, this.cacheDir); + cached = loadDustCache(networkName, pubkeyHex, opts.root); } if (!result) throw new Error('Dust sync exhausted retries without producing a result'); @@ -413,7 +412,7 @@ export class WalletDataRepository { seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, - opts: FacadeOptions = {}, + opts: FacadeOptions, ): Promise { const syncMode = opts.syncMode ?? 'full'; const requireStrictSync = opts.requireStrictSync ?? true; @@ -428,8 +427,8 @@ export class WalletDataRepository { await assertLedgerSupported(networkName, network, this.fetchProtocolVersion, opts.signal); const currentChainId = await this.fetchChainId(network.node).catch(() => null); - validateWalletCacheChainId(networkName, currentChainId, this.cacheDir); - this.keepCachesOfThisIndexer(networkName, network, opts.onStatus); + validateWalletCacheChainId(networkName, currentChainId, opts.root); + this.keepCachesOfThisIndexer(networkName, network, opts.root, opts.onStatus); const chainId = currentChainId ?? undefined; // ── Pre-prime the dust-direct cache for write-mode borrowers ── @@ -438,7 +437,7 @@ export class WalletDataRepository { // near-tip. Read-only borrowers skip it. if (writeMode && !opts.noPrime && !opts.forceFresh) { try { - await this.dust(seed, network, { signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch (err) { // Pre-prime is best-effort — the actual sync below will re-attempt // anyway. Surface the error only via onSyncWarning if anyone cares. @@ -461,8 +460,8 @@ export class WalletDataRepository { throwIfCancelled(opts.signal); const cacheBeforeBuild = opts.forceFresh ? null - : await this.walletStateToRestore(seed, network, networkName, opts.log); - bundle = await buildFacade(seed, network, cacheBeforeBuild, opts.log); + : await this.walletStateToRestore(seed, network, networkName, opts.root, opts.log); + bundle = await buildFacade(seed, network, opts.root, cacheBeforeBuild, opts.log); try { syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, @@ -480,12 +479,12 @@ export class WalletDataRepository { opts.onStatus?.(`Cache is stale, clearing and rebuilding (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); await stopFacade(bundle).catch(() => {}); bundle = undefined; - clearWalletCache(address, networkName, this.cacheDir); - clearDustDirectCache(networkName, dustPublicKeyHexFromSeed(seed), this.cacheDir); + clearWalletCache(address, networkName, opts.root); + clearDustDirectCache(networkName, dustPublicKeyHexFromSeed(seed), opts.root); // Re-prime the dust cache so the next attempt restores from a // current checkpoint instead of a full SDK resync. try { - await this.dust(seed, network, { signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch { /* best-effort */ } continue; } @@ -493,7 +492,7 @@ export class WalletDataRepository { if (attempt < SYNC_MAX_ATTEMPTS && String(err?.message ?? '').includes('timed out')) { // Save partial sync progress to cache before retrying so the next // attempt resumes from the latest event id. - try { await saveWalletCache(address, networkName, bundle.facade, this.cacheDir, chainId); } catch { /* best-effort */ } + try { await saveWalletCache(address, networkName, bundle.facade, opts.root, chainId); } catch { /* best-effort */ } opts.onStatus?.(`Sync timed out, retrying (attempt ${attempt + 1}/${SYNC_MAX_ATTEMPTS})...`); await stopFacade(bundle).catch(() => {}); bundle = undefined; @@ -529,8 +528,8 @@ export class WalletDataRepository { bundle = undefined; await new Promise((r) => setTimeout(r, COLD_START_DELAY_MS)); throwIfCancelled(opts.signal); - const retryCache = loadWalletCache(address, networkName, this.cacheDir); - bundle = await buildFacade(seed, network, retryCache, opts.log); + const retryCache = loadWalletCache(address, networkName, opts.root); + bundle = await buildFacade(seed, network, opts.root, retryCache, opts.log); syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, onSyncDetail: opts.onSyncDetail, @@ -543,9 +542,9 @@ export class WalletDataRepository { } if (!opts.skipAutoSave) { - try { await saveWalletCache(address, networkName, bundle.facade, this.cacheDir, chainId); } catch { /* best-effort */ } + try { await saveWalletCache(address, networkName, bundle.facade, opts.root, chainId); } catch { /* best-effort */ } } - if (!opts.readOnly) this.invalidate({ network, seed }); + if (!opts.readOnly) this.invalidate({ network, root: opts.root, seed }); return result; } finally { await cleanup(); @@ -576,7 +575,7 @@ export class WalletDataRepository { if (kinds.includes('facade') && scope.seed) { const address = deriveUnshieldedAddress(scope.seed, networkName); - try { clearWalletCache(address, networkName, this.cacheDir); } catch { /* best-effort */ } + try { clearWalletCache(address, networkName, scope.root); } catch { /* best-effort */ } } } @@ -677,7 +676,7 @@ function defaultDustFetcher( signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - cacheDir?: string; + root: string; log?: VerboseLog; }, ): Promise { @@ -727,7 +726,7 @@ export function defaultRepository(): WalletDataRepository { return defaultRepo; } -/** Test/diagnostic: replace the process singleton (e.g. with a different `cacheDir`). */ +/** Test/diagnostic: replace the process singleton (e.g. with different fetchers). */ export function setDefaultRepository(repo: WalletDataRepository | null): void { defaultRepo = repo; } diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index d5505551..a47732cd 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -35,7 +35,7 @@ import { createDAppConnector } from './dapp-connector.ts'; const HOUR_MS = 60 * 60 * 1000; async function shieldedTransfer(params: ShieldedTransferParams): Promise { - const { seed, network, networkConfig, amount, progress, signal } = params; + const { seed, root, network, networkConfig, amount, progress, signal } = params; const networkId = getNetworkId(networkConfig.networkId); const nightToken = ledger.unshieldedToken().raw; const receiverAddress = decodeShieldedAddress(params.recipient, network); @@ -75,7 +75,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise const finalized = await bundle.facade.finalizeRecipe(signed); // Spending an open swap offer's coins would cancel it: refused. - const open = readOpenOffers(network, deriveUnshieldedAddress(seed, network)); + const open = readOpenOffers(root, network, deriveUnshieldedAddress(seed, network)); if (open.length > 0) { try { assertSpendsNoOfferCoin(open, spentNullifiers(Buffer.from(finalized.serialize()).toString('hex'))); @@ -97,6 +97,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise return String(txId); }, { + root, syncMode: 'full', log: params.log, requireStrictSync: true, @@ -110,8 +111,8 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise /** The wallet a test's preparation checks, built from its saved state and synced quickly (no shielded sync). */ async function syncedPrepWallet(wallet: PrepWallet, reportSync: boolean, beforeSync?: () => void) { - bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS); - const bundle = await buildFacade(wallet.seed, wallet.networkConfig, loadWalletCache(wallet.address, wallet.network)); + bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS, wallet.root); + const bundle = await buildFacade(wallet.seed, wallet.networkConfig, wallet.root, loadWalletCache(wallet.address, wallet.network, wallet.root)); try { beforeSync?.(); const state = await startAndSyncFacade(bundle, { @@ -141,7 +142,7 @@ async function prepNightBalance(wallet: PrepWallet): Promise { try { const balance = state.unshielded.balances[ledger.unshieldedToken().raw] ?? 0n; if (balance > 0n) { - try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade, wallet.root); } catch { /* best-effort */ } } return balance; } finally { @@ -157,7 +158,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv const result = await ensureDust(bundle, (status) => wallet.onMessage(`Dust: ${status}`)); if (result.alreadyAvailable) { wallet.onMessage('Dust already available'); - try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade, wallet.root); } catch { /* best-effort */ } return { alreadyAvailable: true, dustAvailable: true }; } @@ -167,7 +168,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv const dustAvailable = hasDustAvailable(await waitForDustAvailable(bundle, waitMs, wallet.signal)); if (dustAvailable) { wallet.onMessage('Dust is available'); - try { await saveWalletCache(wallet.address, wallet.network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(wallet.address, wallet.network, bundle.facade, wallet.root); } catch { /* best-effort */ } } return { alreadyAvailable: false, dustAvailable }; } finally { @@ -176,7 +177,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv } const openConnector: EngineWallet['openConnector'] = async (options): Promise => { - const { seed, network, networkConfig, address, syncMode, signal, onMessage } = options; + const { seed, root, network, networkConfig, address, syncMode, signal, onMessage } = options; // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig, undefined, signal); // A failure before the connector is handed back stops what was started, so @@ -186,7 +187,7 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise isFacadeSynced(state, syncMode, built.emptyStreams), dustWaitMs: options.dustWaitMs, - openOffers: () => readOpenOffers(network, address), + openOffers: () => readOpenOffers(root, network, address), callbacks: { onPhaseStart: (_connId, _method, phase) => { onMessage(`${phase}...`); @@ -258,7 +259,7 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise { - const { seed, networkConfig, network, address, syncMode } = options; + const { seed, root, networkConfig, network, address, syncMode } = options; // The repository owns validating the caches, priming Dust, building the // facade, syncing (with retries) and stopping it. Its save is skipped: mn // serve saves only when no transaction is pending, since the SDK drops @@ -271,7 +272,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { return hasDustAvailable(lastState); }, async saveState() { - try { await saveWalletCache(address, network, bundle.facade); } catch { /* best-effort */ } + try { await saveWalletCache(address, network, bundle.facade, root); } catch { /* best-effort */ } }, connect: ({ approvalOptions, feeLimits, callbacks }) => createDAppConnector({ bundle, @@ -283,11 +284,12 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { // one that is synced by the rule the sync used. initialState: lastState, isCurrent: (state) => isFacadeSynced(state, syncMode, bundle.emptyStreams), - openOffers: () => readOpenOffers(network, address), + openOffers: () => readOpenOffers(root, network, address), }), }; return serve(session); }, { + root, syncMode, // serve accepts write requests from dApps — must be strictly synced. requireStrictSync: true, diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 7c7fe4cd..a0174002 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -99,7 +99,6 @@ export const ALLOWED_STATE = { 'lib/wallet-config.ts': { warnedPlain: 'shared on purpose: each plain-text wallet is warned about once per run' }, // The host sources, set once by the host at start (handlers see them through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, - 'lib/state-root.ts': { source: 'shared on purpose: the host sets the paths source once' }, 'lib/notices.ts': { sink: 'shared on purpose: the host sets the notice sink once' }, 'lib/prompter.ts': { current: 'shared on purpose: the host sets the prompter once' }, }; diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index 8a58f7bc..90c69667 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -5,6 +5,7 @@ import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './help import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { testHost } from './helpers/test-host.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -56,7 +57,7 @@ afterEach(() => { beforeAll(async () => { const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); - const { indexer } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']) }).config; + const { indexer } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }).config; const answered = await fetch(indexer, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: '{ block { height } }' }), signal: AbortSignal.timeout(5_000) }) .then((r) => r.ok, () => false); if (!answered) throw new Error(`No ledger-9 indexer answers at ${indexer}: start the local chain (or point undeployed at one with midnight config set) before npm run test:live.`); diff --git a/src/__tests__/cache-indexer.test.ts b/src/__tests__/cache-indexer.test.ts index 1bf021d8..12eab208 100644 --- a/src/__tests__/cache-indexer.test.ts +++ b/src/__tests__/cache-indexer.test.ts @@ -13,6 +13,8 @@ const BLOCKFROST = 'wss://midnight-preprod.blockfrost.io/api/v0/ws?project_id=ni const OLD_PREPROD = 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws'; const PREVIEW = 'wss://indexer.preview.midnight.network/api/v4/graphql/ws'; +// The state root the function is given, and the cache folder under it. +let root: string; let dir: string; const files = (network: string) => (fs.existsSync(path.join(dir, network)) ? fs.readdirSync(path.join(dir, network)).sort() : []); const cache = (network: string, ...names: string[]) => { @@ -20,8 +22,11 @@ const cache = (network: string, ...names: string[]) => { for (const name of names) fs.writeFileSync(path.join(dir, network, name), '{}'); }; -beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-cache-indexer-')); }); -afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); +beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-cache-indexer-')); + dir = path.join(root, 'cache'); +}); +afterEach(() => { fs.rmSync(root, { recursive: true, force: true }); }); describe('indexerIdentity', () => { it('is the host and port, never the query that carries a project id', () => { @@ -37,7 +42,7 @@ describe('bindCachesToIndexer', () => { cache('preprod', 'mn_addr_preprod1abc.json', 'dust-0123.json', 'dust-native-0123.json', 'shielded-4567.json'); cache('preview', 'mn_addr_preview1abc.json'); - const change = bindCachesToIndexer('preprod', BLOCKFROST, dir); + const change = bindCachesToIndexer('preprod', BLOCKFROST, root); expect(change).toEqual({ previous: 'indexer.preprod.midnight.network', current: 'midnight-preprod.blockfrost.io', removed: 4 }); expect(files('preprod')).toEqual(['indexer.host']); expect(files('preview')).toEqual(['mn_addr_preview1abc.json']); @@ -45,51 +50,51 @@ describe('bindCachesToIndexer', () => { it('keeps state saved before the indexer was recorded when the network is still on that indexer', () => { cache('preview', 'mn_addr_preview1abc.json', 'dust-0123.json'); - expect(bindCachesToIndexer('preview', PREVIEW, dir)).toBeUndefined(); + expect(bindCachesToIndexer('preview', PREVIEW, root)).toBeUndefined(); expect(files('preview')).toEqual(['dust-0123.json', 'indexer.host', 'mn_addr_preview1abc.json']); }); it('keeps a local network\'s unrecorded state: its indexer was never a fixed one', () => { cache('undeployed', 'mn_addr_undeployed1abc.json'); - expect(bindCachesToIndexer('undeployed', 'ws://localhost:8088/api/v4/graphql/ws', dir)).toBeUndefined(); + expect(bindCachesToIndexer('undeployed', 'ws://localhost:8088/api/v4/graphql/ws', root)).toBeUndefined(); expect(files('undeployed')).toEqual(['indexer.host', 'mn_addr_undeployed1abc.json']); }); it('does nothing more once the directory belongs to the indexer', () => { - bindCachesToIndexer('preprod', BLOCKFROST, dir); + bindCachesToIndexer('preprod', BLOCKFROST, root); cache('preprod', 'dust-0123.json'); - expect(bindCachesToIndexer('preprod', BLOCKFROST, dir)).toBeUndefined(); + expect(bindCachesToIndexer('preprod', BLOCKFROST, root)).toBeUndefined(); expect(files('preprod')).toEqual(['dust-0123.json', 'indexer.host']); }); it('removes the state again when the indexer changes, in either direction', () => { - bindCachesToIndexer('preprod', BLOCKFROST, dir); + bindCachesToIndexer('preprod', BLOCKFROST, root); cache('preprod', 'dust-0123.json'); - expect(bindCachesToIndexer('preprod', 'wss://my-indexer.example/api/v4/graphql/ws', dir)) + expect(bindCachesToIndexer('preprod', 'wss://my-indexer.example/api/v4/graphql/ws', root)) .toEqual({ previous: 'midnight-preprod.blockfrost.io', current: 'my-indexer.example', removed: 1 }); cache('preprod', 'dust-0123.json'); - expect(bindCachesToIndexer('preprod', BLOCKFROST, dir)?.removed).toBe(1); + expect(bindCachesToIndexer('preprod', BLOCKFROST, root)?.removed).toBe(1); }); it('tells two local stacks apart by their port', () => { - bindCachesToIndexer('undeployed', 'ws://localhost:8088/api/v4/graphql/ws', dir); + bindCachesToIndexer('undeployed', 'ws://localhost:8088/api/v4/graphql/ws', root); cache('undeployed', 'dust-0123.json'); - expect(bindCachesToIndexer('undeployed', 'ws://localhost:38088/api/v4/graphql/ws', dir)?.removed).toBe(1); + expect(bindCachesToIndexer('undeployed', 'ws://localhost:38088/api/v4/graphql/ws', root)?.removed).toBe(1); }); it('records the host only: the project id is never written', () => { - bindCachesToIndexer('preprod', BLOCKFROST, dir); + bindCachesToIndexer('preprod', BLOCKFROST, root); expect(fs.readFileSync(path.join(dir, 'preprod', 'indexer.host'), 'utf-8')).toBe('midnight-preprod.blockfrost.io\n'); }); it('records the indexer for a network with no cache yet, and reports nothing', () => { - expect(bindCachesToIndexer('preprod', BLOCKFROST, dir)).toBeUndefined(); + expect(bindCachesToIndexer('preprod', BLOCKFROST, root)).toBeUndefined(); expect(files('preprod')).toEqual(['indexer.host']); }); it('leaves the old preprod state alone while preprod is still pointed at the old indexer', () => { cache('preprod', 'dust-0123.json'); - expect(bindCachesToIndexer('preprod', OLD_PREPROD, dir)).toBeUndefined(); + expect(bindCachesToIndexer('preprod', OLD_PREPROD, root)).toBeUndefined(); expect(files('preprod')).toEqual(['dust-0123.json', 'indexer.host']); }); }); diff --git a/src/__tests__/chain-reset-clearing.test.ts b/src/__tests__/chain-reset-clearing.test.ts index d335e4aa..8256f8ea 100644 --- a/src/__tests__/chain-reset-clearing.test.ts +++ b/src/__tests__/chain-reset-clearing.test.ts @@ -25,15 +25,16 @@ const touch = (file: string): string => { describe('clearChainCaches', () => { it("clears the wallet, Dust, shielded and native-sidecar caches of one network and leaves another network's", () => { + // `dir` is the state root; its cache folder is where the files land. const cache = path.join(dir, 'cache'); - const wallet = touch(getCachePath('mn_addr_undeployed1abcdefghijklmnop', 'undeployed', cache)); - const dust = touch(getDustCachePath('undeployed', 'ab'.repeat(32), cache)); - const shielded = touch(getShieldedCachePath('undeployed', 'cd'.repeat(32), cache)); + const wallet = touch(getCachePath('mn_addr_undeployed1abcdefghijklmnop', 'undeployed', dir)); + const dust = touch(getDustCachePath('undeployed', 'ab'.repeat(32), dir)); + const shielded = touch(getShieldedCachePath('undeployed', 'cd'.repeat(32), dir)); const native = touch(path.join(cache, 'undeployed', `dust-native-${'ab'.repeat(10)}.json`)); - const otherWallet = touch(getCachePath('mn_addr_preview1abcdefghijklmnop', 'preview', cache)); - const otherDust = touch(getDustCachePath('preview', 'ab'.repeat(32), cache)); + const otherWallet = touch(getCachePath('mn_addr_preview1abcdefghijklmnop', 'preview', dir)); + const otherDust = touch(getDustCachePath('preview', 'ab'.repeat(32), dir)); - clearChainCaches('undeployed', cache); + clearChainCaches('undeployed', dir); expect([wallet, dust, shielded, native].map((f) => fs.existsSync(f))).toEqual([false, false, false, false]); expect([fs.existsSync(otherWallet), fs.existsSync(otherDust)]).toEqual([true, true]); diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index b076b2c8..bb3c9036 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -15,8 +15,6 @@ import { import { sdkSetOfNetwork } from '@kuiralabs/midnight-cli-core/lib/network'; import { getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; const TEST_DIR = path.join(os.tmpdir(), `midnight-cli-config-test-${process.pid}`); @@ -588,24 +586,22 @@ describe('the sdk-set key', () => { describe('the SDK set a network runs on', () => { const root = path.join(TEST_DIR, 'state'); - beforeEach(() => setHostPathsSource(() => ({ stateRoot: root, home: TEST_DIR }))); - afterEach(() => setHostPathsSource(() => ({ stateRoot: path.join(os.homedir(), MIDNIGHT_DIR), home: os.homedir() }))); it('is the table\'s until config gives the network another, and the caches follow it to a folder of the set\'s own', () => { - expect(sdkSetOfNetwork('undeployed')).toBe('rc'); - expect(networkCacheFolder('undeployed')).toBe('undeployed'); - expect(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')).toBe(path.join(root, 'cache', 'undeployed', 'mn_addr_undeployed1a.json')); + expect(sdkSetOfNetwork('undeployed', root)).toBe('rc'); + expect(networkCacheFolder('undeployed', root)).toBe('undeployed'); + expect(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed', root)).toBe(path.join(root, 'cache', 'undeployed', 'mn_addr_undeployed1a.json')); - setConfigValue('sdk-set', 'beta', undefined, 'undeployed'); - expect(sdkSetOfNetwork('undeployed')).toBe('beta'); - expect(networkCacheFolder('undeployed')).toBe('undeployed.beta'); - expect(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')).toBe(path.join(root, 'cache', 'undeployed.beta', 'mn_addr_undeployed1a.json')); - expect(getDustCachePath('undeployed', 'ab'.repeat(32))).toBe(path.join(root, 'cache', 'undeployed.beta', `dust-${'ab'.repeat(10)}.json`)); + setConfigValue('sdk-set', 'beta', root, 'undeployed'); + expect(sdkSetOfNetwork('undeployed', root)).toBe('beta'); + expect(networkCacheFolder('undeployed', root)).toBe('undeployed.beta'); + expect(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed', root)).toBe(path.join(root, 'cache', 'undeployed.beta', 'mn_addr_undeployed1a.json')); + expect(getDustCachePath('undeployed', 'ab'.repeat(32), root)).toBe(path.join(root, 'cache', 'undeployed.beta', `dust-${'ab'.repeat(10)}.json`)); // Back on the network's own set, the caches it kept there are the ones read. - unsetConfigValue('sdk-set', undefined, 'undeployed'); - expect(networkCacheFolder('undeployed')).toBe('undeployed'); - expect(sdkSetOfNetwork('stagenet')).toBe('beta'); - expect(networkCacheFolder('stagenet')).toBe('stagenet'); + unsetConfigValue('sdk-set', root, 'undeployed'); + expect(networkCacheFolder('undeployed', root)).toBe('undeployed'); + expect(sdkSetOfNetwork('stagenet', root)).toBe('beta'); + expect(networkCacheFolder('stagenet', root)).toBe('stagenet'); }); }); diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index ea13861d..01300443 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -316,8 +316,8 @@ describe('commands that write check the call before each whole write', () => { it('cache clear --wallet: cancelled while the wallet is unlocked, it clears no cache', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - const created = await createWallet('alice', walletSecretFrom(), PASSPHRASE); - const cache = getCachePath(created.addresses.undeployed, 'undeployed'); + const created = await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE); + const cache = getCachePath(created.addresses.undeployed, 'undeployed', stateRootIn(home)); fs.mkdirSync(path.dirname(cache), { recursive: true }); fs.writeFileSync(cache, '{}'); const call = new AbortController(); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 8c497530..ce14180d 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -31,7 +31,6 @@ import { FULL_FLAG, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-c import { CancelledError, isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError, EXIT_CANCELLED } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import type { CallContext, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { hostPaths } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; import { createSdkWarningRouter, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; @@ -141,7 +140,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => it('gives the handler the configuration the host gives when the call starts, and --verbose', async () => { const { ctx } = (await run('plain')).call; - expect(ctx.config.paths).toStrictEqual(hostPaths()); + expect(ctx.config.paths).toStrictEqual(provisions.host.paths()); expect(ctx.config.settings).toStrictEqual(settings()); expect(ctx.diagnostics.isVerbose).toBe(false); received.length = 0; diff --git a/src/__tests__/config-command.test.ts b/src/__tests__/config-command.test.ts index 10182cc1..a88843da 100644 --- a/src/__tests__/config-command.test.ts +++ b/src/__tests__/config-command.test.ts @@ -1,18 +1,28 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; let io: CapturedOutput; +// A home of the test's own: the config the commands write is never the user's. +let home: string; +const originalHome = process.env.HOME; + // Save the original config value before tests, restore after let originalNetwork: string; beforeEach(() => { process.env.NO_COLOR = ''; - originalNetwork = loadCliConfig().network; + home = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-config-command-')); + process.env.HOME = home; + originalNetwork = loadCliConfig(stateRootIn(home)).network; io = captureOutput(); }); @@ -20,11 +30,13 @@ afterEach(async () => { delete process.env.NO_COLOR; io.restore(); // Restore original config to avoid side effects - if (loadCliConfig().network !== originalNetwork) { + if (loadCliConfig(stateRootIn(home)).network !== originalNetwork) { const restoreIo = captureOutput(); await cliCall(configCommand, parseArgs(['config', 'set', 'network', originalNetwork])); restoreIo.restore(); } + process.env.HOME = originalHome; + fs.rmSync(home, { recursive: true, force: true }); }); describe('config command — error handling', () => { diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 0ac2f420..77e632a1 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -14,6 +14,7 @@ import { servePayerAt } from '../lib/serve-payer.ts'; import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { stateRootIn } from './helpers/state-root-in.ts'; const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -44,7 +45,7 @@ describe('deployContract', () => { const said: string[] = []; await expect(deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy'), + target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home)), wallet: 'nobody', // Never reached: serving would be the step after the funds check. payer: servePayerAt(1), @@ -65,7 +66,7 @@ describe('deployContract', () => { const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); await expect(deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy'), + target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home)), wallet: 'external', payer: ownPayer, progress: () => silentSpinner(), @@ -90,7 +91,7 @@ describe('deployContract', () => { const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); await expect(deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy'), + target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home)), wallet: 'external', payer: ownPayer, progress: () => silentSpinner(), diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index 13c66b7f..ea771edd 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -263,14 +263,16 @@ describe('generated scripts', () => { describe('a cancelled run', () => { it('starts no script for a deploy, a call or a state read whose run was cancelled, and says it was cancelled', async () => { const dappDir = mkdtempSync(join(tmpdir(), 'mn-cancelled-run-')); + const root = mkdtempSync(join(tmpdir(), 'mn-cancelled-run-root-')); try { - const common = { dappDir, network: 'undeployed' as const, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; + const common = { dappDir, network: 'undeployed' as const, root, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; await expect(runDeploy({ ...common, servePort: 9932 })).rejects.toBeInstanceOf(CancelledError); await expect(runCall({ ...common, servePort: 9932, contractAddress: 'ab'.repeat(32), circuit: 'increment' })).rejects.toBeInstanceOf(CancelledError); await expect(runState({ ...common, contractAddress: 'ab'.repeat(32) })).rejects.toBeInstanceOf(CancelledError); expect(readdirSync(dappDir)).toEqual([]); } finally { rmSync(dappDir, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); } }); }); diff --git a/src/__tests__/contract-runtime-check.test.ts b/src/__tests__/contract-runtime-check.test.ts index b0d9d325..1205f485 100644 --- a/src/__tests__/contract-runtime-check.test.ts +++ b/src/__tests__/contract-runtime-check.test.ts @@ -1,7 +1,7 @@ // A contract compiled for another compact runtime than the network's engine // runs is refused up front, naming the compiler that engine needs. -import { describe, expect, it } from 'vitest'; +import { afterAll, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -12,6 +12,9 @@ import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { runDeploy } from '../lib/contract/runner.ts'; const contract = (runtimeVersion: string, compilerVersion = '0.30.0') => ({ name: 'counter', compilerVersion, runtimeVersion }); +// A state root with no config: undeployed on the set the table names. +const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-runtime-check-root-')); +afterAll(() => fs.rmSync(ROOT, { recursive: true, force: true })); describe('the rc engine\'s compact runtime', () => { it('is the one it says, and takes contracts compiled for it, by the runtime\'s own rule', () => { @@ -27,7 +30,7 @@ describe('the rc engine\'s compact runtime', () => { describe('a contract for another compact runtime', () => { it('is refused as a usage mistake, naming both runtimes and the compiler to use', async () => { - const refused = await assertContractRunsOn(contract('0.16.0'), 'undeployed').then(() => undefined, (err: unknown) => err); + const refused = await assertContractRunsOn(contract('0.16.0'), 'undeployed', ROOT).then(() => undefined, (err: unknown) => err); expect(refused).toBeInstanceOf(UsageError); expect((refused as Error).message).toBe( 'counter was compiled by compactc 0.30.0 for compact-runtime 0.16.0, but undeployed runs contracts on compact-runtime 0.20.0.\nRecompile it with compactc 0.35.', @@ -36,8 +39,8 @@ describe('a contract for another compact runtime', () => { }); it('lets through one compiled for the engine\'s runtime, and one whose compiler recorded none', async () => { - await expect(assertContractRunsOn(contract('0.20.0', '0.35.0'), 'undeployed')).resolves.toBeUndefined(); - await expect(assertContractRunsOn(contract('unknown', 'unknown'), 'undeployed')).resolves.toBeUndefined(); + await expect(assertContractRunsOn(contract('0.20.0', '0.35.0'), 'undeployed', ROOT)).resolves.toBeUndefined(); + await expect(assertContractRunsOn(contract('unknown', 'unknown'), 'undeployed', ROOT)).resolves.toBeUndefined(); }); it('is refused by the runner too, before any script runs', async () => { @@ -47,7 +50,7 @@ describe('a contract for another compact runtime', () => { fs.mkdirSync(path.join(managedDir, 'compiler'), { recursive: true }); fs.writeFileSync(path.join(managedDir, 'compiler', 'contract-info.json'), JSON.stringify({ 'compiler-version': '0.30.0', 'language-version': '0.22.0', 'runtime-version': '0.16.0', circuits: [], witnesses: [] })); const networkConfig = { indexer: 'http://127.0.0.1:1', indexerWS: 'ws://127.0.0.1:1', node: 'ws://127.0.0.1:1', proofServer: 'http://127.0.0.1:1', networkId: 'Undeployed' }; - await expect(runDeploy({ dappDir, network: 'undeployed', networkConfig, managedDir, contractName: 'counter', servePort: 1 })) + await expect(runDeploy({ dappDir, network: 'undeployed', root: ROOT, networkConfig, managedDir, contractName: 'counter', servePort: 1 })) .rejects.toThrow('Recompile it with compactc 0.35.'); // No script was written into the dApp. expect(fs.readdirSync(dappDir).filter((f) => f.endsWith('.mjs'))).toEqual([]); diff --git a/src/__tests__/dust-direct-cache.test.ts b/src/__tests__/dust-direct-cache.test.ts index 861a899d..a4547701 100644 --- a/src/__tests__/dust-direct-cache.test.ts +++ b/src/__tests__/dust-direct-cache.test.ts @@ -10,7 +10,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { loadDustCache, saveDustCache, dustPublicKeyHex } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; import { clearDustDirectCache, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -const CACHE_DIR = path.join(os.tmpdir(), `midnight-dust-cache-test-${process.pid}-${Date.now()}`); +const STATE_ROOT = path.join(os.tmpdir(), `midnight-dust-cache-test-${process.pid}-${Date.now()}`); const NETWORK = 'undeployed'; const SEED_HEX = '0000000000000000000000000000000000000000000000000000000000000042'; @@ -30,11 +30,11 @@ function testDustPubkeyHex(): string { } beforeEach(() => { - fs.mkdirSync(CACHE_DIR, { recursive: true }); + fs.mkdirSync(STATE_ROOT, { recursive: true }); }); afterEach(() => { - fs.rmSync(CACHE_DIR, { recursive: true, force: true }); + fs.rmSync(STATE_ROOT, { recursive: true, force: true }); }); describe('dustPublicKeyHex', () => { @@ -56,8 +56,8 @@ describe('dust-direct cache: round-trip', () => { const pubkey = testDustPubkeyHex(); const state = freshDustState(); - saveDustCache(NETWORK, pubkey, state, 42, CACHE_DIR); - const loaded = loadDustCache(NETWORK, pubkey, CACHE_DIR); + saveDustCache(NETWORK, pubkey, state, 42, STATE_ROOT); + const loaded = loadDustCache(NETWORK, pubkey, STATE_ROOT); expect(loaded).not.toBeNull(); expect(loaded!.lastAppliedEventId).toBe(42); @@ -71,25 +71,25 @@ describe('dust-direct cache: round-trip', () => { const state = freshDustState(); const retention = { ownedGenerationIndices: [0, 3, 99], generationFrontier: 120 }; - saveDustCache(NETWORK, pubkey, state, 42, CACHE_DIR, undefined, retention); - const loaded = loadDustCache(NETWORK, pubkey, CACHE_DIR); + saveDustCache(NETWORK, pubkey, state, 42, STATE_ROOT, undefined, retention); + const loaded = loadDustCache(NETWORK, pubkey, STATE_ROOT); expect(loaded!.retention).toEqual(retention); }); it('defaults to empty retention when none is provided', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); - const loaded = loadDustCache(NETWORK, pubkey, CACHE_DIR); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); + const loaded = loadDustCache(NETWORK, pubkey, STATE_ROOT); expect(loaded!.retention).toEqual({ ownedGenerationIndices: [], generationFrontier: 0 }); }); it('writes file with 0o600 permissions', () => { const pubkey = testDustPubkeyHex(); const state = freshDustState(); - saveDustCache(NETWORK, pubkey, state, 0, CACHE_DIR); + saveDustCache(NETWORK, pubkey, state, 0, STATE_ROOT); - const filePath = getDustCachePath(NETWORK, pubkey, CACHE_DIR); + const filePath = getDustCachePath(NETWORK, pubkey, STATE_ROOT); const stat = fs.statSync(filePath); // On macOS/Linux the mode low 9 bits reflect user/group/other rwx. expect(stat.mode & 0o777).toBe(0o600); @@ -98,113 +98,113 @@ describe('dust-direct cache: round-trip', () => { describe('dust-direct cache: invalidation', () => { it('returns null when the file is missing', () => { - expect(loadDustCache(NETWORK, testDustPubkeyHex(), CACHE_DIR)).toBeNull(); + expect(loadDustCache(NETWORK, testDustPubkeyHex(), STATE_ROOT)).toBeNull(); }); it('returns null on version mismatch', () => { const pubkey = testDustPubkeyHex(); const state = freshDustState(); - saveDustCache(NETWORK, pubkey, state, 1, CACHE_DIR); + saveDustCache(NETWORK, pubkey, state, 1, STATE_ROOT); // Corrupt: bump version on disk - const filePath = getDustCachePath(NETWORK, pubkey, CACHE_DIR); + const filePath = getDustCachePath(NETWORK, pubkey, STATE_ROOT); const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')); data.version = 999; fs.writeFileSync(filePath, JSON.stringify(data)); - expect(loadDustCache(NETWORK, pubkey, CACHE_DIR)).toBeNull(); + expect(loadDustCache(NETWORK, pubkey, STATE_ROOT)).toBeNull(); }); it('invalidates a legacy v1 cache (no retention fields) so it re-syncs', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 5, CACHE_DIR); + saveDustCache(NETWORK, pubkey, freshDustState(), 5, STATE_ROOT); // Rewrite as a pre-collapse v1 file: version 1, retention fields absent. - const filePath = getDustCachePath(NETWORK, pubkey, CACHE_DIR); + const filePath = getDustCachePath(NETWORK, pubkey, STATE_ROOT); const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')); data.version = 1; delete data.ownedGenerationIndices; delete data.generationFrontier; fs.writeFileSync(filePath, JSON.stringify(data)); - expect(loadDustCache(NETWORK, pubkey, CACHE_DIR)).toBeNull(); + expect(loadDustCache(NETWORK, pubkey, STATE_ROOT)).toBeNull(); }); it('invalidates a cache written by ledger-8 mn (v2) so a ledger-9 chain re-syncs', () => { // Dev-preset localnets share a genesis hash, so only the version keeps a // ledger-8 cache from being replayed onto a ledger-9 chain. const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 5, CACHE_DIR); - const filePath = getDustCachePath(NETWORK, pubkey, CACHE_DIR); + saveDustCache(NETWORK, pubkey, freshDustState(), 5, STATE_ROOT); + const filePath = getDustCachePath(NETWORK, pubkey, STATE_ROOT); const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')); data.version = 2; fs.writeFileSync(filePath, JSON.stringify(data)); - expect(loadDustCache(NETWORK, pubkey, CACHE_DIR)).toBeNull(); + expect(loadDustCache(NETWORK, pubkey, STATE_ROOT)).toBeNull(); }); it('returns null on network mismatch', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); - expect(loadDustCache('preprod', pubkey, CACHE_DIR)).toBeNull(); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); + expect(loadDustCache('preprod', pubkey, STATE_ROOT)).toBeNull(); }); it('returns null on pubkey mismatch', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); - expect(loadDustCache(NETWORK, 'f'.repeat(64), CACHE_DIR)).toBeNull(); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); + expect(loadDustCache(NETWORK, 'f'.repeat(64), STATE_ROOT)).toBeNull(); }); it('returns null on corrupted JSON', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); - fs.writeFileSync(getDustCachePath(NETWORK, pubkey, CACHE_DIR), '{not-json'); - expect(loadDustCache(NETWORK, pubkey, CACHE_DIR)).toBeNull(); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); + fs.writeFileSync(getDustCachePath(NETWORK, pubkey, STATE_ROOT), '{not-json'); + expect(loadDustCache(NETWORK, pubkey, STATE_ROOT)).toBeNull(); }); it('returns null when dustState is not a hex string', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); - const filePath = getDustCachePath(NETWORK, pubkey, CACHE_DIR); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); + const filePath = getDustCachePath(NETWORK, pubkey, STATE_ROOT); const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')); data.dustState = 'not-hex-zzz'; fs.writeFileSync(filePath, JSON.stringify(data)); - expect(loadDustCache(NETWORK, pubkey, CACHE_DIR)).toBeNull(); + expect(loadDustCache(NETWORK, pubkey, STATE_ROOT)).toBeNull(); }); }); describe('dust-direct cache: clearDustDirectCache', () => { it('removes a single (network, pubkey) file', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); - expect(fs.existsSync(getDustCachePath(NETWORK, pubkey, CACHE_DIR))).toBe(true); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); + expect(fs.existsSync(getDustCachePath(NETWORK, pubkey, STATE_ROOT))).toBe(true); - clearDustDirectCache(NETWORK, pubkey, CACHE_DIR); - expect(fs.existsSync(getDustCachePath(NETWORK, pubkey, CACHE_DIR))).toBe(false); + clearDustDirectCache(NETWORK, pubkey, STATE_ROOT); + expect(fs.existsSync(getDustCachePath(NETWORK, pubkey, STATE_ROOT))).toBe(false); }); it('removes all dust-* files in a network dir, preserving non-dust files', () => { const pubkey = testDustPubkeyHex(); - saveDustCache(NETWORK, pubkey, freshDustState(), 1, CACHE_DIR); + saveDustCache(NETWORK, pubkey, freshDustState(), 1, STATE_ROOT); // Simulate an existing facade cache file that should NOT be touched. - const networkDir = path.join(CACHE_DIR, NETWORK); + const networkDir = path.join(STATE_ROOT, 'cache', NETWORK); const walletCachePath = path.join(networkDir, 'some-wallet-cache.json'); fs.writeFileSync(walletCachePath, '{}'); - clearDustDirectCache(NETWORK, undefined, CACHE_DIR); + clearDustDirectCache(NETWORK, undefined, STATE_ROOT); - expect(fs.existsSync(getDustCachePath(NETWORK, pubkey, CACHE_DIR))).toBe(false); + expect(fs.existsSync(getDustCachePath(NETWORK, pubkey, STATE_ROOT))).toBe(false); expect(fs.existsSync(walletCachePath)).toBe(true); }); it('removes all dust-* files across all networks when called with no args', () => { const pubkey = testDustPubkeyHex(); - saveDustCache('undeployed', pubkey, freshDustState(), 1, CACHE_DIR); - saveDustCache('preprod', pubkey, freshDustState(), 2, CACHE_DIR); + saveDustCache('undeployed', pubkey, freshDustState(), 1, STATE_ROOT); + saveDustCache('preprod', pubkey, freshDustState(), 2, STATE_ROOT); - clearDustDirectCache(undefined, undefined, CACHE_DIR); + clearDustDirectCache(undefined, undefined, STATE_ROOT); - expect(fs.existsSync(getDustCachePath('undeployed', pubkey, CACHE_DIR))).toBe(false); - expect(fs.existsSync(getDustCachePath('preprod', pubkey, CACHE_DIR))).toBe(false); + expect(fs.existsSync(getDustCachePath('undeployed', pubkey, STATE_ROOT))).toBe(false); + expect(fs.existsSync(getDustCachePath('preprod', pubkey, STATE_ROOT))).toBe(false); }); }); diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index fbd3ef07..e388cdce 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -129,7 +129,6 @@ function fakeRepo(result: DustDirectResult): WalletDataRepository { fetchChainId: async () => null, // skip the node RPC (offline) fetchUnshielded: async () => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }), fetchDust: async () => result, - cacheDir: EXPORT_TMP, }); } @@ -141,6 +140,7 @@ describe('exportDustSnapshot', () => { // the incomplete result rather than a false "warm" snapshot. const repo = fakeRepo(fakeDust(ownedState, { lastAppliedEventId: 42, balance: 500n, partial: true })); const res = await exportDustSnapshot(EXPORT_SEED, 'undeployed', EXPORT_NETWORK, { + root: EXPORT_TMP, repository: repo, buildBaseDust: async () => baseSnapshot('0'), }); @@ -158,6 +158,7 @@ describe('exportDustSnapshot', () => { it('reports partial: false for a completed sync', async () => { const repo = fakeRepo(fakeDust(ownedState, { lastAppliedEventId: 100, eventCount: 100, partial: false })); const res = await exportDustSnapshot(EXPORT_SEED, 'undeployed', EXPORT_NETWORK, { + root: EXPORT_TMP, repository: repo, buildBaseDust: async () => baseSnapshot('0'), }); @@ -171,6 +172,7 @@ describe('exportDustSnapshot', () => { const repo = fakeRepo(fakeDust(fresh, { lastAppliedEventId: -1, eventCount: 0, partial: false })); const base = baseSnapshot('0'); const res = await exportDustSnapshot(EXPORT_SEED, 'undeployed', EXPORT_NETWORK, { + root: EXPORT_TMP, repository: repo, buildBaseDust: async () => base, }); diff --git a/src/__tests__/dust-sync-native.test.ts b/src/__tests__/dust-sync-native.test.ts index 459b2e09..c2d68df4 100644 --- a/src/__tests__/dust-sync-native.test.ts +++ b/src/__tests__/dust-sync-native.test.ts @@ -164,7 +164,7 @@ describe('runDustSyncNative exit handling (fake sidecar binary)', () => { it('accepts the checkpoint from a clean exit (control: the fake binary works)', async () => { fakeSidecar(0); - const r = await runDustSyncNative(seed, network, { startFromId: 0 }); + const r = await runDustSyncNative(seed, network, { root: join(dir, '.midnight'), startFromId: 0 }); expect(r.lastAppliedEventId).toBe(7); }); @@ -172,7 +172,7 @@ describe('runDustSyncNative exit handling (fake sidecar binary)', () => { // A ledger-8 sidecar on a ledger-9 chain dies like this (exit 2) after a // checkpoint already sits at --out; parsing it as success froze dust. fakeSidecar(2); - await expect(runDustSyncNative(seed, network, { startFromId: 0 })).rejects.toThrow('dust-sync exited 2'); + await expect(runDustSyncNative(seed, network, { root: join(dir, '.midnight'), startFromId: 0 })).rejects.toThrow('dust-sync exited 2'); }); }); diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index 7ca91bc5..ecc27b08 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -1,31 +1,38 @@ // The engine for a network: one per process, loaded on first use, and the // same for work every set does alike. -import { describe, expect, it } from 'vitest'; +import { afterAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { OtherSdkSetError, anyEngine, engineFor, preferEngineOf, sdkSetOf, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { getValidNetworkNames, sdkSetOfNetwork, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +// A state root with no config: every network on the set the table names. +const ROOT = mkdtempSync(join(tmpdir(), 'mn-engine-test-')); +afterAll(() => rmSync(ROOT, { recursive: true, force: true })); + describe('the engine for a network', () => { it('is the rc engine for every network but stagenet, which runs the beta set', async () => { for (const network of getValidNetworkNames() as NetworkName[]) { if (network === 'stagenet') continue; - expect(sdkSetOf(network)).toBe('rc'); - expect(await engineFor(network)).toBe(rcEngine); + expect(sdkSetOf(network, ROOT)).toBe('rc'); + expect(await engineFor(network, ROOT)).toBe(rcEngine); } - expect(sdkSetOf('stagenet')).toBe('beta'); + expect(sdkSetOf('stagenet', ROOT)).toBe('beta'); }); it('refuses stagenet in a process that has loaded the rc engine, naming both sets', async () => { - await engineFor('undeployed'); - const refusal = await engineFor('stagenet').catch((err: unknown) => err); + await engineFor('undeployed', ROOT); + const refusal = await engineFor('stagenet', ROOT).catch((err: unknown) => err); expect(refusal).toBeInstanceOf(OtherSdkSetError); expect(refusal).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'rc', wantedSet: 'beta' }); }); it('is the one loaded in this process for work every set does alike', async () => { - expect(await anyEngine()).toBe(await engineFor('undeployed')); + expect(await anyEngine()).toBe(await engineFor('undeployed', ROOT)); }); it('derives a wallet\'s addresses on every network, matching one network at a time', async () => { @@ -47,10 +54,10 @@ describe('the network picks the engine', () => { const asked: string[] = []; setEngineLoader(async (set) => { asked.push(set); return rcEngine; }); try { - expect(await engineFor('preview')).toBe(rcEngine); - expect(await engineFor('undeployed')).toBe(rcEngine); + expect(await engineFor('preview', ROOT)).toBe(rcEngine); + expect(await engineFor('undeployed', ROOT)).toBe(rcEngine); expect(asked).toStrictEqual(['rc']); - for (const network of getValidNetworkNames() as NetworkName[]) expect(sdkSetOf(network)).toBe(sdkSetOfNetwork(network)); + for (const network of getValidNetworkNames() as NetworkName[]) expect(sdkSetOf(network, ROOT)).toBe(sdkSetOfNetwork(network, ROOT)); } finally { setEngineLoader(loadInstalledEngine); } @@ -61,11 +68,11 @@ describe('the network picks the engine', () => { const beta = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; setEngineLoader(async (set) => { asked.push(set); return set === 'beta' ? beta : rcEngine; }); try { - preferEngineOf('stagenet'); + preferEngineOf('stagenet', ROOT); expect(await anyEngine()).toBe(beta); expect(asked).toStrictEqual(['beta']); } finally { - preferEngineOf('undeployed'); + preferEngineOf('undeployed', ROOT); setEngineLoader(loadInstalledEngine); } }); @@ -74,7 +81,7 @@ describe('the network picks the engine', () => { const other = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; setEngineLoader(async () => other); try { - await expect(engineFor('undeployed')).rejects.toThrow("This process runs the beta SDK set and can't load the rc one"); + await expect(engineFor('undeployed', ROOT)).rejects.toThrow("This process runs the beta SDK set and can't load the rc one"); } finally { setEngineLoader(loadInstalledEngine); } diff --git a/src/__tests__/fixtures/record-swap-offer.ts b/src/__tests__/fixtures/record-swap-offer.ts index d5109cd7..ec674e19 100644 --- a/src/__tests__/fixtures/record-swap-offer.ts +++ b/src/__tests__/fixtures/record-swap-offer.ts @@ -14,7 +14,6 @@ import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { engineFor, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { loadInstalledEngine } from '../../lib/installed-engines.ts'; @@ -34,14 +33,14 @@ const networkConfig: NetworkConfig = { }; const home = mkdtempSync(join(tmpdir(), 'mn-record-offer-')); +const root = join(home, '.midnight'); setSettingsSource(() => settingsFromEnvironment(process.env)); -setHostPathsSource(() => ({ stateRoot: join(home, '.midnight'), home })); setEngineLoader(loadInstalledEngine); -const engine = await engineFor('undeployed'); +const engine = await engineFor('undeployed', root); const ctx = { notify: () => {}, connectionId: 'record', requestId: 1, metadata: {} }; const open = (seed: Buffer) => engine.wallet.openConnector({ - seed, network: 'undeployed', networkConfig, address: engine.keys.unshieldedAddress(seed, 'undeployed'), syncMode: 'full', + seed, root, network: 'undeployed', networkConfig, address: engine.keys.unshieldedAddress(seed, 'undeployed'), syncMode: 'full', onMessage: (m) => { if (!/\d+\/\d+/.test(m)) process.stderr.write(` ${m}\n`); }, }); diff --git a/src/__tests__/generate-command.test.ts b/src/__tests__/generate-command.test.ts index e7a84462..cc7c91cc 100644 --- a/src/__tests__/generate-command.test.ts +++ b/src/__tests__/generate-command.test.ts @@ -9,6 +9,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-generate-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; @@ -40,7 +41,7 @@ describe('generate command — random mode', () => { it('writes no seed or mnemonic in the clear: both are sealed under the passphrase', async () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); await cliCall(generateCommand, parseArgs(['generate', '--network', 'undeployed', '--output', walletFile])); - const { seed, mnemonic } = await unlockWallet(walletFile); + const { seed, mnemonic } = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); const text = fs.readFileSync(walletFile, 'utf8'); expect(text).not.toContain(seed); expect(text).not.toContain(mnemonic!.split(' ')[0]! + ' ' + mnemonic!.split(' ')[1]!); @@ -52,7 +53,7 @@ describe('generate command — random mode', () => { await cliCall(generateCommand, args); expect(fs.existsSync(walletFile)).toBe(true); - const config = await unlockWallet(walletFile); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); expect(config.addresses.undeployed).toBeDefined(); expect(config.mnemonic).toBeDefined(); expect(config.mnemonic!.split(' ').length).toBe(24); @@ -90,7 +91,7 @@ describe('generate command — seed mode', () => { const args = parseArgs(['generate', '--network', 'preprod', '--seed', TEST_SEED, '--output', walletFile]); await cliCall(generateCommand, args); - const config = await unlockWallet(walletFile); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); expect(config.seed).toBe(TEST_SEED); expect(config.addresses.preprod).toBeDefined(); expect(config.mnemonic).toBeUndefined(); @@ -105,8 +106,8 @@ describe('generate command — seed mode', () => { io.clearStdout(); await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--seed', TEST_SEED, '--output', file2])); - const config1 = (await unlockWallet(file1)); - const config2 = (await unlockWallet(file2)); + const config1 = (await unlockWallet(file1, { root: stateRootIn(TEST_DIR) })); + const config2 = (await unlockWallet(file2, { root: stateRootIn(TEST_DIR) })); expect(config1.addresses.preprod).toBe(config2.addresses.preprod); expect(config1.seed).toBe(config2.seed); }); @@ -132,9 +133,9 @@ describe('generate command — seed mode', () => { // any implementation deriving Midnight addresses from this mnemonic // must land here, so --seed and --mnemonic must both produce it. const golden = 'mn_addr_preview1dwv2rta0a2skyhrvukaw2q9r2sq6yc4jhj63rf7afxpkrrv6g35q4y8xms'; - expect((await unlockWallet(fromSeed)).addresses.preview).toBe(golden); - expect((await unlockWallet(fromMnemonic)).addresses.preview).toBe(golden); - expect((await unlockWallet(fromSeed)).seed).toBe(seedHex); + expect((await unlockWallet(fromSeed, { root: stateRootIn(TEST_DIR) })).addresses.preview).toBe(golden); + expect((await unlockWallet(fromMnemonic, { root: stateRootIn(TEST_DIR) })).addresses.preview).toBe(golden); + expect((await unlockWallet(fromSeed, { root: stateRootIn(TEST_DIR) })).seed).toBe(seedHex); }); it('does not include mnemonic in seed mode', async () => { @@ -149,7 +150,7 @@ describe('generate command — seed mode', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--seed', '0x' + TEST_SEED, '--output', walletFile])); - const config = await unlockWallet(walletFile); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); expect(config.seed).toBe(TEST_SEED); }); @@ -158,7 +159,7 @@ describe('generate command — seed mode', () => { process.env.MN_SEED = TEST_SEED; await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--output', walletFile])); - const config = await unlockWallet(walletFile); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); expect(config.seed).toBe(TEST_SEED); expect(config.mnemonic).toBeUndefined(); }); @@ -168,7 +169,7 @@ describe('generate command — seed mode', () => { process.env.MN_SEED = '0000000000000000000000000000000000000000000000000000000000000009'; await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--seed', TEST_SEED, '--output', walletFile])); - const config = await unlockWallet(walletFile); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); expect(config.seed).toBe(TEST_SEED); }); }); @@ -182,7 +183,7 @@ describe('generate command — mnemonic mode', () => { const args = parseArgs(['generate', '--network', 'preview', '--mnemonic', VALID_MNEMONIC, '--output', walletFile]); await cliCall(generateCommand, args); - const config = await unlockWallet(walletFile); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); expect(config.addresses.preview).toBeDefined(); expect(config.mnemonic).toBe(VALID_MNEMONIC); expect(config.addresses.preview.startsWith('mn_addr_preview1')).toBe(true); @@ -195,8 +196,8 @@ describe('generate command — mnemonic mode', () => { await cliCall(generateCommand, parseArgs(['generate', '--network', 'preview', '--mnemonic', VALID_MNEMONIC, '--output', file1])); await cliCall(generateCommand, parseArgs(['generate', '--network', 'preview', '--mnemonic', VALID_MNEMONIC, '--output', file2])); - const config1 = (await unlockWallet(file1)); - const config2 = (await unlockWallet(file2)); + const config1 = (await unlockWallet(file1, { root: stateRootIn(TEST_DIR) })); + const config2 = (await unlockWallet(file2, { root: stateRootIn(TEST_DIR) })); expect(config1.addresses.preview).toBe(config2.addresses.preview); expect(config1.seed).toBe(config2.seed); }); @@ -250,13 +251,13 @@ describe('generate command — overwrite protection', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); // Create the file first await cliCall(generateCommand, parseArgs(['generate', '--network', 'undeployed', '--seed', TEST_SEED, '--output', walletFile])); - const config1 = (await unlockWallet(walletFile)); + const config1 = (await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) })); io.clearStdout(); // Generate again with --force and a different seed const newSeed = '0000000000000000000000000000000000000000000000000000000000000003'; await cliCall(generateCommand, parseArgs(['generate', '--network', 'undeployed', '--seed', newSeed, '--force', '--output', walletFile])); - const config2 = (await unlockWallet(walletFile)); + const config2 = (await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) })); expect(config2.seed).toBe(newSeed); expect(config2.seed).not.toBe(config1.seed); diff --git a/src/__tests__/grant-prepare.test.ts b/src/__tests__/grant-prepare.test.ts index c039fd6e..777187c5 100644 --- a/src/__tests__/grant-prepare.test.ts +++ b/src/__tests__/grant-prepare.test.ts @@ -23,7 +23,7 @@ let origHome: string | undefined; const accounts = () => path.join(home, '.midnight', 'accounts'); const recordsOf = (wallet: string) => path.join(accounts(), 'undeployed', wallet); -const prepare = (...argv: string[]) => prepareGrant(parseArgs(['grant', ...argv, ...ENDPOINTS])); +const prepare = (...argv: string[]) => prepareGrant(parseArgs(['grant', ...argv, ...ENDPOINTS]), path.join(home, '.midnight')); const asAlice = (...argv: string[]) => prepare(...argv, '--wallet', 'alice'); // A wallet file, as far as preparing needs one: that it is there. const aliceWallet = () => { diff --git a/src/__tests__/helpers/shell-settings.ts b/src/__tests__/helpers/shell-settings.ts index e9b08357..f063cb7e 100644 --- a/src/__tests__/helpers/shell-settings.ts +++ b/src/__tests__/helpers/shell-settings.ts @@ -1,17 +1,12 @@ // The test run stands in for the shell: libraries read the environment the -// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, keep their state under -// the home the tests set (HOME), and load the engines the CLI ships, as the -// CLI gives them. +// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, and load the engines the +// CLI ships, as the CLI gives them. Where state is kept, each test says: its +// host's paths (test-host.ts), or the root it passes a library. -import { homedir } from 'node:os'; -import { join } from 'node:path'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import { loadInstalledEngine } from '../../lib/installed-engines.ts'; setSettingsSource(() => settingsFromEnvironment(process.env)); -setHostPathsSource(() => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() })); // And the engines this build ships, as the CLI gives them. setEngineLoader(loadInstalledEngine); diff --git a/src/__tests__/host-paths.test.ts b/src/__tests__/host-paths.test.ts new file mode 100644 index 00000000..4e909b9b --- /dev/null +++ b/src/__tests__/host-paths.test.ts @@ -0,0 +1,134 @@ +// Two hosts with different state roots in one process keep their state apart: +// each call's libraries are given its host's root, and nothing reads a +// process-wide one or the home directory. The config, the wallets, the open +// swap offers and the wallet caches each land under their own host's root. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { cacheRootDir, getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; +import { captureCommand } from '../lib/run-command.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; +import { getActiveWalletName, listWallets } from '../lib/wallet-config.ts'; +import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; +import { clearChainCaches } from '../lib/chain-caches.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const MAKER = 'mn_addr_undeployed1maker'; +const OFFER: OpenOffer = { + id: 'a1'.repeat(16), + terms: { give: { token: '00'.repeat(31) + '01', amount: 10n }, want: { token: '00'.repeat(31) + '02', amount: 7n } }, + nullifiers: ['n1'], + madeAt: new Date('2026-11-02T10:00:00.000Z'), + expiresAt: new Date('2026-11-03T10:00:00.000Z'), +}; + +let base: string; +let originalHome: string | undefined; +let rootA: string; +let rootB: string; +let hostA: Host; +let hostB: Host; + +/** A host whose state root is `/.midnight`, and a home of its own. */ +function hostAt(home: string): Host { + return createHost({ paths: { stateRoot: path.join(home, MIDNIGHT_DIR), home } }); +} + +/** A wallet created under `root`, sealed under the passphrase set there. */ +async function walletIn(root: string, name: string): Promise { + const passphrase = await passphraseForNewSecret(root, { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }); + await createWallet(root, name, walletSecretFrom({ seed: Buffer.alloc(32, name.length) }), passphrase); +} + +beforeEach(() => { + base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-host-paths-'))); + // The process's home is a third, empty folder: neither host's state may land there. + originalHome = process.env.HOME; + process.env.HOME = path.join(base, 'process-home'); + fs.mkdirSync(process.env.HOME); + hostA = hostAt(path.join(base, 'a')); + hostB = hostAt(path.join(base, 'b')); + rootA = hostA.paths().stateRoot; + rootB = hostB.paths().stateRoot; +}); + +afterEach(() => { + process.env.HOME = originalHome; + fs.rmSync(base, { recursive: true, force: true }); +}); + +describe('two hosts with different state roots', () => { + it('each read and write their own config through the config command', async () => { + await captureCommand(configCommand, parseArgs(['config', 'set', 'network', 'preview']), { host: hostA }); + await captureCommand(configCommand, parseArgs(['config', 'set', 'network', 'preprod']), { host: hostB }); + + expect(await captureCommand(configCommand, parseArgs(['config', 'get', 'network']), { host: hostA })).toMatchObject({ value: 'preview' }); + expect(await captureCommand(configCommand, parseArgs(['config', 'get', 'network']), { host: hostB })).toMatchObject({ value: 'preprod' }); + expect(loadCliConfig(rootA).network).toBe('preview'); + expect(loadCliConfig(rootB).network).toBe('preprod'); + expect(fs.readdirSync(process.env.HOME!)).toEqual([]); + }); + + it('each create, list and activate their own wallets', async () => { + await walletIn(rootA, 'alice'); + await walletIn(rootB, 'bob'); + + expect((await listWallets(rootA)).map((w) => w.name)).toEqual(['alice']); + expect((await listWallets(rootB)).map((w) => w.name)).toEqual(['bob']); + expect(getActiveWalletName(rootA)).toBe('alice'); + expect(getActiveWalletName(rootB)).toBe('bob'); + // As the MCP server runs it. + const { default: walletCommand } = await installedCommands.find('wallet')!.load(); + const listedA = await captureCommand(walletCommand, parseArgs(['wallet', 'list']), { host: hostA }); + const listedB = await captureCommand(walletCommand, parseArgs(['wallet', 'list']), { host: hostB }); + expect((listedA.wallets as { name: string }[]).map((w) => w.name)).toEqual(['alice']); + expect((listedB.wallets as { name: string }[]).map((w) => w.name)).toEqual(['bob']); + expect(fs.existsSync(path.join(rootA, 'wallets', 'alice.json'))).toBe(true); + expect(fs.existsSync(path.join(rootB, 'wallets', 'bob.json'))).toBe(true); + expect(fs.readdirSync(process.env.HOME!)).toEqual([]); + }); + + it('each keep their own open swap offers', () => { + recordOpenOffer(rootA, 'undeployed', MAKER, OFFER); + + expect(readOpenOffers(rootA, 'undeployed', MAKER)).toEqual([OFFER]); + expect(readOpenOffers(rootB, 'undeployed', MAKER)).toEqual([]); + expect(openOffersFile(rootA, 'undeployed', MAKER)).toBe(path.join(rootA, 'swap-offers', 'undeployed', `${MAKER}.json`)); + expect(fs.existsSync(path.join(rootB, 'swap-offers'))).toBe(false); + }); + + it('each keep their wallet caches in their own folder, named by their own config\'s SDK set', async () => { + const address = 'mn_addr_undeployed1abcdefghijklmnopqrst'; + await captureCommand(configCommand, parseArgs(['config', 'set', 'sdk-set', 'beta', '--network', 'undeployed']), { host: hostA }); + + expect(cacheRootDir(rootA)).toBe(path.join(rootA, 'cache')); + expect(cacheRootDir(rootB)).toBe(path.join(rootB, 'cache')); + expect(sdkSetOf('undeployed', rootA)).toBe('beta'); + expect(sdkSetOf('undeployed', rootB)).toBe('rc'); + expect(networkCacheFolder('undeployed', rootA)).toBe('undeployed.beta'); + expect(networkCacheFolder('undeployed', rootB)).toBe('undeployed'); + const cacheA = getCachePath(address, 'undeployed', rootA); + const cacheB = getCachePath(address, 'undeployed', rootB); + expect(cacheA).toBe(path.join(rootA, 'cache', 'undeployed.beta', 'mn_addr_undeployed1a.json')); + expect(cacheB).toBe(path.join(rootB, 'cache', 'undeployed', 'mn_addr_undeployed1a.json')); + + // Clearing one host's caches leaves the other's. + for (const file of [cacheA, cacheB]) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, '{}'); + } + clearChainCaches('undeployed', rootB); + expect(fs.existsSync(cacheA)).toBe(true); + expect(fs.existsSync(cacheB)).toBe(false); + }); +}); diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index a9c1bd7b..20129fa3 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -20,6 +20,7 @@ import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { localIndexerFlags } from './helpers/local-indexer.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-json-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; @@ -344,12 +345,12 @@ describe('config --json', () => { let originalNetwork: string; beforeEach(() => { - originalNetwork = loadCliConfig().network; + originalNetwork = loadCliConfig(stateRootIn(TEST_DIR)).network; }); afterEach(async () => { // Restore original config - if (loadCliConfig().network !== originalNetwork) { + if (loadCliConfig(stateRootIn(TEST_DIR)).network !== originalNetwork) { io.restore(); const restoreIo = captureOutput(); await cliCall(configCommand, parseArgs(['config', 'set', 'network', originalNetwork])); diff --git a/src/__tests__/localnet-cancellation.test.ts b/src/__tests__/localnet-cancellation.test.ts index 120a9944..6ffbb24c 100644 --- a/src/__tests__/localnet-cancellation.test.ts +++ b/src/__tests__/localnet-cancellation.test.ts @@ -137,7 +137,7 @@ describe('localnet commands, cancelled while Docker runs', () => { }); describe('localnet up, cancelled (started containers stay, and it says which)', () => { - const dockerCall = (exec: ExecRunner, signal: AbortSignal): DockerCall => ({ signal, exec, onStderr: () => {} }); + const dockerCall = (exec: ExecRunner, signal: AbortSignal): DockerCall => ({ signal, exec, onStderr: () => {}, root: join(home, '.midnight') }); it('during docker compose up: the client is killed, and the error names the containers left in place', async () => { const call = new AbortController(); diff --git a/src/__tests__/localnet-command.test.ts b/src/__tests__/localnet-command.test.ts index 4018ed05..4b26f2e7 100644 --- a/src/__tests__/localnet-command.test.ts +++ b/src/__tests__/localnet-command.test.ts @@ -140,15 +140,17 @@ describe('ledger-9 build: mn localnet cannot start a network', () => { // The compose stack is ledger 8, which wallet-sdk 2.0 can't sync with, and // no published indexer image runs ledger 9 yet. Every start path goes // through ensureComposeFile, so it refuses there, before writing anything. + // A state root of the test's own, which nothing creates. + const root = join(tmpdir(), `midnight-localnet-ledger9-${process.pid}`); const composeFingerprint = () => { - const path = getComposePath(); + const path = getComposePath(root); return existsSync(path) ? `${statSync(path).mtimeMs}:${readFileSync(path, 'utf-8').length}` : 'absent'; }; it('ensureComposeFile refuses, says what to run instead, and writes nothing', () => { const before = composeFingerprint(); let err: unknown; - try { ensureComposeFile(); } catch (e) { err = e; } + try { ensureComposeFile(root); } catch (e) { err = e; } expect(err).toBeInstanceOf(LocalnetUnavailableError); const msg = (err as Error).message; expect(msg).toContain('ledger 9'); diff --git a/src/__tests__/manual-command.test.ts b/src/__tests__/manual-command.test.ts index 3b4d5a51..b116ce13 100644 --- a/src/__tests__/manual-command.test.ts +++ b/src/__tests__/manual-command.test.ts @@ -1,4 +1,7 @@ import { describe, it, expect } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { buildManual } from '../commands/manual.ts'; import { getConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { installedCommands } from '../lib/installed-commands.ts'; @@ -80,7 +83,8 @@ describe('mn manual', () => { it('describes every key `config` accepts', () => { // The keys config accepts, as its refusal of an unknown key lists them. let refusal = ''; - try { getConfigValue('no-such-key'); } catch (err) { refusal = (err as Error).message; } + const root = mkdtempSync(join(tmpdir(), 'mn-manual-')); + try { getConfigValue('no-such-key', root); } catch (err) { refusal = (err as Error).message; } finally { rmSync(root, { recursive: true, force: true }); } const keys = refusal.split('Valid keys: ')[1]!.split(', '); expect(keys.length).toBeGreaterThan(0); const section = stripAnsi(buildManual()).split('Config keys')[1]!.split('Compatibility alias')[0]!; diff --git a/src/__tests__/mcp-server-advice.test.ts b/src/__tests__/mcp-server-advice.test.ts index 74addceb..8a427791 100644 --- a/src/__tests__/mcp-server-advice.test.ts +++ b/src/__tests__/mcp-server-advice.test.ts @@ -1,23 +1,30 @@ // A call the MCP server can't take because of the SDK set it runs is told to use a server of its own. -import { describe, expect, it } from 'vitest'; +import { afterAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; import { withServerAdvice } from '../lib/mcp/server-advice.ts'; +// A state root with no config: every network on the set the table names. +const ROOT = mkdtempSync(join(tmpdir(), 'mn-server-advice-')); +afterAll(() => rmSync(ROOT, { recursive: true, force: true })); + describe('the MCP server\'s advice for a call on the other SDK set', () => { it('names the networks of the set it can\'t load, and says to start a server for them', () => { - const advised = withServerAdvice(new OtherSdkSetError('rc', 'beta')); + const advised = withServerAdvice(new OtherSdkSetError('rc', 'beta'), ROOT); expect(advised).toBeInstanceOf(OtherSdkSetError); expect(advised).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'rc', wantedSet: 'beta' }); expect(advised.message).toBe("This MCP server runs the rc SDK set, and stagenet runs on the beta set: two sets' ledgers can't share a process. Start another MCP server for stagenet and make the call there."); }); it('names every network of the rc set the other way round', () => { - expect(withServerAdvice(new OtherSdkSetError('beta', 'rc')).message).toContain('and preprod, preview, undeployed run on the rc set'); + expect(withServerAdvice(new OtherSdkSetError('beta', 'rc'), ROOT).message).toContain('and preprod, preview, undeployed run on the rc set'); }); it('leaves every other error as it was', () => { const error = new Error('something else'); - expect(withServerAdvice(error)).toBe(error); + expect(withServerAdvice(error, ROOT)).toBe(error); }); }); diff --git a/src/__tests__/multi-wallet.test.ts b/src/__tests__/multi-wallet.test.ts index fd954eab..ec705060 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/src/__tests__/multi-wallet.test.ts @@ -74,37 +74,32 @@ afterEach(() => { describe('resolveWalletPath', () => { it('treats value with / as a file path', () => { - const result = resolveWalletPath('/tmp/my-wallet.json'); + const result = resolveWalletPath(TEST_MIDNIGHT_DIR, '/tmp/my-wallet.json'); expect(result).toBe('/tmp/my-wallet.json'); }); it('treats value ending in .json as a file path', () => { - const result = resolveWalletPath('wallet.json'); + const result = resolveWalletPath(TEST_MIDNIGHT_DIR, 'wallet.json'); expect(path.isAbsolute(result)).toBe(true); expect(result).toContain('wallet.json'); }); it('treats simple name as wallet name and resolves to wallets dir', () => { - const result = resolveWalletPath('alice'); + const result = resolveWalletPath(TEST_MIDNIGHT_DIR, 'alice'); expect(result).toContain(WALLETS_DIR_NAME); expect(result).toContain('alice.json'); }); it('resolves to wallets directory when no argument given', () => { - // resolveWalletPath reads the real ~/.midnight/config.json for the active wallet name, - // falling back to DEFAULT_WALLET_NAME if no config exists. - const result = resolveWalletPath(); + // No config under the state root: the default wallet. + const result = resolveWalletPath(TEST_MIDNIGHT_DIR); expect(result).toContain(WALLETS_DIR_NAME); expect(result).toMatch(/\.json$/); }); it('uses active wallet from config when no argument given', () => { - // resolveWalletPath reads from real ~/.midnight/config.json - // We can't inject a test config dir, so we verify the behavior - // by checking that the result uses the wallets directory pattern - const result = resolveWalletPath(); - expect(result).toContain(WALLETS_DIR_NAME); - expect(result).toMatch(/\.json$/); + createConfig({ wallet: 'alice' }); + expect(resolveWalletPath(TEST_MIDNIGHT_DIR)).toBe(path.join(TEST_WALLETS_DIR, 'alice.json')); }); }); @@ -112,10 +107,8 @@ describe('resolveWalletPath', () => { describe('listWallets', () => { it('returns empty array when wallets dir does not exist', async () => { - const wallets = await listWallets(); - // There might be a real ~/.midnight/wallets dir, but in test context - // we check the structure is correct - expect(Array.isArray(wallets)).toBe(true); + const wallets = await listWallets(TEST_MIDNIGHT_DIR); + expect(wallets).toEqual([]); }); it('lists wallets from wallets directory', () => { @@ -144,20 +137,20 @@ describe('listWallets', () => { describe('removeWallet', () => { it('throws when wallet does not exist', () => { - expect(() => removeWallet('nonexistent')).toThrow('not found'); + expect(() => removeWallet(TEST_MIDNIGHT_DIR, 'nonexistent')).toThrow('not found'); }); it('rejects invalid wallet names with path traversal', () => { - expect(() => removeWallet('../evil')).toThrow('Invalid wallet name'); - expect(() => removeWallet('path/to/wallet')).toThrow('Invalid wallet name'); + expect(() => removeWallet(TEST_MIDNIGHT_DIR, '../evil')).toThrow('Invalid wallet name'); + expect(() => removeWallet(TEST_MIDNIGHT_DIR, 'path/to/wallet')).toThrow('Invalid wallet name'); }); it('rejects empty wallet name', () => { - expect(() => removeWallet('')).toThrow('Invalid wallet name'); + expect(() => removeWallet(TEST_MIDNIGHT_DIR, '')).toThrow('Invalid wallet name'); }); it('rejects wallet name ending in .json', () => { - expect(() => removeWallet('test.json')).toThrow('Invalid wallet name'); + expect(() => removeWallet(TEST_MIDNIGHT_DIR, 'test.json')).toThrow('Invalid wallet name'); }); }); @@ -166,12 +159,12 @@ describe('removeWallet', () => { describe('migrateOldWallet', () => { it('is a no-op when old wallet does not exist', () => { // Should not throw - migrateOldWallet(); + migrateOldWallet(TEST_MIDNIGHT_DIR); }); it('is idempotent — does nothing on second call', () => { - migrateOldWallet(); - migrateOldWallet(); + migrateOldWallet(TEST_MIDNIGHT_DIR); + migrateOldWallet(TEST_MIDNIGHT_DIR); // No error }); }); @@ -189,20 +182,20 @@ describe('loadWalletConfig error messages', () => { describe('setActiveWallet validation', () => { it('rejects path traversal names', () => { - expect(() => setActiveWallet('../evil')).toThrow('Invalid wallet name'); - expect(() => setActiveWallet('a/b')).toThrow('Invalid wallet name'); + expect(() => setActiveWallet(TEST_MIDNIGHT_DIR, '../evil')).toThrow('Invalid wallet name'); + expect(() => setActiveWallet(TEST_MIDNIGHT_DIR, 'a/b')).toThrow('Invalid wallet name'); }); it('rejects empty name', () => { - expect(() => setActiveWallet('')).toThrow('Invalid wallet name'); + expect(() => setActiveWallet(TEST_MIDNIGHT_DIR, '')).toThrow('Invalid wallet name'); }); it('rejects .json suffix', () => { - expect(() => setActiveWallet('test.json')).toThrow('Invalid wallet name'); + expect(() => setActiveWallet(TEST_MIDNIGHT_DIR, 'test.json')).toThrow('Invalid wallet name'); }); it('rejects control characters', () => { - expect(() => setActiveWallet('test\x00name')).toThrow('Invalid wallet name'); + expect(() => setActiveWallet(TEST_MIDNIGHT_DIR, 'test\x00name')).toThrow('Invalid wallet name'); }); }); diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index e3c85050..80fe799f 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -39,8 +39,8 @@ beforeEach(async () => { process.env.HOME = home; process.env.MN_PASSPHRASE = PASSPHRASE; establishPassphrase(stateRootIn(home), PASSPHRASE); - await createWallet('alice', walletSecretFrom(), PASSPHRASE); - await createWallet('bob', walletSecretFrom(), PASSPHRASE); + await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE); + await createWallet(stateRootIn(home), 'bob', walletSecretFrom(), PASSPHRASE); io = captureOutput(); // Every endpoint: takes HTTP requests and WebSocket upgrades, and answers none. requests = 0; diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index b09a5343..6924df31 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -45,7 +45,7 @@ describe('notices', () => { it("carry a library's warning when its caller gives no warn of its own", async () => { const lines: string[] = []; setNoticeSink((line) => lines.push(line)); - await unlockWallet(plainWallet('notice-alice')); + await unlockWallet(plainWallet('notice-alice'), { root: path.join(home, '.midnight') }); expect(lines.join('\n')).toMatch(/not protected: its seed is in plain text/); }); diff --git a/src/__tests__/open-offers.test.ts b/src/__tests__/open-offers.test.ts index 6b694e5a..c36f538c 100644 --- a/src/__tests__/open-offers.test.ts +++ b/src/__tests__/open-offers.test.ts @@ -3,10 +3,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync, statSync } from 'node:fs'; -import { tmpdir, homedir } from 'node:os'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import { assertSpendsNoOfferCoin, closeOpenOffers, OfferCoinsInUseError, openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; @@ -19,31 +17,31 @@ const offer = (id: string, nullifiers: string[]): OpenOffer => ({ expiresAt: new Date('2026-11-03T10:00:00.000Z'), }); +let home: string; let root: string; beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'mn-open-offers-')); - setHostPathsSource(() => ({ stateRoot: join(root, '.midnight'), home: root })); + home = mkdtempSync(join(tmpdir(), 'mn-open-offers-')); + root = join(home, '.midnight'); }); afterEach(() => { - setHostPathsSource(() => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() })); - rmSync(root, { recursive: true, force: true }); + rmSync(home, { recursive: true, force: true }); }); describe('open offers', () => { it('records an offer per wallet and network, in mn\'s state, readable only by its owner', () => { - recordOpenOffer('undeployed', WALLET, offer('a1', ['n1'])); - expect(readOpenOffers('undeployed', WALLET)).toEqual([offer('a1', ['n1'])]); - expect(readOpenOffers('stagenet', WALLET)).toEqual([]); - expect(openOffersFile('undeployed', WALLET)).toBe(join(root, '.midnight', 'swap-offers', 'undeployed', `${WALLET}.json`)); - expect(statSync(openOffersFile('undeployed', WALLET)).mode & 0o077).toBe(0); + recordOpenOffer(root, 'undeployed', WALLET, offer('a1', ['n1'])); + expect(readOpenOffers(root, 'undeployed', WALLET)).toEqual([offer('a1', ['n1'])]); + expect(readOpenOffers(root, 'stagenet', WALLET)).toEqual([]); + expect(openOffersFile(root, 'undeployed', WALLET)).toBe(join(root, 'swap-offers', 'undeployed', `${WALLET}.json`)); + expect(statSync(openOffersFile(root, 'undeployed', WALLET)).mode & 0o077).toBe(0); }); it('closes offers by id, keeping the rest', () => { - recordOpenOffer('undeployed', WALLET, offer('a1', ['n1'])); - recordOpenOffer('undeployed', WALLET, offer('a2', ['n2'])); - expect(closeOpenOffers('undeployed', WALLET, ['a1']).map((o) => o.id)).toEqual(['a1']); - expect(readOpenOffers('undeployed', WALLET).map((o) => o.id)).toEqual(['a2']); - expect(closeOpenOffers('undeployed', WALLET, ['gone'])).toEqual([]); + recordOpenOffer(root, 'undeployed', WALLET, offer('a1', ['n1'])); + recordOpenOffer(root, 'undeployed', WALLET, offer('a2', ['n2'])); + expect(closeOpenOffers(root, 'undeployed', WALLET, ['a1']).map((o) => o.id)).toEqual(['a1']); + expect(readOpenOffers(root, 'undeployed', WALLET).map((o) => o.id)).toEqual(['a2']); + expect(closeOpenOffers(root, 'undeployed', WALLET, ['gone'])).toEqual([]); }); it('refuses a spend of an open offer\'s coin, naming the offer, unless the spend cancels it', () => { diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index 732f1608..01598d78 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -20,6 +20,7 @@ import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import contractCommand from '../commands/contract.ts'; import grantCommand from '../commands/grant.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -39,7 +40,7 @@ afterEach(() => { describe('resolvePayingTarget', () => { it('acts on undeployed when no network is given, with the endpoints given as flags', () => { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); expect(target.network).toBe('undeployed'); expect(target.endpoints).toEqual({ node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', proofServer: 'http://localhost:26300' }); expect(target.networkConfig.node).toBe('ws://localhost:29944'); @@ -48,9 +49,9 @@ describe('resolvePayingTarget', () => { }); it('acts on the network set with config set network when none is given, as every other command does', () => { - saveCliConfig({ network: 'preprod' }); - expect(resolvePayingTarget(parseArgs(['contract', 'deploy']), 'contract', 'deploy').network).toBe('preprod'); - expect(resolvePayingTarget(parseArgs(['contract', 'deploy', '--network', 'preview']), 'contract', 'deploy').network).toBe('preview'); + saveCliConfig({ network: 'preprod' }, stateRootIn(home)); + expect(resolvePayingTarget(parseArgs(['contract', 'deploy']), 'contract', 'deploy', stateRootIn(home)).network).toBe('preprod'); + expect(resolvePayingTarget(parseArgs(['contract', 'deploy', '--network', 'preview']), 'contract', 'deploy', stateRootIn(home)).network).toBe('preview'); }); }); @@ -99,7 +100,7 @@ describe('the serve payer', () => { const serve = await runningServe(); const said: string[] = []; try { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); const served = await servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings, undefined); expect(served.port).toBe(serve.port); expect(said).toEqual([`Reusing existing mn serve on port ${serve.port}`, `mn serve ready (port ${serve.port})`]); @@ -114,7 +115,7 @@ describe('the serve payer', () => { const serve = await runningServe(); const said: string[] = []; try { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); const controller = new AbortController(); controller.abort(); await expect(servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings, controller.signal)).rejects.toBeInstanceOf(CancelledError); @@ -125,7 +126,7 @@ describe('the serve payer', () => { }); it('checks no wallet for a call already cancelled', async () => { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy'); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); const controller = new AbortController(); controller.abort(); // Not cancelled, this would fail on the missing wallet file. diff --git a/src/__tests__/prep-runner-cancellation.test.ts b/src/__tests__/prep-runner-cancellation.test.ts index 86c61c98..d51ed1fa 100644 --- a/src/__tests__/prep-runner-cancellation.test.ts +++ b/src/__tests__/prep-runner-cancellation.test.ts @@ -14,7 +14,7 @@ describe('runPrepSteps', () => { const controller = new AbortController(); controller.abort(); const started: string[] = []; - await expect(runPrepSteps(config, '/nonexistent', createPrepContext(createSdkWarningRouter().openCall().warnings, controller.signal), { + await expect(runPrepSteps(config, '/nonexistent', createPrepContext('/nonexistent/.midnight', createSdkWarningRouter().openCall().warnings, controller.signal), { onStepStart: (step) => started.push(step), onStepComplete: () => {}, onMessage: () => {}, diff --git a/src/__tests__/provision-wallets.test.ts b/src/__tests__/provision-wallets.test.ts index f84d4dd5..d52ea585 100644 --- a/src/__tests__/provision-wallets.test.ts +++ b/src/__tests__/provision-wallets.test.ts @@ -8,6 +8,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { provisionDevWallets, type ProvisionSteps } from '../lib/dev/provision-wallets.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; let home: string; let originalHome: string | undefined; @@ -41,6 +42,7 @@ describe('provisionDevWallets', () => { const progress: string[] = []; const result = await provisionDevWallets({ + root: stateRootIn(home), names: ['dev-alice', 'dev-bob', 'dev-carol'], amountNight: 1000, steps: recordingSteps(calls), @@ -68,7 +70,7 @@ describe('provisionDevWallets', () => { writeFileSync(join(home, '.midnight', 'wallets', 'dev-alice.json'), '{}'); const calls: string[] = []; - const result = await provisionDevWallets({ names: ['dev-alice'], amountNight: 1000, steps: recordingSteps(calls, ['dev-alice']) }); + const result = await provisionDevWallets({ root: stateRootIn(home), names: ['dev-alice'], amountNight: 1000, steps: recordingSteps(calls, ['dev-alice']) }); expect(calls).toEqual(['check dev-alice', 'register dev-alice']); expect(result).toEqual([{ name: 'dev-alice', state: 'created' }]); @@ -82,7 +84,7 @@ describe('provisionDevWallets', () => { steps.airdrop = async (name, amount, signal) => { await airdrop(name, amount, signal); controller.abort(); }; // Regression: it failed with the signal's own AbortError, which mn's error codes don't read as CANCELLED. - await expect(provisionDevWallets({ names: ['dev-alice'], amountNight: 1000, steps, signal: controller.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(provisionDevWallets({ root: stateRootIn(home), names: ['dev-alice'], amountNight: 1000, steps, signal: controller.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(calls).toEqual(['generate dev-alice', 'airdrop dev-alice 1000']); }); }); diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 3273cb3d..8c2c7ebf 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -63,7 +63,7 @@ describe('parseSeedHex', () => { describe('resolveSeedSource', () => { it('reads --seed, with no backing wallet file/config', async () => { - const r = await resolveSeedSource(argsFor(['--seed', SEED_A])); + const r = await resolveSeedSource(argsFor(['--seed', SEED_A]), stateRootIn(TMP)); expect(r.seed.toString('hex')).toBe(SEED_A); expect(r.walletPath).toBeNull(); expect(r.config).toBeNull(); @@ -71,46 +71,46 @@ describe('resolveSeedSource', () => { it('reads MN_SEED when --seed is absent', async () => { process.env.MN_SEED = SEED_A; - const r = await resolveSeedSource(argsFor([])); + const r = await resolveSeedSource(argsFor([]), stateRootIn(TMP)); expect(r.seed.toString('hex')).toBe(SEED_A); expect(r.walletPath).toBeNull(); }); it('lets --seed win over MN_SEED', async () => { process.env.MN_SEED = SEED_B; - const r = await resolveSeedSource(argsFor(['--seed', SEED_A])); + const r = await resolveSeedSource(argsFor(['--seed', SEED_A]), stateRootIn(TMP)); expect(r.seed.toString('hex')).toBe(SEED_A); }); it('strips 0x and trims a trailing newline (MN_SEED from $(cat seed.hex))', async () => { process.env.MN_SEED = `0x${SEED_A}\n`; - const r = await resolveSeedSource(argsFor([])); + const r = await resolveSeedSource(argsFor([]), stateRootIn(TMP)); expect(r.seed.toString('hex')).toBe(SEED_A); }); it('rejects a bad-length --seed', async () => { - await expect(resolveSeedSource(argsFor(['--seed', 'aabb']))).rejects.toThrow(/64 or 128 hex characters/); + await expect(resolveSeedSource(argsFor(['--seed', 'aabb']), stateRootIn(TMP))).rejects.toThrow(/64 or 128 hex characters/); }); it('accepts a 128-hex (64-byte BIP-39) --seed', async () => { const seed64 = '33'.repeat(64); - const r = await resolveSeedSource(argsFor(['--seed', seed64])); + const r = await resolveSeedSource(argsFor(['--seed', seed64]), stateRootIn(TMP)); expect(r.seed.length).toBe(64); expect(r.seed.toString('hex')).toBe(seed64); }); it('rejects in-between lengths (only 32- and 64-byte seeds occur)', async () => { - await expect(resolveSeedSource(argsFor(['--seed', '44'.repeat(48)]))).rejects.toThrow(/64 or 128 hex characters/); + await expect(resolveSeedSource(argsFor(['--seed', '44'.repeat(48)]), stateRootIn(TMP))).rejects.toThrow(/64 or 128 hex characters/); }); it('names MN_SEED in the error when MN_SEED is the bad source', async () => { process.env.MN_SEED = 'zz'; - await expect(resolveSeedSource(argsFor([]))).rejects.toThrow(/MN_SEED/); + await expect(resolveSeedSource(argsFor([]), stateRootIn(TMP))).rejects.toThrow(/MN_SEED/); }); it('reads a wallet file via --wallet, exposing walletPath + config', async () => { const p = walletFile(SEED_B); - const r = await resolveSeedSource(argsFor(['--wallet', p])); + const r = await resolveSeedSource(argsFor(['--wallet', p]), stateRootIn(TMP)); expect(r.seed.toString('hex')).toBe(SEED_B); expect(r.walletPath).toBe(p); expect(r.config).not.toHaveProperty('seed'); @@ -123,7 +123,7 @@ describe('resolveSeedSource', () => { try { establishPassphrase(stateRootIn(TMP), PASSPHRASE); const p = writeSealedWallet(join(TMP, 'sealed.json'), { addresses: {} as WalletPublic['addresses'], createdAt: new Date().toISOString() }, { seed: SEED_B }, PASSPHRASE); - const r = await resolveSeedSource(argsFor(['--wallet', p])); + const r = await resolveSeedSource(argsFor(['--wallet', p]), stateRootIn(TMP)); expect(r.seed.toString('hex')).toBe(SEED_B); expect(r.config?.isSealed).toBe(true); } finally { @@ -134,15 +134,15 @@ describe('resolveSeedSource', () => { it('requireExplicit throws a labeled error naming every source when none is given', async () => { // No --seed / MN_SEED / --wallet, and requireExplicit disables the active fallback. - await expect(resolveSeedSource(argsFor([]), { requireExplicit: true, label: 'address' })) + await expect(resolveSeedSource(argsFor([]), stateRootIn(TMP), { requireExplicit: true, label: 'address' })) .rejects.toThrow(/address needs a seed source/); - const msg = await resolveSeedSource(argsFor([]), { requireExplicit: true, label: 'address' }).then(() => '', (e: Error) => e.message); + const msg = await resolveSeedSource(argsFor([]), stateRootIn(TMP), { requireExplicit: true, label: 'address' }).then(() => '', (e: Error) => e.message); expect(msg).toContain('--seed'); expect(msg).toContain('MN_SEED'); expect(msg).toContain('--wallet'); }); it('resolveSeed returns just the seed buffer', async () => { - expect((await resolveSeed(argsFor(['--seed', SEED_A]))).toString('hex')).toBe(SEED_A); + expect((await resolveSeed(argsFor(['--seed', SEED_A]), stateRootIn(TMP))).toString('hex')).toBe(SEED_A); }); }); diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index 4231d845..84a03167 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -10,6 +10,7 @@ import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; const scratch = { node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws' }; @@ -68,6 +69,11 @@ describe('startServeOrReuse against a running serve', () => { // A fake `mn serve`: a real JSON-RPC WebSocket server answering the two // probes the reuse check makes. Endpoints are passed explicitly, so neither // docker nor saved config affects what is requested. + // A state root of the test's own, with no config, for the calls that need no wallet. + let emptyRoot: string; + beforeEach(() => { emptyRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-serve-root-')); }); + afterEach(() => fs.rmSync(emptyRoot, { recursive: true, force: true })); + async function fakeServe(configuration: Record, unshieldedAddress?: string) { const { WebSocketServer } = await import('ws'); const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' }); @@ -94,7 +100,7 @@ describe('startServeOrReuse against a running serve', () => { const serve = await fakeServe({ substrateNodeUri: requested.node, indexerWsUri: requested.indexerWS }); try { const messages: string[] = []; - const handle = await startServeOrReuse({ port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, onMessage: (m) => messages.push(m) }); + const handle = await startServeOrReuse({ root: emptyRoot, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, onMessage: (m) => messages.push(m) }); expect(handle.port).toBe(serve.port); expect(messages).toContain(`Reusing existing mn serve on port ${serve.port}`); await handle.stop(); // a no-op for a reused serve: the fake must still answer @@ -109,7 +115,7 @@ describe('startServeOrReuse against a running serve', () => { const { startServeOrReuse } = await import('../lib/serve-manager.ts'); const serve = await fakeServe({ substrateNodeUri: 'ws://localhost:9944', indexerWsUri: 'ws://localhost:8088/api/v4/graphql/ws' }); try { - await expect(startServeOrReuse({ port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested })) + await expect(startServeOrReuse({ root: emptyRoot, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested })) .rejects.toThrow(/on a different undeployed chain: node ws:\/\/localhost:9944 \(need ws:\/\/localhost:29944\)/); } finally { await serve.close(); @@ -145,7 +151,7 @@ describe('startServeOrReuse against a running serve', () => { const { startServeOrReuse } = await import('../lib/serve-manager.ts'); const serve = await fakeServe(sameChain, deriveAllAddresses(TWO).undeployed); try { - const handle = await startServeOrReuse({ port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' }); + const handle = await startServeOrReuse({ root: stateRootIn(home), port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' }); expect(handle.port).toBe(serve.port); } finally { await serve.close(); @@ -159,7 +165,7 @@ describe('startServeOrReuse against a running serve', () => { const bob = deriveAllAddresses(BOB).undeployed; const serve = await fakeServe(sameChain, bob); try { - await expect(startServeOrReuse({ port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' })) + await expect(startServeOrReuse({ root: stateRootIn(home), port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' })) .rejects.toThrow(`can't pay for this command: it serves the wallet at ${bob}, and this command pays from two (${deriveAllAddresses(TWO).undeployed})`); } finally { await serve.close(); diff --git a/src/__tests__/shielded-direct-cache.test.ts b/src/__tests__/shielded-direct-cache.test.ts index 8f23b4c8..eb00b501 100644 --- a/src/__tests__/shielded-direct-cache.test.ts +++ b/src/__tests__/shielded-direct-cache.test.ts @@ -53,7 +53,7 @@ describe('shielded-direct cache round-trip', () => { it('rejects a version mismatch', () => { const path = getShieldedCachePath('undeployed', PUBKEY, dir); - mkdirSync(join(dir, 'undeployed'), { recursive: true }); + mkdirSync(join(dir, 'cache', 'undeployed'), { recursive: true }); const raw = { version: 999, network: 'undeployed', coinPublicKeyHex: PUBKEY, lastAppliedEventId: 1, timestamp: '', zswapState: Buffer.from(freshState().serialize()).toString('hex') }; writeFileSync(path, JSON.stringify(raw)); expect(loadShieldedCache('undeployed', PUBKEY, dir)).toBeNull(); diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index d4b64616..d864ffbb 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -1,14 +1,18 @@ -// Each owner builds its paths under the state root the host gives, -// and the files land where they did before the state root, with the same contents: the +// Each owner builds its paths under the state root it is given, and the files +// land where they did before the state root, with the same contents: the // fixture was recorded from the code before the change. A root outside the -// home gets the same layout and nothing is written to the home; with no root -// given, a library refuses instead of guessing. +// home gets the same layout and nothing is written to the home; a host that +// gave no root refuses instead of guessing. import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { setHostPathsSource, stateRoot, NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; +import { cliCall } from './helpers/cli-call.ts'; import { setConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { passphraseForNewSecret, PASSPHRASE_ENV } from '../lib/passphrase.ts'; @@ -31,18 +35,16 @@ beforeEach(() => { }); afterEach(() => { delete process.env[PASSPHRASE_ENV]; - // Back to what the test harness gives, as the shell does. - setHostPathsSource(() => ({ stateRoot: path.join(os.homedir(), MIDNIGHT_DIR), home: os.homedir() })); fs.rmSync(dir, { recursive: true, force: true }); }); -/** The same steps the fixture was recorded with, through each owner. */ -async function writeEveryOwnersFiles(): Promise { - setConfigValue('network', 'preview'); - setConfigValue('node', 'ws://localhost:29944', undefined, 'undeployed'); - bindCachesToIndexer('undeployed', 'ws://localhost:28088/api/v4/graphql/ws'); - await createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret()); - fs.mkdirSync(accountRecordsDir('undeployed', 'alice'), { recursive: true }); +/** The same steps the fixture was recorded with, through each owner, under the state root `root`. */ +async function writeEveryOwnersFiles(root: string): Promise { + setConfigValue('network', 'preview', root); + setConfigValue('node', 'ws://localhost:29944', root, 'undeployed'); + bindCachesToIndexer('undeployed', 'ws://localhost:28088/api/v4/graphql/ws', root); + await createWallet(root, 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret(root)); + fs.mkdirSync(accountRecordsDir('undeployed', 'alice', root), { recursive: true }); } /** Every file and folder under `root`, relative to `base`, folders ending in /. */ @@ -55,9 +57,8 @@ function layout(root: string, base: string): string[] { describe('the state root the host gives', () => { it('lays out every owner\'s files as before the state root, with the same contents', async () => { const home = path.join(dir, 'home'); - setHostPathsSource(() => ({ stateRoot: path.join(home, MIDNIGHT_DIR), home })); - await writeEveryOwnersFiles(); - const root = stateRoot(); + const root = path.join(home, MIDNIGHT_DIR); + await writeEveryOwnersFiles(root); const rel = (p: string) => path.relative(home, p); const wallet = JSON.parse(fs.readFileSync(path.join(root, 'wallets/alice.json'), 'utf8')); @@ -71,11 +72,11 @@ describe('the state root the host gives', () => { expect(stagenet).toMatch(/^mn_addr_stagenet1/); expect(Object.keys(JSON.parse(fs.readFileSync(path.join(root, 'keystore.json'), 'utf8')))).toEqual(before.keystoreKeys); expect({ - walletCache: rel(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')), - dustCache: rel(getDustCachePath('undeployed', 'ab'.repeat(32))), - shieldedCache: rel(getShieldedCachePath('undeployed', 'cd'.repeat(32))), - compose: rel(getComposePath()), - accountArtifacts: rel(accountArtifactsDir()), + walletCache: rel(getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed', root)), + dustCache: rel(getDustCachePath('undeployed', 'ab'.repeat(32), root)), + shieldedCache: rel(getShieldedCachePath('undeployed', 'cd'.repeat(32), root)), + compose: rel(getComposePath(root)), + accountArtifacts: rel(accountArtifactsDir(root)), }).toEqual(before.paths); }); @@ -83,20 +84,16 @@ describe('the state root the host gives', () => { const home = path.join(dir, 'home'); const root = path.join(dir, 'elsewhere', 'state'); fs.mkdirSync(home, { recursive: true }); - setHostPathsSource(() => ({ stateRoot: root, home })); - await writeEveryOwnersFiles(); + await writeEveryOwnersFiles(root); expect(layout(root, root)).toEqual(before.files.filter((f) => f !== `${MIDNIGHT_DIR}/`).map((f) => f.slice(MIDNIGHT_DIR.length + 1))); expect(fs.readdirSync(home)).toEqual([]); - expect(getComposePath()).toBe(path.join(root, 'localnet', 'compose.yml')); + expect(getComposePath(root)).toBe(path.join(root, 'localnet', 'compose.yml')); }); - it('refuses when the host gave no root, for each owner', () => { - setHostPathsSource(null); - expect(() => stateRoot()).toThrow(NoStateRootError); - expect(() => setConfigValue('network', 'preview')).toThrow(NoStateRootError); - expect(() => getCachePath('mn_addr_undeployed1abcdefghijklmnopqrst', 'undeployed')).toThrow(NoStateRootError); - expect(() => getComposePath()).toThrow(NoStateRootError); - expect(() => accountRecordsDir('undeployed', 'alice')).toThrow(NoStateRootError); + it('refuses when the host gave no root, before a command runs', async () => { + const host = createHost(); + expect(() => host.paths()).toThrow(NoStateRootError); + await expect((async () => cliCall(configCommand, parseArgs(['config', 'set', 'network', 'preview']), { host }))()).rejects.toThrow(NoStateRootError); }); }); diff --git a/src/__tests__/swap-request.test.ts b/src/__tests__/swap-request.test.ts index a9dfb334..7e20c3ef 100644 --- a/src/__tests__/swap-request.test.ts +++ b/src/__tests__/swap-request.test.ts @@ -2,7 +2,7 @@ // opens: the terms, the expiry, and an offer file checked against its bytes, // its network, the agreed terms and its expiry. -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -15,6 +15,9 @@ import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../ import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; const NOW = new Date('2026-11-02T12:00:00.000Z'); +// A state root with no config: the networks' own endpoints. +const ROOT = mkdtempSync(join(tmpdir(), 'mn-swap-request-root-')); +afterAll(() => rmSync(ROOT, { recursive: true, force: true })); const TERMS = ['--give', '10', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT]; describe('the terms', () => { @@ -38,9 +41,9 @@ describe('the terms', () => { describe('make', () => { it('expires a day on unless --expires-in says', () => { - expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed']), NOW).expiresAt).toEqual(new Date(NOW.getTime() + DEFAULT_OFFER_LIFETIME_S * 1000)); - expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', '60']), NOW).expiresAt).toEqual(new Date(NOW.getTime() + 60_000)); - expect(() => prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', 'soon']), NOW)).toThrow('--expires-in must be a whole number of seconds'); + expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed']), ROOT, NOW).expiresAt).toEqual(new Date(NOW.getTime() + DEFAULT_OFFER_LIFETIME_S * 1000)); + expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', '60']), ROOT, NOW).expiresAt).toEqual(new Date(NOW.getTime() + 60_000)); + expect(() => prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', 'soon']), ROOT, NOW)).toThrow('--expires-in must be a whole number of seconds'); }); }); @@ -58,7 +61,7 @@ describe('take', () => { })); return file; }; - const take = (file: string, terms = TERMS) => prepareTake(parseArgs(['swap', 'take', file, ...terms, '--network', 'undeployed']), NOW); + const take = (file: string, terms = TERMS) => prepareTake(parseArgs(['swap', 'take', file, ...terms, '--network', 'undeployed']), ROOT, NOW); it('reads a real offer file at the agreed terms', async () => { const { offer, agreed, target } = await take(offerFile()); diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index dcd2f0f5..1de69fd1 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -34,7 +34,7 @@ function saveWallet(name: string, seed: Buffer, shielded = false): string { return file; } -const request = (...argv: string[]) => resolveTransferRequest(parseArgs(['transfer', ...argv])); +const request = (...argv: string[]) => resolveTransferRequest(parseArgs(['transfer', ...argv]), path.join(HOME, MIDNIGHT_DIR)); beforeEach(() => { origHome = process.env.HOME; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 21f15d95..572db67e 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -80,7 +80,6 @@ describe('verbose, per call', () => { fetchProtocolVersion: async () => 2001000n, fetchTip: async () => { throw new Error('node unreachable'); }, fetchUnshielded: async () => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }), - cacheDir: home, }); const verboseLines: string[] = []; const quietLines: string[] = []; diff --git a/src/__tests__/wallet-cache.test.ts b/src/__tests__/wallet-cache.test.ts index 6f4e2f46..a9793f47 100644 --- a/src/__tests__/wallet-cache.test.ts +++ b/src/__tests__/wallet-cache.test.ts @@ -22,19 +22,22 @@ function makeTmpDir(): string { } describe('wallet-cache', () => { + // The state root the functions are given, and the cache folder under it. + let root: string; let cacheDir: string; beforeEach(() => { - cacheDir = makeTmpDir(); + root = makeTmpDir(); + cacheDir = join(root, 'cache'); }); afterEach(() => { - rmSync(cacheDir, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); }); describe('getCachePath', () => { - it('returns path under cacheDir/network/prefix.json', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + it('returns path under the state root\'s cache/network/prefix.json', () => { + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); expect(path).toBe(join(cacheDir, TEST_NETWORK, `${TEST_ADDRESS.slice(0, 20)}.json`)); }); }); @@ -53,8 +56,8 @@ describe('wallet-cache', () => { dust: { serializeState: async () => walletData.dust }, }; - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, cacheDir); - const loaded = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, root); + const loaded = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(loaded).not.toBeNull(); expect(loaded!.shielded).toBe(walletData.shielded); @@ -69,10 +72,10 @@ describe('wallet-cache', () => { dust: { serializeState: async () => 'c' }, }; - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); expect(existsSync(path)).toBe(false); - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, cacheDir); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, root); expect(existsSync(path)).toBe(true); }); @@ -83,9 +86,9 @@ describe('wallet-cache', () => { dust: { serializeState: async () => 'dust-data' }, }; - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, cacheDir); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, root); - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); const raw = JSON.parse(readFileSync(path, 'utf-8')); expect(raw.version).toBe(CACHE_VERSION); expect(raw.network).toBe(TEST_NETWORK); @@ -96,21 +99,21 @@ describe('wallet-cache', () => { describe('loadWalletCache — error cases', () => { it('returns null when cache file does not exist', () => { - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); it('returns null when cache file is corrupted JSON', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); mkdirSync(join(cacheDir, TEST_NETWORK), { recursive: true }); writeFileSync(path, 'not valid json{{{'); - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); it('returns null when version mismatches', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); mkdirSync(join(cacheDir, TEST_NETWORK), { recursive: true }); writeFileSync(path, JSON.stringify({ version: CACHE_VERSION + 1, @@ -120,12 +123,12 @@ describe('wallet-cache', () => { wallets: { shielded: 'a', unshielded: 'b', dust: 'c' }, })); - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); it('returns null when network mismatches', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); mkdirSync(join(cacheDir, TEST_NETWORK), { recursive: true }); writeFileSync(path, JSON.stringify({ version: CACHE_VERSION, @@ -135,12 +138,12 @@ describe('wallet-cache', () => { wallets: { shielded: 'a', unshielded: 'b', dust: 'c' }, })); - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); it('returns null when address mismatches', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); mkdirSync(join(cacheDir, TEST_NETWORK), { recursive: true }); writeFileSync(path, JSON.stringify({ version: CACHE_VERSION, @@ -150,12 +153,12 @@ describe('wallet-cache', () => { wallets: { shielded: 'a', unshielded: 'b', dust: 'c' }, })); - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); it('returns null when wallets structure is missing fields', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); mkdirSync(join(cacheDir, TEST_NETWORK), { recursive: true }); writeFileSync(path, JSON.stringify({ version: CACHE_VERSION, @@ -165,12 +168,12 @@ describe('wallet-cache', () => { wallets: { shielded: 'a' }, })); - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); it('returns null when wallets field is null', () => { - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); mkdirSync(join(cacheDir, TEST_NETWORK), { recursive: true }); writeFileSync(path, JSON.stringify({ version: CACHE_VERSION, @@ -180,7 +183,7 @@ describe('wallet-cache', () => { wallets: null, })); - const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const result = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(result).toBeNull(); }); }); @@ -193,16 +196,16 @@ describe('wallet-cache', () => { dust: { serializeState: async () => 'c' }, }; - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, cacheDir); - const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, root); + const path = getCachePath(TEST_ADDRESS, TEST_NETWORK, root); expect(existsSync(path)).toBe(true); - clearWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + clearWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(existsSync(path)).toBe(false); }); it('does not throw when cache file does not exist', () => { - expect(() => clearWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir)).not.toThrow(); + expect(() => clearWalletCache(TEST_ADDRESS, TEST_NETWORK, root)).not.toThrow(); }); it('deletes all caches for a network', async () => { @@ -213,12 +216,12 @@ describe('wallet-cache', () => { }; const addr2 = 'mn_addr_preprod1other_address_here'; - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, cacheDir); - await saveWalletCache(addr2, TEST_NETWORK, fakeFacade, cacheDir); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, fakeFacade, root); + await saveWalletCache(addr2, TEST_NETWORK, fakeFacade, root); - clearWalletCache(undefined, TEST_NETWORK, cacheDir); - expect(existsSync(getCachePath(TEST_ADDRESS, TEST_NETWORK, cacheDir))).toBe(false); - expect(existsSync(getCachePath(addr2, TEST_NETWORK, cacheDir))).toBe(false); + clearWalletCache(undefined, TEST_NETWORK, root); + expect(existsSync(getCachePath(TEST_ADDRESS, TEST_NETWORK, root))).toBe(false); + expect(existsSync(getCachePath(addr2, TEST_NETWORK, root))).toBe(false); }); }); @@ -235,10 +238,10 @@ describe('wallet-cache', () => { dust: { serializeState: async () => 'new-dust' }, }; - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, facade1, cacheDir); - await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, facade2, cacheDir); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, facade1, root); + await saveWalletCache(TEST_ADDRESS, TEST_NETWORK, facade2, root); - const loaded = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, cacheDir); + const loaded = loadWalletCache(TEST_ADDRESS, TEST_NETWORK, root); expect(loaded!.shielded).toBe('new-shielded'); expect(loaded!.unshielded).toBe('new-unshielded'); expect(loaded!.dust).toBe('new-dust'); diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 630926af..4a223ce6 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -236,7 +236,7 @@ describe('a wallet written before stagenet', () => { const config = await loadWalletConfig(filePath); expect(config.addresses.stagenet).toBe(stagenetAddress); expect(JSON.parse(fs.readFileSync(filePath, 'utf-8')).addresses).toEqual(VALID_ADDRESSES); - expect(await walletAddress(filePath, 'stagenet')).toBe(stagenetAddress); + expect(await walletAddress(filePath, 'stagenet', stateRootIn(TEST_DIR))).toBe(stagenetAddress); }); it('keeps a sealed wallet as written until it is unlocked, then derives and saves its stagenet addresses beside the sealed secret', async () => { diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index 7046ae3e..b9b3b783 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -38,41 +38,41 @@ afterEach(() => { describe('createWallet', () => { it('writes a sealed wallet that unlocks to its new mnemonic, and makes it active', async () => { - const created = await createWallet('alice', walletSecretFrom(), PASSPHRASE); + const created = await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE); - expect(created.file).toBe(walletFilePath('alice')); + expect(created.file).toBe(walletFilePath(stateRootIn(home), 'alice')); expect(created.mnemonic!.split(' ')).toHaveLength(24); expect(fs.readFileSync(created.file, 'utf8')).not.toContain(created.seed.toString('hex')); - const unlocked = await unlockWallet(created.file); + const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) }); expect(unlocked.seed).toBe(created.seed.toString('hex')); expect(unlocked.mnemonic).toBe(created.mnemonic); - expect(getActiveWalletName()).toBe('alice'); + expect(getActiveWalletName(stateRootIn(home))).toBe('alice'); }); it('derives its addresses from a given mnemonic', async () => { - const created = await createWallet('bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE); + const created = await createWallet(stateRootIn(home), 'bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE); expect(created.addresses).toEqual(deriveAllAddresses(Buffer.from(mnemonicToSeedSync(MNEMONIC)))); }); it('keeps a given seed and no mnemonic', async () => { const seed = Buffer.alloc(32, 2); - const created = await createWallet('carol', walletSecretFrom({ seed }), PASSPHRASE); - const unlocked = await unlockWallet(created.file); + const created = await createWallet(stateRootIn(home), 'carol', walletSecretFrom({ seed }), PASSPHRASE); + const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) }); expect(unlocked.seed).toBe(seed.toString('hex')); expect(unlocked.mnemonic).toBeUndefined(); }); it('replaces an existing wallet only when asked', async () => { - const first = await createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE); - await expect(createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE)).rejects.toThrow(`Wallet file already exists: ${first.file}`); - expect((await unlockWallet(first.file)).seed).toBe(Buffer.alloc(32, 1).toString('hex')); + const first = await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE); + await expect(createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE)).rejects.toThrow(`Wallet file already exists: ${first.file}`); + expect((await unlockWallet(first.file, { root: stateRootIn(home) })).seed).toBe(Buffer.alloc(32, 1).toString('hex')); - await createWallet('alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, { overwrite: true }); - expect((await unlockWallet(first.file)).seed).toBe(Buffer.alloc(32, 2).toString('hex')); + await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, { overwrite: true }); + expect((await unlockWallet(first.file, { root: stateRootIn(home) })).seed).toBe(Buffer.alloc(32, 2).toString('hex')); }); it('refuses a name that is not a simple name, and an invalid mnemonic', () => { - expect(() => walletFilePath('../alice')).toThrow('Invalid wallet name: "../alice"'); + expect(() => walletFilePath(stateRootIn(home), '../alice')).toThrow('Invalid wallet name: "../alice"'); expect(() => walletSecretFrom({ mnemonic: 'not a real mnemonic' })).toThrow('Invalid BIP-39 mnemonic'); }); }); diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index a72dd092..51d5fbe8 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -1,7 +1,7 @@ // Boundary tests for WalletDataRepository. // Uses the four constructor seams (now, fetchTip, fetchUnshielded, fetchDust) // to exercise cache + tip + invalidation logic without touching the network, -// the SDK, or the proof server. cacheDir points at a per-test tmp directory. +// the SDK, or the proof server. Each read keeps its caches under a per-test tmp state root. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { mkdtempSync, rmSync, readFileSync, readdirSync } from 'node:fs'; @@ -76,10 +76,9 @@ describe('WalletDataRepository — ledger guard', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), fetchDust, - cacheDir: TMP, }); - await expect(repo.dust(SEED, NETWORK)).rejects.toBeInstanceOf(UnsupportedLedgerError); + await expect(repo.dust(SEED, NETWORK, { root: TMP })).rejects.toBeInstanceOf(UnsupportedLedgerError); expect(fetchDust).not.toHaveBeenCalled(); }); }); @@ -92,7 +91,6 @@ describe('WalletDataRepository — unshielded reads', () => { fetchTip: async () => { tipCalls++; return 'tip-A'; }, fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary({ utxoCount: 3 }); }, fetchDust: async () => fakeDustResult(), - cacheDir: TMP, }); const first = await repo.unshielded('addr-1', NETWORK); @@ -113,7 +111,6 @@ describe('WalletDataRepository — unshielded reads', () => { fetchTip: async () => tip, fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary({ utxoCount: fetchCalls }); }, fetchDust: async () => fakeDustResult(), - cacheDir: TMP, }); await repo.unshielded('addr-1', NETWORK); @@ -133,7 +130,6 @@ describe('WalletDataRepository — unshielded reads', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary(); }, fetchDust: async () => fakeDustResult(), - cacheDir: TMP, }); await repo.unshielded('addr-1', NETWORK); @@ -153,7 +149,6 @@ describe('WalletDataRepository — unshielded reads', () => { }, fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary({ utxoCount: 7 }); }, fetchDust: async () => fakeDustResult(), - cacheDir: TMP, }); // Prime the memo, then break the tip and step past the TTL. @@ -175,11 +170,10 @@ describe('WalletDataRepository — dust reads', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), fetchDust: async () => { fetchCalls++; return fakeDustResult(); }, - cacheDir: TMP, }); - await repo.dust(SEED, NETWORK); - const second = await repo.dust(SEED, NETWORK); + await repo.dust(SEED, NETWORK, { root: TMP }); + const second = await repo.dust(SEED, NETWORK, { root: TMP }); expect(second.fromCache).toBe(true); expect(fetchCalls).toBe(1); }); @@ -195,20 +189,19 @@ describe('WalletDataRepository — dust reads', () => { startIds.push(opts.startFromId); return fakeDustResult({ lastAppliedEventId: lastId, eventCount: lastId + 1 - opts.startFromId }); }, - cacheDir: TMP, }); // Before the reset: the cache reaches event 500. - await new WalletDataRepository(deps(null, [], 500)).dust(SEED, NETWORK); + await new WalletDataRepository(deps(null, [], 500)).dust(SEED, NETWORK, { root: TMP }); // After it: the chain's latest event is 106, so the cache can't be from this chain. const startIds: number[] = []; - const view = await new WalletDataRepository(deps(106, startIds, 106)).dust(SEED, NETWORK); + const view = await new WalletDataRepository(deps(106, startIds, 106)).dust(SEED, NETWORK, { root: TMP }); expect(startIds).toEqual([0]); expect(view.fromCache).toBe(false); - const files = readdirSync(join(TMP, 'undeployed')).filter((f) => f.startsWith('dust-')); + const files = readdirSync(join(TMP, 'cache', 'undeployed')).filter((f) => f.startsWith('dust-')); expect(files).toHaveLength(1); - expect(JSON.parse(readFileSync(join(TMP, 'undeployed', files[0]!), 'utf-8')).lastAppliedEventId).toBe(106); + expect(JSON.parse(readFileSync(join(TMP, 'cache', 'undeployed', files[0]!), 'utf-8')).lastAppliedEventId).toBe(106); }); it('resumes a Dust cache that is behind or at the chain\'s latest event', async () => { @@ -220,10 +213,9 @@ describe('WalletDataRepository — dust reads', () => { fetchChainId: async () => null, fetchEventTip: async () => eventTip, fetchDust: async (_seed, _net, opts) => { startIds.push(opts.startFromId); return fakeDustResult({ lastAppliedEventId: lastId }); }, - cacheDir: TMP, }); - await new WalletDataRepository(deps(null, 100)).dust(SEED, NETWORK); - await new WalletDataRepository(deps(150, 150)).dust(SEED, NETWORK); + await new WalletDataRepository(deps(null, 100)).dust(SEED, NETWORK, { root: TMP }); + await new WalletDataRepository(deps(150, 150)).dust(SEED, NETWORK, { root: TMP }); expect(startIds).toEqual([0, 101]); }); @@ -249,10 +241,9 @@ describe('WalletDataRepository — dust reads', () => { nextLastEventId += 250; return result; }, - cacheDir: TMP, }); - const view = await repo.dust(SEED, NETWORK); + const view = await repo.dust(SEED, NETWORK, { root: TMP }); expect(startIds).toEqual([0, 250, 500, 750]); // each call resumed from prior checkpoint expect(view.eventsApplied).toBe(1000); // sum across 4 calls expect(view.fromCache).toBe(false); // we started cold @@ -275,10 +266,9 @@ describe('WalletDataRepository — dust reads', () => { opts.onCheckpoint?.(result.state, result.lastAppliedEventId, result.retention); return result; }, - cacheDir: TMP, }); - const view = await repo.dust(SEED, NETWORK); + const view = await repo.dust(SEED, NETWORK, { root: TMP }); expect(calls).toBe(21); expect(view.partial).toBe(false); expect(view.eventsApplied).toBe(21 * 80_000); @@ -298,10 +288,9 @@ describe('WalletDataRepository — dust reads', () => { if (moved) opts.onCheckpoint?.(result.state, result.lastAppliedEventId, result.retention); return result; }, - cacheDir: TMP, }); - const view = await repo.dust(SEED, NETWORK); + const view = await repo.dust(SEED, NETWORK, { root: TMP }); expect(calls).toBe(4); expect(view.partial).toBe(true); expect(view.lastAppliedEventId).toBe(499); @@ -315,10 +304,9 @@ describe('WalletDataRepository — dust reads', () => { fetchTip: async () => { throw new Error('node unreachable'); }, fetchUnshielded: async () => fakeBalanceSummary(), fetchDust: async () => fakeDustResult({ lastAppliedEventId: 77, eventCount: 78 }), - cacheDir: TMP, }); - const view = await repo.dust(SEED, NETWORK); + const view = await repo.dust(SEED, NETWORK, { root: TMP }); expect(view.lastAppliedEventId).toBe(77); expect(view.partial).toBe(false); }); @@ -329,10 +317,9 @@ describe('WalletDataRepository — dust reads', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), fetchDust: async () => fakeDustResult({ lastAppliedEventId: 4242, eventCount: 4243, partial: false }), - cacheDir: TMP, }); - const view = await repo.dust(SEED, NETWORK); + const view = await repo.dust(SEED, NETWORK, { root: TMP }); expect(view.partial).toBe(false); expect(view.lastAppliedEventId).toBe(4242); }); @@ -362,10 +349,9 @@ describe('WalletDataRepository — dust reads', () => { nextLastEventId += 250; return result; }, - cacheDir: TMP, }); - const view = await repo.dust(SEED, NETWORK); + const view = await repo.dust(SEED, NETWORK, { root: TMP }); expect(view.partial).toBe(true); expect(calls).toBe(6); // it used its hour, and no more expect(view.lastAppliedEventId).toBe(nextLastEventId - 250); // the checkpoint it got to @@ -382,17 +368,16 @@ describe('WalletDataRepository — dust reads', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), fetchDust, - cacheDir: TMP, }); const cold = await new WalletDataRepository( deps(async () => fakeDustResult({ lastAppliedEventId: 900, eventCount: 901 })), - ).dust(SEED, NETWORK); + ).dust(SEED, NETWORK, { root: TMP }); expect(cold.lastAppliedEventId).toBe(900); const warm = await new WalletDataRepository( deps(async () => fakeDustResult({ lastAppliedEventId: -1, eventCount: 0 })), - ).dust(SEED, NETWORK); + ).dust(SEED, NETWORK, { root: TMP }); expect(warm.lastAppliedEventId).toBe(900); expect(warm.fromCache).toBe(true); }); @@ -409,12 +394,11 @@ describe('WalletDataRepository — dust reads', () => { lastStartFromId = opts.startFromId; return fakeDustResult(); }, - cacheDir: TMP, }); - await repo.dust(SEED, NETWORK); // 1st: starts at 0 + await repo.dust(SEED, NETWORK, { root: TMP }); // 1st: starts at 0 expect(lastStartFromId).toBe(0); - await repo.dust(SEED, NETWORK, { forceFresh: true }); // forceFresh: start back at 0, ignore disk + await repo.dust(SEED, NETWORK, { root: TMP, forceFresh: true }); // forceFresh: start back at 0, ignore disk expect(fetchCalls).toBe(2); expect(lastStartFromId).toBe(0); }); @@ -428,17 +412,16 @@ describe('WalletDataRepository — invalidation', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => { unshieldedCalls++; return fakeBalanceSummary(); }, fetchDust: async () => { dustCalls++; return fakeDustResult(); }, - cacheDir: TMP, }); - await repo.dust(SEED, NETWORK); + await repo.dust(SEED, NETWORK, { root: TMP }); await repo.unshielded(SEED, NETWORK); expect(dustCalls).toBe(1); expect(unshieldedCalls).toBe(1); - repo.invalidate({ network: NETWORK, seed: SEED }); + repo.invalidate({ network: NETWORK, root: TMP, seed: SEED }); - await repo.dust(SEED, NETWORK); + await repo.dust(SEED, NETWORK, { root: TMP }); await repo.unshielded(SEED, NETWORK); expect(dustCalls).toBe(2); expect(unshieldedCalls).toBe(2); @@ -451,15 +434,14 @@ describe('WalletDataRepository — invalidation', () => { fetchTip: async () => 'tip-A', fetchUnshielded: async () => { unshieldedCalls++; return fakeBalanceSummary(); }, fetchDust: async () => { dustCalls++; return fakeDustResult(); }, - cacheDir: TMP, }); - await repo.dust(SEED, NETWORK); + await repo.dust(SEED, NETWORK, { root: TMP }); await repo.unshielded(SEED, NETWORK); - repo.invalidate({ network: NETWORK, seed: SEED, kinds: ['dust'] }); + repo.invalidate({ network: NETWORK, root: TMP, seed: SEED, kinds: ['dust'] }); - const dustAgain = await repo.dust(SEED, NETWORK); + const dustAgain = await repo.dust(SEED, NETWORK, { root: TMP }); const unshieldedAgain = await repo.unshielded(SEED, NETWORK); // Network was hit again for dust (memo dropped), but the disk checkpoint // from the first call survived → fromCache is true (delta-resume counts). @@ -477,13 +459,14 @@ describe('WalletDataRepository — invalidation', () => { // the guard never wiped anything — a chain reset surfaced a stale balance from // the old chain's coins. These lock both halves via the fetchChainId seam. -/** Read the single dust-*.json cache file written under TMP, or null. */ +/** Read the single dust-*.json cache file written under TMP's cache folder, or null. */ function readDustCacheFile(): { chainId?: string; lastAppliedEventId?: number } | null { - for (const net of readdirSync(TMP)) { + const cacheDir = join(TMP, 'cache'); + for (const net of readdirSync(cacheDir)) { let files: string[] = []; - try { files = readdirSync(join(TMP, net)); } catch { continue; } + try { files = readdirSync(join(cacheDir, net)); } catch { continue; } const f = files.find((x) => x.startsWith('dust-') && x.endsWith('.json')); - if (f) return JSON.parse(readFileSync(join(TMP, net, f), 'utf-8')); + if (f) return JSON.parse(readFileSync(join(cacheDir, net, f), 'utf-8')); } return null; } @@ -495,16 +478,15 @@ describe('WalletDataRepository — dust cache chain-reset guard', () => { fetchUnshielded: async () => fakeBalanceSummary(), fetchDust, fetchChainId: async () => chainId, - cacheDir: TMP, }); it('persists the chain genesis hash into the dust cache on save', async () => { - await mkRepo('0xchainA', async () => fakeDustResult()).dust(SEED, NETWORK); + await mkRepo('0xchainA', async () => fakeDustResult()).dust(SEED, NETWORK, { root: TMP }); expect(readDustCacheFile()?.chainId).toBe('0xchainA'); }); it('wipes a cache from a different chain and re-syncs fresh from event 0', async () => { - await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK); + await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK, { root: TMP }); expect(readDustCacheFile()?.chainId).toBe('0xchainA'); // Chain reset: node now reports genesis hash B. A fresh repo must WIPE the @@ -513,7 +495,7 @@ describe('WalletDataRepository — dust cache chain-reset guard', () => { const view = await mkRepo('0xchainB', async (_s, _n, opts) => { startFromSeen = opts.startFromId; return fakeDustResult({ lastAppliedEventId: 2 }); - }).dust(SEED, NETWORK); + }).dust(SEED, NETWORK, { root: TMP }); expect(startFromSeen).toBe(0); // wiped → fresh, not resumed expect(view.fromCache).toBe(false); @@ -521,13 +503,13 @@ describe('WalletDataRepository — dust cache chain-reset guard', () => { }); it('resumes (does NOT wipe) when the genesis hash is unchanged', async () => { - await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK); + await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK, { root: TMP }); let startFromSeen = -999; const view = await mkRepo('0xchainA', async (_s, _n, opts) => { startFromSeen = opts.startFromId; return fakeDustResult({ lastAppliedEventId: 5 }); - }).dust(SEED, NETWORK); + }).dust(SEED, NETWORK, { root: TMP }); expect(startFromSeen).toBe(6); // resumed from lastAppliedEventId + 1 expect(view.fromCache).toBe(true); diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index ce76ab17..dd716cf1 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -1,8 +1,8 @@ // What a wallet with no saved state restores from: a new wallet's state on the // Dust checkpoint the direct reader holds, so the SDK doesn't replay the // chain's whole Dust history. `mn contract`'s served wallet once skipped this -// and timed out on stagenet, 226k of 395k Dust events in. A temporary cache -// folder. Live (`npm run test:live`): a new wallet reads the chain's protocol +// and timed out on stagenet, 226k of 395k Dust events in. A temporary state +// root. Live (`npm run test:live`): a new wallet reads the chain's protocol // version from undeployed's indexer (its saved endpoints or the defaults), and // a ledger-9 checkpoint only goes into a wallet on ledger 9. @@ -17,11 +17,12 @@ import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; +import { testHost } from './helpers/test-host.ts'; let NETWORK: NetworkConfig; beforeAll(async () => { - NETWORK = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']) }).config; + NETWORK = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }).config; const answered = await fetch(NETWORK.indexer, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: '{ block { protocolVersion } }' }), signal: AbortSignal.timeout(5_000) }) .then(async (r) => ((await r.json()) as { data?: { block?: { protocolVersion?: number } } }).data?.block?.protocolVersion ?? null, () => null); if (answered === null) throw new Error(`No indexer answers at ${NETWORK.indexer}: start the local chain (or point undeployed at one with midnight config set) before npm run test:live.`); @@ -29,16 +30,16 @@ beforeAll(async () => { }); const SEED = Buffer.from('11'.repeat(32), 'hex'); -let cacheDir: string; -beforeEach(() => { cacheDir = mkdtempSync(join(tmpdir(), 'mn-restore-state-')); }); -afterEach(() => { rmSync(cacheDir, { recursive: true, force: true }); }); +let root: string; +beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'mn-restore-state-')); }); +afterEach(() => { rmSync(root, { recursive: true, force: true }); }); describe('walletStateToRestore', () => { it('with no saved wallet, starts the Dust wallet at the checkpoint the direct reader holds', async () => { const checkpoint = ledger.DustLocalState.deserialize(Buffer.from(DUST_STATE_OWNED_HEX, 'hex')); - saveDustCache('undeployed', dustPublicKeyHexFromSeed(SEED), checkpoint, 395_185, cacheDir); + saveDustCache('undeployed', dustPublicKeyHexFromSeed(SEED), checkpoint, 395_185, root); - const state = await new WalletDataRepository({ cacheDir }).walletStateToRestore(SEED, NETWORK, 'undeployed'); + const state = await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root); expect(state, 'a wallet to restore, not one built from its keys').not.toBeNull(); const dust = JSON.parse(state!.dust) as { offset: string; state: string }; @@ -47,6 +48,6 @@ describe('walletStateToRestore', () => { }, 30_000); it('with no saved wallet and no checkpoint, is null: the wallet is built from its keys', async () => { - expect(await new WalletDataRepository({ cacheDir }).walletStateToRestore(SEED, NETWORK, 'undeployed')).toBeNull(); + expect(await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root)).toBeNull(); }); }); diff --git a/src/commands/address.ts b/src/commands/address.ts index 6ec24682..5da3bcbc 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -11,7 +11,8 @@ import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context' export default async function addressCommand(args: ParsedArgs, ctx: CallContext): Promise { // `address` is a seed-derivation tool with no active-wallet notion → requireExplicit. - const seedBuffer = await resolveSeed(args, { requireExplicit: true, label: 'address' }); + const root = ctx.config.paths.stateRoot; + const seedBuffer = await resolveSeed(args, root, { requireExplicit: true, label: 'address' }); const indexStr = getFlag(args, 'index'); const keyIndex = indexStr !== undefined ? parseInt(indexStr, 10) : 0; @@ -19,8 +20,8 @@ export default async function addressCommand(args: ParsedArgs, ctx: CallContext) throw new Error('Key index must be a non-negative integer'); } - const networkName = resolveNetworkName({ args }); - const address = (await engineFor(networkName)).keys.unshieldedAddress(seedBuffer, networkName, keyIndex); + const networkName = resolveNetworkName({ args, configDir: root }); + const address = (await engineFor(networkName, root)).keys.unshieldedAddress(seedBuffer, networkName, keyIndex); const derivationPath = `m/44'/2400'/0'/NightExternal/${keyIndex}`; // JSON mode diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 5eb8a14d..1a51d688 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -37,13 +37,14 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) } const amountNight = parseAmount(amountStr); - const { name: networkName, config: networkConfig } = resolveNetwork({ args }); + const root = ctx.config.paths.stateRoot; + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); if (networkName !== 'undeployed') { throw new Error( @@ -60,7 +61,7 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) const walletFlag = getFlag(args, 'wallet'); const isShielded = hasFlag(args, 'shielded') || (walletFlag !== undefined && walletFlag.startsWith('mn_shield-addr_')); - const destination = await resolveDestination(args, networkName, networkConfig, isShielded); + const destination = await resolveDestination(args, root, networkName, networkConfig, isShielded); if (isShielded) { return shieldedAirdrop(args, destination as ShieldedDestination, amountNight, networkName, networkConfig, ctx); @@ -88,6 +89,7 @@ function looksLikeBech32mAddress(value: string): boolean { async function resolveDestination( args: ParsedArgs, + root: string, networkName: NetworkName, networkConfig: NetworkConfig, isShielded: boolean, @@ -95,26 +97,27 @@ async function resolveDestination( const walletFlag = getFlag(args, 'wallet'); if (walletFlag !== undefined && looksLikeBech32mAddress(walletFlag)) { - return resolveAddressDestination(walletFlag, networkName, isShielded); + return resolveAddressDestination(walletFlag, root, networkName, isShielded); } // Fall back to wallet file (name, path, or active wallet) - const walletPath = resolveWalletPath(walletFlag); + const walletPath = resolveWalletPath(root, walletFlag); if (isShielded) { // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase // (unless the network was added after the wallet was written). - const stored = await walletShieldedAddress(walletPath, networkName); + const stored = await walletShieldedAddress(walletPath, networkName, root); if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${networkName}.`); - const decoded = await resolveAddressDestination(stored, networkName, true) as ShieldedDestination; + const decoded = await resolveAddressDestination(stored, root, networkName, true) as ShieldedDestination; return { kind: 'wallet', bech32m: decoded.bech32m, walletPath }; } - return { kind: 'address', address: await walletAddress(walletPath, networkName) }; + return { kind: 'address', address: await walletAddress(walletPath, networkName, root) }; } async function resolveAddressDestination( address: string, + root: string, networkName: NetworkName, isShielded: boolean, ): Promise { @@ -144,7 +147,7 @@ async function resolveAddressDestination( if (isShielded) { try { - (await engineFor(networkName)).keys.assertAddress(address, 'shielded', networkName); + (await engineFor(networkName, root)).keys.assertAddress(address, 'shielded', networkName); } catch (err: any) { throw new Error(`Invalid shielded address: ${err.message}`); } @@ -176,7 +179,8 @@ async function unshieldedAirdrop( const spinner = ctx.progress.start('Starting genesis wallet...'); try { - const result = await (await engineFor(networkName)).wallet.airdrop({ + const result = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.airdrop({ + root: ctx.config.paths.stateRoot, networkConfig, recipientAddress, amountNight, @@ -276,8 +280,9 @@ async function shieldedAirdrop( const spinner = ctx.progress.start('Syncing genesis wallet...'); try { - const txHash = await (await engineFor(networkName)).wallet.shieldedTransfer({ + const txHash = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.shieldedTransfer({ seed: genesisSeedBuffer, + root: ctx.config.paths.stateRoot, network: networkName, networkConfig, recipient: userShieldedAddrStr, diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 0dabf1a8..15a7f233 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -65,14 +65,15 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise args = { ...args, flags: { ...args.flags, network: inferredNetwork } }; } - const { name: networkName, config: networkConfig } = resolveNetwork({ args }); + const root = ctx.config.paths.stateRoot; + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); // Shielded balances are private: reading one needs the wallet's secret key, // which an address alone doesn't carry. If this address belongs to one of our // wallets we have the seed → run the full wallet sync (which shows shielded). // Otherwise there's nothing to decrypt with → fail with a clear, actionable error. if (hasFlag(args, 'shielded')) { - const owned = await findWalletByAddress(address); + const owned = await findWalletByAddress(root, address); if (owned) { ctx.diagnostics.line('balance', `shielded positional → wallet ${owned.wallet.name} on ${owned.network}`); const delegated: ParsedArgs = { @@ -93,12 +94,12 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); const spinner = ctx.progress.start(`Checking balance on ${networkName}...`); try { - const result = await (await engineFor(networkName)).wallet.unshieldedBalance(address, networkConfig, { + const result = await (await engineFor(networkName, root)).wallet.unshieldedBalance(address, networkConfig, { forceFresh: hasFlag(args, 'no-cache'), signal: ctx.signal, log: ctx.diagnostics.line, @@ -171,14 +172,15 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise // ── Wallet-based: full facade sync, both unshielded + shielded ── async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise { - const { name: networkName, config: networkConfig } = resolveNetwork({ args }); + const root = ctx.config.paths.stateRoot; + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); ctx.diagnostics.line('balance', `network=${networkName} indexerWS=${networkConfig.indexerWS}`); // Seed source: --seed → MN_SEED → --wallet → active wallet (shared resolver). - const { seed: seedBuffer, walletPath, config } = await resolveSeedSource(args); + const { seed: seedBuffer, walletPath, config } = await resolveSeedSource(args, root); ctx.diagnostics.line('balance', `wallet path=${walletPath ?? '(from --seed/MN_SEED)'}`); // Derive the unshielded address from the seed so a --seed/MN_SEED caller (no wallet // file) behaves identically to a named wallet — for a wallet this equals the stored one. - const engine = await engineFor(networkName); + const engine = await engineFor(networkName, root); const address = config?.addresses[networkName] ?? engine.keys.unshieldedAddress(seedBuffer, networkName); const shieldedAddrStr = config?.shieldedAddresses?.[networkName] ?? ''; @@ -186,7 +188,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); // Keep the SDK's transient errors and RPC noise off the terminal while this runs. const stopListening = ctx.sdkWarnings.listen(undefined); @@ -212,7 +214,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise // ── Phase 1: fast unshielded via GraphQL (no facade, no proof server) ── if (!isJson) activeSpinner = ctx.progress.start('Checking unshielded...'); ctx.diagnostics.line('balance', `phase=unshielded forceFresh=${noCache}`); - const unshieldedResult = await (await engineFor(networkName)).wallet.unshieldedBalance(address, networkConfig, { + const unshieldedResult = await (await engineFor(networkName, root)).wallet.unshieldedBalance(address, networkConfig, { forceFresh: noCache, signal: ctx.signal, log: ctx.diagnostics.line, @@ -273,6 +275,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise networkName, networkConfig.indexerWS, { + root, forceFresh: noCache, chainId, signal: ctx.signal, diff --git a/src/commands/cache.ts b/src/commands/cache.ts index 47ca6dc6..9b20a8c0 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -21,27 +21,28 @@ export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): ); } + const root = ctx.config.paths.stateRoot; const walletFlag = getFlag(args, 'wallet'); const networkFlag = getFlag(args, 'network'); const jsonMode = hasFlag(args, 'json'); if (walletFlag) { // Clear cache for a specific wallet - const walletPath = resolveWalletPath(walletFlag); - const config = await unlockWallet(walletPath); + const walletPath = resolveWalletPath(root, walletFlag); + const config = await unlockWallet(walletPath, { root }); // Cancelled while the wallet was unlocked: no cache is cleared. throwIfCancelled(ctx.signal); - const networkName = resolveNetworkName({ args }); + const networkName = resolveNetworkName({ args, configDir: root }); const address = config.addresses[networkName]; - clearWalletCache(address, networkName); + clearWalletCache(address, networkName, root); // Also clear the dust-direct cache for this wallet on this network. - const { keys } = await engineFor(networkName); + const { keys } = await engineFor(networkName, root); const dustPubkey = keys.dustPublicKeyHex(Buffer.from(config.seed, 'hex')); - clearDustDirectCache(networkName, dustPubkey); - clearNativeDustCheckpoint(networkName, dustPubkey); + clearDustDirectCache(networkName, dustPubkey, root); + clearNativeDustCheckpoint(networkName, dustPubkey, root); // And the shielded-direct cache (keyed by the wallet's coin public key). const shieldedPubkey = keys.shieldedCoinPublicKeyHex(Buffer.from(config.seed, 'hex')); - clearShieldedDirectCache(networkName, shieldedPubkey); + clearShieldedDirectCache(networkName, shieldedPubkey, root); if (jsonMode) { ctx.output.result({ action: 'clear', scope: 'wallet', wallet: walletFlag, network: networkName }); return; @@ -49,7 +50,7 @@ export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): ctx.output.stderr(green('✓') + ` Cache cleared for wallet "${walletFlag}" on ${networkName}\n`); } else if (networkFlag) { // Clear cache for a specific network - clearChainCaches(networkFlag); + clearChainCaches(networkFlag, root); if (jsonMode) { ctx.output.result({ action: 'clear', scope: 'network', network: networkFlag }); return; @@ -57,7 +58,7 @@ export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): ctx.output.stderr(green('✓') + ` Cache cleared for network "${networkFlag}"\n`); } else { // Clear all cache - clearChainCaches(undefined); + clearChainCaches(undefined, root); if (jsonMode) { ctx.output.result({ action: 'clear', scope: 'all' }); return; diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index 4b666e8d..d352ec39 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -5,10 +5,10 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTar /** The subcommands that reach a chain: inspect reads only the compiled contract (--path, --managed, --name). */ const ON_CHAIN: readonly string[] = ['deploy', 'call', 'state']; -/** The wallet a deploy or call pays from exists and can be read. */ -async function checkSendingWallet(params: Readonly>): Promise { +/** The wallet a deploy or call pays from, under the state root `root`, exists and can be read. */ +async function checkSendingWallet(params: Readonly>, root: string): Promise { const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); - await loadWalletConfig(resolveWalletPath(params.wallet as string | undefined)); + await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined)); } export const contractDefinition: CommandDefinition = { @@ -218,8 +218,9 @@ export const contractDefinition: CommandDefinition = { const { info } = resolveContractDeployRequest(args); const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); - await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy').network); - await checkSendingWallet(params); + const root = call.host.paths().stateRoot; + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy', root).network, root); + await checkSendingWallet(params, root); }, }, order: 26, @@ -252,8 +253,9 @@ export const contractDefinition: CommandDefinition = { const { info } = resolveContractCallRequest(args); const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); - await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call').network); - await checkSendingWallet(params); + const root = call.host.paths().stateRoot; + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call', root).network, root); + await checkSendingWallet(params, root); }, }, order: 27, diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 3ab6761d..026b849d 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -118,9 +118,9 @@ async function handleDeploy(args: ParsedArgs, payer: Payer, ctx: CallContext): P ctx.output.stderr('\n' + header('Contract Deploy') + '\n\n'); } - const target = resolvePayingTarget(args, 'contract', 'deploy'); + const target = resolvePayingTarget(args, 'contract', 'deploy', ctx.config.paths.stateRoot); const { network } = target; - await assertContractRunsOn(info, network); + await assertContractRunsOn(info, network, target.root); if (!jsonMode) { ctx.output.stderr(keyValue('Contract', info.name) + '\n'); @@ -192,9 +192,9 @@ async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Pro ctx.output.stderr('\n' + header('Contract Call') + '\n\n'); } - const target = resolvePayingTarget(args, 'contract', 'call'); + const target = resolvePayingTarget(args, 'contract', 'call', ctx.config.paths.stateRoot); const { network } = target; - await assertContractRunsOn(info, network); + await assertContractRunsOn(info, network, target.root); if (!jsonMode) { ctx.output.stderr(keyValue('Contract', info.name) + '\n'); @@ -238,7 +238,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { const { runState } = await import('../lib/contract/runner.ts'); - const { network, networkConfig } = resolvePayingTarget(args, 'contract', 'state'); + const { network, root, networkConfig } = resolvePayingTarget(args, 'contract', 'state', ctx.config.paths.stateRoot); if (!jsonMode) { ctx.output.stderr('\n' + header('Contract State') + '\n\n'); @@ -255,6 +255,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { const result = await runState({ dappDir, network, + root, networkConfig, managedDir: info.managedDir, contractName: info.name, @@ -298,7 +299,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { spinner.stop(yellow('⚠') + ' Parsed state unavailable, showing raw'); // The engine's query takes no signal: the call stops waiting for it when cancelled. - const raw = await untilCancelled((await engineFor(network)).contracts.rawState(networkConfig, address), ctx.signal); + const raw = await untilCancelled((await engineFor(network, root)).contracts.rawState(networkConfig, address), ctx.signal); if (!raw) { throw new Error(`No contract found at address ${address} on ${network}`); diff --git a/src/commands/dev.ts b/src/commands/dev.ts index cbf20949..f54cebe0 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -54,7 +54,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr // ── Phase 2: ensure localnet running ────────────────────── const localnetSpinner = ctx.progress.start('Checking localnet...'); try { - const result = await ensureLocalnetRunning((msg) => localnetSpinner.update(msg)); + const result = await ensureLocalnetRunning(ctx.config.paths.stateRoot, (msg) => localnetSpinner.update(msg)); const stateLabel = { 'already-running': 'Ledger-9 stack reachable', }[result.state]; @@ -68,6 +68,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr const walletSpinner = ctx.progress.start('Provisioning dev wallets...'); try { const provisioned = await provisionDevWallets({ + root: ctx.config.paths.stateRoot, names: DEFAULT_DEV_WALLET_NAMES, amountNight: DEFAULT_DEV_AIRDROP_AMOUNT, signal, @@ -154,7 +155,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr // Unlock mn's passphrase now, while stdin is still a plain terminal: once the // dispatcher reads keys in raw mode, a passphrase typed for [d]'s deploy would // be read as dev keystrokes too. Asked once per run; MN_PASSPHRASE asks nothing. - if (isPassphraseSet()) await unlockPassphrase(); + if (isPassphraseSet(ctx.config.paths.stateRoot)) await unlockPassphrase(ctx.config.paths.stateRoot); const abortController = new AbortController(); const stopRequest = () => { @@ -244,7 +245,7 @@ async function deployContract(project: ProjectInfo, ctx: CallContext): Promise config > network default applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); const isJson = hasFlag(args, 'json'); const minimal = isMinimalMode(args); @@ -49,7 +50,7 @@ export default async function dustCommand(args: ParsedArgs, ctx: CallContext): P // The chain-id check connects to the node; keep polkadot-js's RPC-CORE noise off stderr. const stopListening = ctx.sdkWarnings.listen(undefined); try { - await dustExport(await resolveSeed(args), networkName, networkConfig, isJson, minimal, ctx); + await dustExport(await resolveSeed(args, root), networkName, networkConfig, isJson, minimal, ctx); } finally { stopListening(); } @@ -57,7 +58,7 @@ export default async function dustCommand(args: ParsedArgs, ctx: CallContext): P } // status / register: named wallet + its stored address (used by the registration pre-check). - const config = await unlockWallet(resolveWalletPath(getFlag(args, 'wallet'))); + const config = await unlockWallet(resolveWalletPath(root, getFlag(args, 'wallet')), { root }); const seedBuffer = Buffer.from(config.seed, 'hex'); const address = config.addresses[networkName]; @@ -100,7 +101,8 @@ async function dustExport( ): Promise { const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); try { - const result = await (await engineFor(networkName)).wallet.exportDust(seedBuffer, networkName, networkConfig, { + const result = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.exportDust(seedBuffer, networkName, networkConfig, { + root: ctx.config.paths.stateRoot, signal: ctx.signal, log: ctx.diagnostics.line, onProgress: (applied, maxIdSeen) => spinner.update( @@ -258,7 +260,8 @@ async function dustRegister( const spinner = ctx.progress.start('Syncing wallet...'); try { - const result = await (await engineFor(network)).wallet.registerDust(seedBuffer, networkConfig, { + const result = await (await engineFor(network, ctx.config.paths.stateRoot)).wallet.registerDust(seedBuffer, networkConfig, { + root: ctx.config.paths.stateRoot, signal: ctx.signal, sdkWarnings: ctx.sdkWarnings, log: ctx.diagnostics.line, @@ -319,7 +322,8 @@ async function dustStatusDirect( const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); try { - const view = await (await engineFor(network)).wallet.dustBalance(seedBuffer, networkConfig, { + const view = await (await engineFor(network, ctx.config.paths.stateRoot)).wallet.dustBalance(seedBuffer, networkConfig, { + root: ctx.config.paths.stateRoot, forceFresh: !useCache, signal: ctx.signal, log: ctx.diagnostics.line, diff --git a/src/commands/generate.ts b/src/commands/generate.ts index 50b36a13..9f942011 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -20,7 +20,8 @@ import { getDefaultWalletPath } from '../lib/wallet-paths.ts'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function generateCommand(args: ParsedArgs, ctx: CallContext): Promise { - const networkName = resolveNetworkName({ args }); + const root = ctx.config.paths.stateRoot; + const networkName = resolveNetworkName({ args, configDir: root }); const outputPath = getFlag(args, 'output'); // Mutual exclusion: --seed and --mnemonic cannot both be specified. @@ -38,7 +39,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext // Overwrite protection: check if target file already exists const targetPath = outputPath ? path.resolve(outputPath) - : getDefaultWalletPath(); + : getDefaultWalletPath(root); if (fs.existsSync(targetPath) && !hasFlag(args, 'force')) { throw new Error( @@ -66,7 +67,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic)); } - const addresses = (await engineFor(networkName)).keys.unshieldedAddresses(seedBuffer); + const addresses = (await engineFor(networkName, root)).keys.unshieldedAddresses(seedBuffer); const activeAddress = addresses[networkName]; const config: WalletPublic = { @@ -75,7 +76,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext }; const secrets = mnemonic ? { seed: seedBuffer.toString('hex'), mnemonic } : { seed: seedBuffer.toString('hex') }; - const passphrase = await passphraseForNewSecret(undefined, { signal: ctx.signal }); + const passphrase = await passphraseForNewSecret(root, { signal: ctx.signal }); // Cancelled while the passphrase was asked for: no wallet is written, and no new passphrase saved. throwIfCancelled(ctx.signal); const savedPath = writeSealedWallet(targetPath, config, secrets, passphrase, { overwrite: hasFlag(args, 'force') }); diff --git a/src/commands/genesis-address.ts b/src/commands/genesis-address.ts index 4e53d89e..e1d36842 100644 --- a/src/commands/genesis-address.ts +++ b/src/commands/genesis-address.ts @@ -9,9 +9,10 @@ import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function genesisAddressCommand(args: ParsedArgs, ctx: CallContext): Promise { - const networkName = resolveNetworkName({ args }); + const root = ctx.config.paths.stateRoot; + const networkName = resolveNetworkName({ args, configDir: root }); const seedBuffer = Buffer.from(GENESIS_SEED, 'hex'); - const address = (await engineFor(networkName)).keys.unshieldedAddress(seedBuffer, networkName); + const address = (await engineFor(networkName, root)).keys.unshieldedAddress(seedBuffer, networkName); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index 89b6670a..66ed780a 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -5,9 +5,10 @@ import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmati /** A grant request can run: its arguments, the network, the account and the wallet are all in order. */ async function checkGrant(params: Readonly>, call: ToolCheckCall) { const { prepareGrant } = await import('../lib/grant/prepare.ts'); - const prepared = await prepareGrant(call.argv()); + const root = call.host.paths().stateRoot; + const prepared = await prepareGrant(call.argv(), root); const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); - await loadWalletConfig(resolveWalletPath(params.wallet as string | undefined)); + await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined)); return prepared; } diff --git a/src/commands/grant.ts b/src/commands/grant.ts index 0eaf1fef..b84b2d8a 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -52,7 +52,7 @@ function shortOfShieldedNight(held: bigint, value: bigint): UsageError { } export default async function grantCommand(args: ParsedArgs, ctx: CallContext): Promise { - const { request, target, walletName, recordsDir, account } = await prepareGrant(args); + const { request, target, walletName, recordsDir, account } = await prepareGrant(args, ctx.config.paths.stateRoot); const jsonMode = hasFlag(args, 'json'); const walletFlag = getFlag(args, 'wallet'); const spinnerFor = (label: string): Spinner => (jsonMode ? ctx.progress.silent() : ctx.progress.start(label)); @@ -94,7 +94,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, if (request.subcommand === 'device' && request.action === 'new') { const { createPendingDevice, openAccountKey, ownJoinCode } = await import('../lib/grant/sealed-account.ts'); const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('../lib/passphrase.ts'); - const passphrase = isPassphraseSet() ? await unlockPassphrase() : await passphraseForNewSecret(); + const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(target.root) : await passphraseForNewSecret(target.root); const device = createPendingDevice(recordsDir, passphrase); const code = ownJoinCode(recordsDir, openAccountKey(recordsDir, passphrase), device); spinner.stop('Device ready'); @@ -114,7 +114,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const { importAccount } = await import('../lib/grant/account-backup.ts'); const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('../lib/passphrase.ts'); try { - const passphrase = isPassphraseSet() ? await unlockPassphrase() : await passphraseForNewSecret(); + const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(target.root) : await passphraseForNewSecret(target.root); const { contractAddress } = await importAccount(recordsDir, target.network, passphrase, request.file); spinner.stop('Imported'); if (jsonMode) ctx.output.result({ subcommand: request.subcommand, network: target.network, wallet: walletName, ownerKey: 'sealed', address: contractAddress }); @@ -131,7 +131,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const owned: GrantAccount = await openGrantAccount(target.networkConfig, recordsDir, (line) => { spinner.update(line); throwIfCancelled(ctx.signal); - }); + }, { root: target.root }); // How the account's owner key and records are kept: sealed, or in plain text until `wallet protect`. const common = { subcommand: request.subcommand, network: target.network, wallet: walletName, ownerKey: owned.protection }; @@ -232,7 +232,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, if (owned.protection !== 'sealed') throw new UsageError('The account is not protected: its devices are managed once it is. Encrypt it first: midnight wallet protect'); const { openAccountKey, sealedDeviceList } = await import('../lib/grant/sealed-account.ts'); const { unlockPassphrase } = await import('../lib/passphrase.ts'); - const passphrase = await unlockPassphrase(); + const passphrase = await unlockPassphrase(target.root); const devices = sealedDeviceList(recordsDir, openAccountKey(recordsDir, passphrase)); if (owned.ownCode === undefined) throw new Error('A sealed account names its own device code'); const own = owned.ownCode(); @@ -281,7 +281,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, case 'export': { const { exportAccount } = await import('../lib/grant/account-backup.ts'); const { unlockPassphrase } = await import('../lib/passphrase.ts'); - const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(), request.file); + const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(target.root), request.file); spinner.stop('Written'); if (jsonMode) { ctx.output.result({ ...common, address: outcome.contractAddress, file: outcome.file }); diff --git a/src/commands/info.ts b/src/commands/info.ts index 5c0dc769..caefa90a 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -10,10 +10,11 @@ import { bold, dim, teal } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function infoCommand(args: ParsedArgs, ctx: CallContext): Promise { - const resolvedPath = resolveWalletPath(getFlag(args, 'wallet')); + const root = ctx.config.paths.stateRoot; + const resolvedPath = resolveWalletPath(root, getFlag(args, 'wallet')); const config = await loadWalletConfig(resolvedPath); - const activeNetwork = resolveNetworkName({ args }); - const activeAddress = await walletAddress(resolvedPath, activeNetwork); + const activeNetwork = resolveNetworkName({ args, configDir: root }); + const activeAddress = await walletAddress(resolvedPath, activeNetwork, root); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 24b5f88b..4a020392 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -20,11 +20,12 @@ const UNITS: Record = { }; export default async function inspectCostCommand(args: ParsedArgs, ctx: CallContext): Promise { - const { name: networkName, config } = resolveNetwork({ args }); + const root = ctx.config.paths.stateRoot; + const { name: networkName, config } = resolveNetwork({ args, configDir: root }); // A ledger-8 chain's parameters aren't ledger-9 ones: refuse it like every other chain read. await assertLedgerSupported(networkName, config, fetchProtocolVersion, ctx.signal); const { height, parametersHex } = await fetchLedgerParameters(config.indexer, ctx.signal); - const limits = (await engineFor(networkName)).ledger.blockLimits(parametersHex); + const limits = (await engineFor(networkName, root)).ledger.blockLimits(parametersHex); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index 3e892dbe..81e3b827 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -44,9 +44,9 @@ function formatServiceTable(services: readonly ServiceStatus[]): string { } async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall): Promise { - const wrote = ensureComposeFile(); + const wrote = ensureComposeFile(docker.root); if (wrote) { - ctx.output.stderr(dim(` Wrote compose.yml to ${getComposePath()}`) + '\n'); + ctx.output.stderr(dim(` Wrote compose.yml to ${getComposePath(docker.root)}`) + '\n'); } const spinner = ctx.progress.start('Starting local network...'); @@ -79,7 +79,7 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) await waitForFirstBlock(netCfg.node, { timeoutMs: 30_000, signal: ctx.signal }); spinner.update('Waiting for indexer to ingest genesis state...'); - const genesisAddress = (await engineFor('undeployed')).keys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const genesisAddress = (await engineFor('undeployed', docker.root)).keys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); await waitForAddressFunded(netCfg.indexerWS, genesisAddress, { timeoutMs: 30_000, signal: ctx.signal }); spinner.update('Waiting for proof server...'); @@ -166,7 +166,7 @@ async function handleDown(jsonMode: boolean, ctx: CallContext, docker: DockerCal // and would trigger "applied > highest" on the next command. Clearing // here means the next `mn ` starts with a truthful cache. const { clearChainCaches } = await import('../lib/chain-caches.ts'); - clearChainCaches('undeployed'); + clearChainCaches('undeployed', docker.root); // Also wipe the dapp-local LevelDB private-state store if the user is // running this from a dapp directory. The store survives `docker compose @@ -248,7 +248,7 @@ async function handleClean(jsonMode: boolean, ctx: CallContext, docker: DockerCa } async function handleLogs(args: ParsedArgs, ctx: CallContext, docker: DockerCall): Promise { - const composePath = getComposePath(); + const composePath = getComposePath(docker.root); const tail = getFlag(args, 'tail'); const jsonMode = hasFlag(args, 'json'); @@ -322,7 +322,7 @@ export async function runLocalnet(args: ParsedArgs, ctx: CallContext, exec: Exec if (subcommand === 'up') assertLocalnetCanStart(); // Docker runs as a step of this call: its stderr goes where the call's text goes, and the call's cancellation kills it. - const docker: DockerCall = { signal: ctx.signal, exec, onStderr: (text) => ctx.output.stderr(text) }; + const docker: DockerCall = { signal: ctx.signal, exec, onStderr: (text) => ctx.output.stderr(text), root: ctx.config.paths.stateRoot }; // Check Docker is available before any operation await checkDockerAvailable(docker); diff --git a/src/commands/serve.ts b/src/commands/serve.ts index a71f3b39..6cf1505d 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -51,10 +51,11 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // ── Load wallet ── - const config = await unlockWallet(resolveWalletPath(getFlag(args, 'wallet'))); + const root = ctx.config.paths.stateRoot; + const config = await unlockWallet(resolveWalletPath(root, getFlag(args, 'wallet')), { root }); const seedBuffer = Buffer.from(config.seed, 'hex'); - const { name: networkName, config: networkConfig } = resolveNetwork({ args }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); const address = config.addresses[networkName]; // Apply endpoint overrides: --flag > config > network default @@ -62,7 +63,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); // ── Header ── @@ -100,7 +101,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // preview/preprod). dApps there can only do unshielded + dust anyway. const syncMode = shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded')) ? 'full' : 'lite'; - await (await engineFor(networkName)).wallet.serveWallet({ seed: seedBuffer, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, + await (await engineFor(networkName, root)).wallet.serveWallet({ seed: seedBuffer, root, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, onStatus: (s) => spinner.update(s), onSyncProgress: (applied, highest) => { if (highest > 0) { diff --git a/src/commands/swap.definition.ts b/src/commands/swap.definition.ts index 66690b96..034624c2 100644 --- a/src/commands/swap.definition.ts +++ b/src/commands/swap.definition.ts @@ -10,7 +10,7 @@ function describeTerms(params: Readonly>): string { /** A take can run: the offer file is one, for this network, with the agreed terms, not expired. */ async function checkTake(call: ToolCheckCall) { const { prepareTake } = await import('../lib/swap/request.ts'); - return prepareTake(call.argv(), new Date()); + return prepareTake(call.argv(), call.host.paths().stateRoot, new Date()); } export const swapDefinition: CommandDefinition = { @@ -167,7 +167,7 @@ export const swapDefinition: CommandDefinition = { }, async check(_params, call) { const { prepareMake } = await import('../lib/swap/request.ts'); - prepareMake(call.argv(), new Date()); + prepareMake(call.argv(), call.host.paths().stateRoot, new Date()); }, }, order: 40, diff --git a/src/commands/swap.ts b/src/commands/swap.ts index 0e37679e..5d8e0924 100644 --- a/src/commands/swap.ts +++ b/src/commands/swap.ts @@ -29,11 +29,12 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P const jsonMode = hasFlag(args, 'json'); const spinnerFor = (label: string): Spinner => (jsonMode ? ctx.progress.silent() : ctx.progress.start(label)); const walletFlag = getFlag(args, 'wallet'); + const root = ctx.config.paths.stateRoot; const now = new Date(); switch (args.subcommand) { case 'make': { - const { target, terms, expiresAt, out } = prepareMake(args, now); + const { target, terms, expiresAt, out } = prepareMake(args, root, now); if (out !== undefined && existsSync(out)) throw new UsageError(`${out} already exists; an offer file is never written over another`); if (!jsonMode) { ctx.output.stderr('\n' + header('Swap: make an offer') + '\n\n'); @@ -41,11 +42,11 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P ctx.output.stderr(keyValue('Gives', legText(terms.give)) + '\n'); ctx.output.stderr(keyValue('Wants', legText(terms.want)) + '\n\n'); } - const address = await walletAddress(resolveWalletPath(walletFlag), target.network); + const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root); const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Making the offer (proving its half)...'); - const made = await makeOffer(session, address, terms, expiresAt, now); + const made = await makeOffer(session, root, address, terms, expiresAt, now); const file = out ?? `offer-${made.envelope.id.slice(0, 16)}.json`; writeFileSync(file, made.file, { flag: 'wx' }); spinner.stop('Offer made'); @@ -65,7 +66,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P } case 'inspect': { - const target = resolvePayingTarget(args, 'swap', 'inspect'); + const target = resolvePayingTarget(args, 'swap', 'inspect', root); const offer = await readOfferArg(args, target); const spinner = spinnerFor('Asking the indexer whether it is still live...'); const { expired, spends } = await standingOf(offer, target.networkConfig, now, ctx.signal); @@ -86,7 +87,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P } case 'take': { - const { target, offer, agreed } = await prepareTake(args, now); + const { target, offer, agreed } = await prepareTake(args, root, now); if (!jsonMode) { ctx.output.stderr('\n' + header('Swap: take an offer') + '\n\n'); ctx.output.stderr(keyValue('Offer', offer.envelope.id) + '\n'); @@ -116,12 +117,12 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P case 'cancel': { const id = args.positionals[0]; if (id === undefined) throw new UsageError('swap cancel needs the offer\'s id (8 characters of it at least): midnight swap cancel '); - const target = resolvePayingTarget(args, 'swap', 'cancel'); - const address = await walletAddress(resolveWalletPath(walletFlag), target.network); + const target = resolvePayingTarget(args, 'swap', 'cancel', root); + const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root); const session = await payerFor('swap cancel', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Spending the offer\'s coins back to this wallet...'); - const outcome = await cancelOffer(session, target.networkConfig, address, id, ctx.signal); + const outcome = await cancelOffer(session, root, target.networkConfig, address, id, ctx.signal); if (outcome.txHash !== undefined) spinner.update('Waiting for the indexer to list it...'); const receipt = outcome.txHash === undefined ? undefined : await receiptOf(target.networkConfig.indexer, outcome.txHash, ctx.signal); spinner.stop(outcome.txHash === undefined ? 'It was taken already' : 'Offer cancelled'); @@ -142,10 +143,10 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P } case 'list': { - const target = resolvePayingTarget(args, 'swap', 'list'); - const address = await walletAddress(resolveWalletPath(walletFlag), target.network); + const target = resolvePayingTarget(args, 'swap', 'list', root); + const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root); const spinner = spinnerFor('Asking the indexer about each open offer...'); - const listed = await listOffers(target.network, target.networkConfig, address, now, ctx.signal); + const listed = await listOffers(root, target.network, target.networkConfig, address, now, ctx.signal); spinner.stop(`${listed.length} offer${listed.length === 1 ? '' : 's'}`); if (jsonMode) { ctx.output.result({ diff --git a/src/commands/test.ts b/src/commands/test.ts index 02bfe371..108a87b5 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -446,7 +446,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): } // Prep context for resource tracking + teardown - const prep = createPrepContext(ctx.sdkWarnings, signal); + const prep = createPrepContext(ctx.config.paths.stateRoot, ctx.sdkWarnings, signal); const prepResults: PrepStepResult[] = []; // Register teardown on abort @@ -512,6 +512,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): prompt, dappDir, logFile: testLogFile, + home: ctx.config.paths.home, onOutput: (chunk) => writeTestOutput(testOutput.write(chunk)), terminal: 'inherit', onMessage: (msg) => { @@ -548,6 +549,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: 'run', positionals: [], flags: { network } }, + configDir: ctx.config.paths.stateRoot, }); // mn serve should already be started by the prep step (mn-serve) @@ -559,6 +561,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): let currentAction: import('../lib/test/types.ts').TestAction | undefined; const actionResults = await runActions({ + root: ctx.config.paths.stateRoot, actions: actionsConfig.actions, config, dappDir, diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 84300fc3..1558fd69 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -112,7 +112,7 @@ export const transferDefinition: CommandDefinition = { }, async check(_params, call) { const { resolveTransferRequest } = await import('../lib/transfer-request.ts'); - await resolveTransferRequest(call.argv()); + await resolveTransferRequest(call.argv(), call.host.paths().stateRoot); }, }, order: 12, diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 3a4165a5..c2a48c9c 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -17,7 +17,7 @@ import { receiptText } from '../ui/receipt.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); - const request = await resolveTransferRequest(args); + const request = await resolveTransferRequest(args, ctx.config.paths.stateRoot); return request.shielded ? shieldedTransfer(args, request, ctx) : unshieldedTransfer(args, request, ctx); } @@ -28,16 +28,17 @@ async function unshieldedTransfer( { walletPath, walletConfig: config, recipientAddress, amountNight }: TransferRequest, ctx: CallContext, ): Promise { - const seedBuffer = Buffer.from((await unlockWallet(walletPath)).seed, 'hex'); + const root = ctx.config.paths.stateRoot; + const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root })).seed, 'hex'); - const { name: networkName, config: networkConfig } = resolveNetwork({ args }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); const address = config.addresses[networkName]; applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); ctx.output.stderr('\n' + header('Transfer') + '\n\n'); ctx.output.stderr(keyValue('Network', networkName) + '\n'); @@ -49,7 +50,8 @@ async function unshieldedTransfer( const spinner = ctx.progress.start('Starting wallet...'); try { - const result = await (await engineFor(networkName)).wallet.transfer({ + const result = await (await engineFor(networkName, root)).wallet.transfer({ + root, seedBuffer, networkConfig, recipientAddress, @@ -124,15 +126,16 @@ async function shieldedTransfer( ctx: CallContext, ): Promise { const amount = nightToMicro(amountNight); - const seedBuffer = Buffer.from((await unlockWallet(walletPath)).seed, 'hex'); + const root = ctx.config.paths.stateRoot; + const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root })).seed, 'hex'); - const { name: networkName, config: networkConfig } = resolveNetwork({ args }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), node: getFlag(args, 'node'), indexerWS: getFlag(args, 'indexer-ws'), - }, networkName); + }, networkName, root); ctx.output.stderr('\n' + header('Shielded Transfer') + '\n\n'); ctx.output.stderr(keyValue('Network', networkName) + '\n'); @@ -146,8 +149,9 @@ async function shieldedTransfer( const spinner = ctx.progress.start('Syncing wallet...'); try { - const txHash = await (await engineFor(networkName)).wallet.shieldedTransfer({ + const txHash = await (await engineFor(networkName, root)).wallet.shieldedTransfer({ seed: seedBuffer, + root, network: networkName, networkConfig, recipient: recipientAddress, diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 00fe382a..1a92d382 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -132,11 +132,11 @@ export const walletDefinition: CommandDefinition = { // Replacing a wallet deletes its seed, so a call with force is confirmed like remove. confirmation: { when: (params) => params.force === true, - async check(params) { + async check(params, call) { const fs = await import('node:fs'); const { walletFilePath } = await import('../lib/wallet-create.ts'); const name = String(params.name); - return fs.existsSync(walletFilePath(name)) + return fs.existsSync(walletFilePath(call.host.paths().stateRoot, name)) ? `Replace wallet ${name}: its file, and the seed in it, is deleted from this machine and a new wallet written in its place` : `Create wallet ${name} (no wallet of that name exists, so nothing is replaced)`; }, @@ -196,9 +196,9 @@ export const walletDefinition: CommandDefinition = { confirmation: { describe: (params) => `Remove wallet ${params.name}: its file, and the seed in it, is deleted from this machine`, // A wallet that can't be removed is refused before the agent asks the user. - async check(params) { + async check(params, call) { const { assertWalletRemovable } = await import('../lib/wallet-config.ts'); - assertWalletRemovable(String(params.name)); + assertWalletRemovable(call.host.paths().stateRoot, String(params.name)); }, }, order: 5, diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index 6068a067..0bf49146 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -25,7 +25,6 @@ import { coinKeyOfWallet, type ProtectorResult, type WalletCommandContext } from import { header, keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, yellow, dim, green, teal } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; export default async function walletCommand(args: ParsedArgs, ctx: WalletCommandContext): Promise { const subcommand = args.subcommand; @@ -64,9 +63,10 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise ); } - const targetPath = walletFilePath(name); + const root = ctx.config.paths.stateRoot; + const targetPath = walletFilePath(root, name); - const networkName = resolveNetworkName({ args }); + const networkName = resolveNetworkName({ args, configDir: root }); const seedHex = getFlag(args, 'seed'); const mnemonicStr = getFlag(args, 'mnemonic'); @@ -83,11 +83,11 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise const secret = walletSecretFrom(seedHex !== undefined ? { seed: parseSeedHex(seedHex, '--seed') } : { mnemonic: mnemonicStr }); - const passphrase = await passphraseForNewSecret(undefined, { signal: ctx.signal }); + const passphrase = await passphraseForNewSecret(root, { signal: ctx.signal }); // Cancelled while the passphrase was asked for: no wallet is written, and no new passphrase saved. throwIfCancelled(ctx.signal); // Checked above: an existing wallet is replaced only with --force. - const created = await createWallet(name, secret, passphrase, { overwrite: hasFlag(args, 'force') }); + const created = await createWallet(root, name, secret, passphrase, { overwrite: hasFlag(args, 'force') }); const { addresses, shieldedAddresses, mnemonic, file: savedPath } = created; const seedBuffer = created.seed; const activeAddress = addresses[networkName]; @@ -140,8 +140,9 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise } async function walletList(args: ParsedArgs, ctx: CallContext): Promise { - const wallets = await listWallets(); - const networkName = resolveNetworkName({ args }); + const root = ctx.config.paths.stateRoot; + const wallets = await listWallets(root); + const networkName = resolveNetworkName({ args, configDir: root }); if (hasFlag(args, 'json')) { // Agent-slim shape: per-wallet { name, active, network, address, @@ -220,7 +221,7 @@ async function walletUse(args: ParsedArgs, ctx: CallContext): Promise { ); } - setActiveWallet(name); + setActiveWallet(ctx.config.paths.stateRoot, name); if (hasFlag(args, 'json')) { ctx.output.result({ wallet: name, active: true }); @@ -233,12 +234,13 @@ async function walletUse(args: ParsedArgs, ctx: CallContext): Promise { async function walletInfo(args: ParsedArgs, ctx: CallContext): Promise { // Accept both `wallet info ` (positional) and `wallet info --wallet ` // (flag, consistent with balance/dust/transfer); fall back to the active wallet. - const name = getFlag(args, 'wallet') ?? args.positionals[0] ?? getActiveWalletName(); - const walletPath = resolveWalletPath(name); + const root = ctx.config.paths.stateRoot; + const name = getFlag(args, 'wallet') ?? args.positionals[0] ?? getActiveWalletName(root); + const walletPath = resolveWalletPath(root, name); const config = await loadWalletConfig(walletPath); - const isActive = name === getActiveWalletName(); - const networkName = resolveNetworkName({ args }); - const activeAddress = await walletAddress(walletPath, networkName); + const isActive = name === getActiveWalletName(root); + const networkName = resolveNetworkName({ args, configDir: root }); + const activeAddress = await walletAddress(walletPath, networkName, root); if (hasFlag(args, 'json')) { // Agent-slim shape: drops the per-network addresses map (3× repetition @@ -308,7 +310,7 @@ async function walletRemove(args: ParsedArgs, ctx: CallContext): Promise { ); } - removeWallet(name); + removeWallet(ctx.config.paths.stateRoot, name); if (hasFlag(args, 'json')) { ctx.output.result({ wallet: name, removed: true }); @@ -320,11 +322,12 @@ async function walletRemove(args: ParsedArgs, ctx: CallContext): Promise { async function walletSeed(args: ParsedArgs, ctx: CallContext): Promise { // Accept both `wallet seed ` and `wallet seed --wallet `. - const name = getFlag(args, 'wallet') ?? args.positionals[0] ?? getActiveWalletName(); - const walletPath = resolveWalletPath(name); + const root = ctx.config.paths.stateRoot; + const name = getFlag(args, 'wallet') ?? args.positionals[0] ?? getActiveWalletName(root); + const walletPath = resolveWalletPath(root, name); // The seed and mnemonic, opened with mn's passphrase. - const raw = await unlockWallet(walletPath); + const raw = await unlockWallet(walletPath, { root }); // `--entropy` adds the 32-byte BIP-39 entropy (derived from the mnemonic) // alongside the 64-byte PBKDF2 seed. They're DIFFERENT values that produce @@ -387,7 +390,7 @@ async function walletSeed(args: ParsedArgs, ctx: CallContext): Promise { /** Sets mn's passphrase where none is set, and seals every plain-text wallet under it. */ async function walletProtect(args: ParsedArgs, ctx: WalletCommandContext): Promise { - const root = stateRoot(); + const root = ctx.config.paths.stateRoot; const passphrase = await passphraseForNewSecret(root, { signal: ctx.signal }); // Cancelled, it stops between wallets and before a protector, never in the middle of a file. const report = await protectAllWallets(root, passphrase, ctx.signal); @@ -397,7 +400,7 @@ async function walletProtect(args: ParsedArgs, ctx: WalletCommandContext): Promi const results: Array<{ name: string; result: ProtectorResult }> = []; for (const protector of ctx.protectors ?? []) { throwIfCancelled(ctx.signal); - results.push({ name: protector.name, result: await protector.protect(root, passphrase, coinKeyOfWallet) }); + results.push({ name: protector.name, result: await protector.protect(root, passphrase, (wallet) => coinKeyOfWallet(root, wallet)) }); } if (hasFlag(args, 'json')) { ctx.output.result({ sealed, alreadySealed, ...Object.fromEntries(results.map(({ name, result }) => [name, result.report])) }); diff --git a/src/lib/chain-caches.ts b/src/lib/chain-caches.ts index ab111ead..3e1fe8af 100644 --- a/src/lib/chain-caches.ts +++ b/src/lib/chain-caches.ts @@ -9,13 +9,13 @@ import { clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reade import { clearNativeDustCheckpoint } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; /** - * Clears every wallet cache kept for `network` (all networks when undefined): - * the wallet sync caches, the direct Dust and shielded caches, and the native - * sidecar's Dust checkpoints. + * Clears every wallet cache kept for `network` (all networks when undefined) + * under the state root `root`: the wallet sync caches, the direct Dust and + * shielded caches, and the native sidecar's Dust checkpoints. */ -export function clearChainCaches(network: string | undefined, cacheDir?: string): void { - clearWalletCache(undefined, network, cacheDir); - clearDustDirectCache(network, undefined, cacheDir); - clearShieldedDirectCache(network, undefined, cacheDir); - clearNativeDustCheckpoint(network, undefined, cacheDir); +export function clearChainCaches(network: string | undefined, root: string): void { + clearWalletCache(undefined, network, root); + clearDustDirectCache(network, undefined, root); + clearShieldedDirectCache(network, undefined, root); + clearNativeDustCheckpoint(network, undefined, root); } diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 75aafcdb..5de35267 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -14,7 +14,6 @@ import { join } from 'node:path'; import { installSdkNoiseFilters } from './sdk-noise.ts'; import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { setPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -36,7 +35,6 @@ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host }); setNoticeSink(host.notice); setSettingsSource(host.settings); - setHostPathsSource(host.paths); setPrompter(host.prompter); setEngineLoader(loadInstalledEngine); return host; diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index 8a21f2be..3d47e34a 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -36,6 +36,7 @@ export async function callContract({ request, target, wallet, payer, progress, s const result = await runCall({ dappDir, network: target.network, + root: target.root, networkConfig: target.networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index b8453715..975ee365 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -34,6 +34,7 @@ export async function deployContract({ request, target, wallet, payer, progress, const result = await runDeploy({ dappDir, network: target.network, + root: target.root, networkConfig: target.networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index e932f0b9..de882468 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -33,6 +33,8 @@ export interface RunnerOptions { dappDir: string; /** The network: its engine writes the script. */ network: NetworkName; + /** The state root whose config names the network's SDK set. */ + root: string; networkConfig: NetworkConfig; managedDir: string; contractName: string; @@ -71,6 +73,8 @@ export interface StateOptions { dappDir: string; /** The network: its engine writes the script. */ network: NetworkName; + /** The state root whose config names the network's SDK set. */ + root: string; networkConfig: NetworkConfig; managedDir: string; contractName: string; @@ -111,8 +115,8 @@ export function indexerEnvironment(networkConfig: NetworkConfig): Record { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); - await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); - const engine = await engineFor(options.network); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root); + const engine = await engineFor(options.network, options.root); const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.state(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); @@ -126,8 +130,8 @@ export async function runState(options: StateOptions): Promise { export async function runDeploy(options: DeployOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); - await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); - const engine = await engineFor(options.network); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root); + const engine = await engineFor(options.network, options.root); const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.deploy(options, SCRIPT_PARTS); // The private-state secret goes to the subprocess via env (never the on-disk @@ -147,8 +151,8 @@ export async function runDeploy(options: DeployOptions): Promise { export async function runCall(options: CallOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); - await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network); - const engine = await engineFor(options.network); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root); + const engine = await engineFor(options.network, options.root); const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.call(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); diff --git a/src/lib/contract/runtime-check.ts b/src/lib/contract/runtime-check.ts index e3730876..245ce44e 100644 --- a/src/lib/contract/runtime-check.ts +++ b/src/lib/contract/runtime-check.ts @@ -9,14 +9,15 @@ import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import type { ContractInfo } from './inspect.ts'; /** - * Throws a UsageError unless the engine for `network` runs a contract + * Throws a UsageError unless the engine for `network` (by the config under + * the state root `root`) runs a contract * compiled for `info.runtimeVersion`. A contract from a compiler that records * no runtime version is let through: its own code checks the runtime when it * loads. */ -export async function assertContractRunsOn(info: Pick, network: NetworkName): Promise { +export async function assertContractRunsOn(info: Pick, network: NetworkName, root: string): Promise { if (info.runtimeVersion === 'unknown') return; - const { scripts } = (await engineFor(network)).contracts; + const { scripts } = (await engineFor(network, root)).contracts; if (scripts.acceptsRuntime(info.runtimeVersion)) return; throw new UsageError( `${info.name} was compiled by compactc ${info.compilerVersion} for compact-runtime ${info.runtimeVersion}, ` + diff --git a/src/lib/dev/deploy.ts b/src/lib/dev/deploy.ts index 92be928a..649b5bcd 100644 --- a/src/lib/dev/deploy.ts +++ b/src/lib/dev/deploy.ts @@ -10,7 +10,7 @@ import { resolvePayingTarget, type Payer } from '@kuiralabs/midnight-cli-core/li import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -export async function deployDevContract(projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { +export async function deployDevContract(root: string, projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { // The deploy as `mn contract deploy --path --wallet --network ` reads it. const args: ParsedArgs = { command: 'contract', @@ -20,7 +20,7 @@ export async function deployDevContract(projectRoot: string, wallet: string, net }; return deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy'), + target: resolvePayingTarget(args, 'contract', 'deploy', root), wallet, payer, progress: () => progress, diff --git a/src/lib/dev/localnet-ready.ts b/src/lib/dev/localnet-ready.ts index c013f98c..3f53bbb6 100644 --- a/src/lib/dev/localnet-ready.ts +++ b/src/lib/dev/localnet-ready.ts @@ -12,10 +12,11 @@ export interface EnsureLocalnetResult { state: LocalnetState; } -/** Require a running ledger-9 stack; throws with setup instructions if none answers. */ -export async function ensureLocalnetRunning(onProgress?: (msg: string) => void): Promise { +/** Require a running ledger-9 stack, at the endpoints saved under the state root `root`; throws with setup instructions if none answers. */ +export async function ensureLocalnetRunning(root: string, onProgress?: (msg: string) => void): Promise { const { name, config } = resolveNetwork({ args: { command: 'dev', subcommand: undefined, positionals: [], flags: { network: 'undeployed' } }, + configDir: root, }); onProgress?.(`Checking the ledger-9 stack at ${config.node}`); await assertLedger9StackReachable(name, config); diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 58aefe53..4c8311d7 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -37,6 +37,8 @@ export interface ProvisionSteps { } interface ProvisionRun { + /** The state root the wallets and config live under. */ + root: string; names: readonly string[]; amountNight: number; onProgress?: (wallet: string, phase: 'creating' | 'funding' | 'dust' | 'done', state: WalletProvisionState) => void; @@ -47,12 +49,12 @@ interface ProvisionRun { export type ProvisionOptions = ProvisionRun & ({ steps: ProvisionSteps } | { sdkWarnings: CallSdkWarnings }); /** The steps through the wallet functions, on `network` (resolved once, for every wallet). */ -function walletSteps(network: NetworkConfig, sdkWarnings: CallSdkWarnings): ProvisionSteps { +function walletSteps(root: string, network: NetworkConfig, sdkWarnings: CallSdkWarnings): ProvisionSteps { return { - generate: generateWallet, - airdrop: (name, amountNight, signal) => airdropToWallet(network, name, amountNight, signal, sdkWarnings), - registerDust: (name, signal) => registerWalletDust(network, name, signal, sdkWarnings), - needsDust: (name, signal) => walletNeedsDust(network, name, signal), + generate: (name, signal) => generateWallet(root, name, signal), + airdrop: (name, amountNight, signal) => airdropToWallet(root, network, name, amountNight, signal, sdkWarnings), + registerDust: (name, signal) => registerWalletDust(root, network, name, signal, sdkWarnings), + needsDust: (name, signal) => walletNeedsDust(root, network, name, signal), }; } @@ -67,19 +69,20 @@ function walletSteps(network: NetworkConfig, sdkWarnings: CallSdkWarnings): Prov * while the earlier ones register instead of one after another. */ export async function provisionDevWallets(opts: ProvisionOptions): Promise { - const steps = 'steps' in opts ? opts.steps : walletSteps(undeployedNetwork(), opts.sdkWarnings); + const { root } = opts; + const steps = 'steps' in opts ? opts.steps : walletSteps(root, undeployedNetwork(root), opts.sdkWarnings); const results: ProvisionedWallet[] = []; const created: string[] = []; // `wallet generate` sets the new wallet as active — remember the user's // current active wallet so we can restore it after provisioning. - const previousActive = safeGetActiveWallet(); + const previousActive = safeGetActiveWallet(root); try { for (const name of opts.names) { throwIfCancelled(opts.signal); - if (walletExists(name)) { + if (walletExists(root, name)) { // Funded but never registered (setup stopped between funding and // registering): finish it below rather than reuse it as is. if (await steps.needsDust(name, opts.signal)) { @@ -108,61 +111,62 @@ export async function provisionDevWallets(opts: ProvisionOptions): Promise results.filter((r) => r.name === name)); } -function safeGetActiveWallet(): string | null { +function safeGetActiveWallet(root: string): string | null { try { - return getActiveWalletName(); + return getActiveWalletName(root); } catch { return null; } } -function restoreActiveWallet(name: string | null): void { +function restoreActiveWallet(root: string, name: string | null): void { if (!name) return; - if (!walletExists(name)) return; + if (!walletExists(root, name)) return; try { - setActiveWallet(name); + setActiveWallet(root, name); } catch { /* best-effort */ } } // ── Internals ──────────────────────────────────────────────── -function walletExists(name: string): boolean { - return existsSync(walletFilePath(name)); +function walletExists(root: string, name: string): boolean { + return existsSync(walletFilePath(root, name)); } /** The local network, with any endpoints saved for it, as the wallet commands resolve it. */ -function undeployedNetwork(): NetworkConfig { +function undeployedNetwork(root: string): NetworkConfig { return resolveNetwork({ args: { command: 'dev', subcommand: undefined, positionals: [], flags: { network: 'undeployed' } }, + configDir: root, }).config; } -async function generateWallet(name: string, signal?: AbortSignal): Promise { - const passphrase = await passphraseForNewSecret(); +async function generateWallet(root: string, name: string, signal?: AbortSignal): Promise { + const passphrase = await passphraseForNewSecret(root); // Cancelled while the passphrase was asked for: no wallet is written. throwIfCancelled(signal); - await createWallet(name, walletSecretFrom(), passphrase); + await createWallet(root, name, walletSecretFrom(), passphrase); } -async function airdropToWallet(network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { - const recipientAddress = (await loadWalletConfig(resolveWalletPath(name))).addresses.undeployed; +async function airdropToWallet(root: string, network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { + const recipientAddress = (await loadWalletConfig(resolveWalletPath(root, name))).addresses.undeployed; // dev's wallets live on the local chain. - await (await engineFor('undeployed')).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings }); + await (await engineFor('undeployed', root)).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings, root }); } -async function walletNeedsDust(network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { - const address = (await loadWalletConfig(resolveWalletPath(name))).addresses.undeployed; +async function walletNeedsDust(root: string, network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { + const address = (await loadWalletConfig(resolveWalletPath(root, name))).addresses.undeployed; const { registeredUtxos, unregisteredUtxos } = await checkBalance(address, network.indexerWS, undefined, signal); return registeredUtxos === 0 && unregisteredUtxos > 0; } -async function registerWalletDust(network: NetworkConfig, name: string, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { - const { seed } = await unlockWallet(resolveWalletPath(name)); - await (await engineFor('undeployed')).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings }); +async function registerWalletDust(root: string, network: NetworkConfig, name: string, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { + const { seed } = await unlockWallet(resolveWalletPath(root, name), { root }); + await (await engineFor('undeployed', root)).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings, root }); } diff --git a/src/lib/grant/account-records.ts b/src/lib/grant/account-records.ts index 8eadcd8a..5fdfde13 100644 --- a/src/lib/grant/account-records.ts +++ b/src/lib/grant/account-records.ts @@ -6,8 +6,6 @@ import { mkdirSync } from 'node:fs'; import { basename, join } from 'node:path'; import { DIR_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { getActiveWalletName } from '../wallet-config.ts'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** The directory under ~/.midnight that holds each network's accounts. */ export const ACCOUNTS_DIR_NAME = 'accounts'; @@ -17,12 +15,12 @@ export const ACCOUNTS_DIR_NAME = 'accounts'; * wallet given as a file, the file's name without `.json`. The active wallet * when none is given. */ -export function accountWalletName(walletFlag: string | undefined, activeWallet: () => string = getActiveWalletName): string { +export function accountWalletName(walletFlag: string | undefined, activeWallet: () => string): string { if (walletFlag === undefined) return activeWallet(); return basename(walletFlag).replace(/\.json$/, ''); } -export function accountRecordsDir(network: string, walletName: string, root: string = stateRoot()): string { +export function accountRecordsDir(network: string, walletName: string, root: string): string { return join(root, ACCOUNTS_DIR_NAME, network, walletName); } diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 6a7298f5..389fa5b9 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -39,12 +39,11 @@ import { import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { isValidNetworkName, sdkSetOfNetwork, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** Where the account package caches its proving artefacts, under ~/.midnight: each file is fetched the first time a command proves with it. */ const ACCOUNT_ARTIFACTS_DIR_NAME = 'account-artifacts'; -export function accountArtifactsDir(root: string = stateRoot()): string { +export function accountArtifactsDir(root: string): string { return join(root, ACCOUNT_ARTIFACTS_DIR_NAME); } @@ -78,10 +77,10 @@ export class UnreachableByAccountError extends UsageError { } } -/** Throws when the account package can't act on `networkConfig`'s network. */ -export function assertAccountNetwork(networkConfig: NetworkConfig): void { +/** Throws when the account package can't act on `networkConfig`'s network, by the SDK set the config under the state root `root` gives it. */ +export function assertAccountNetwork(networkConfig: NetworkConfig, root: string): void { const id = networkConfig.networkId.toLowerCase(); - const sdkSet = isValidNetworkName(id) ? sdkSetOfNetwork(id) : 'rc'; + const sdkSet = isValidNetworkName(id) ? sdkSetOfNetwork(id, root) : 'rc'; if (sdkSet !== 'rc') throw new UnreachableByAccountError(networkConfig.networkId, sdkSet); if (networkConfig.networkId.toLowerCase() !== ACCOUNT_NETWORK_ID) throw new UnreachableByAccountError(networkConfig.networkId); } @@ -129,7 +128,8 @@ export interface GrantAccount { /** Where an account's passphrase comes from, and where a warning about a plain-text account goes. */ export interface OpenAccountOptions { - root?: string; + /** The state root holding mn's passphrase check and the proving artefacts. */ + root: string; source?: PassphraseSource; warn?: (line: string) => void; } @@ -140,9 +140,9 @@ export interface OpenAccountOptions { * earlier mn wrote in plain text, as it was, with a warning; or, with nothing * on record (a first deploy), a new account sealed from the start. */ -export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: string, say: (line: string) => void, options: OpenAccountOptions = {}): Promise { - assertAccountNetwork(networkConfig); - const root = options.root ?? stateRoot(); +export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: string, say: (line: string) => void, options: OpenAccountOptions): Promise { + const { root } = options; + assertAccountNetwork(networkConfig, root); const progress = (event: ProgressEvent): void => say(describeProgress(event).trim()); const network = networkOf({ networkId: ACCOUNT_NETWORK_ID, node: httpOf(networkConfig.node), indexer: networkConfig.indexer, proofServer: networkConfig.proofServer }); const context = accountContext({ network, artefacts: artefactCache(accountArtifactsDir(root), { progress }), progress }); diff --git a/src/lib/grant/prepare.ts b/src/lib/grant/prepare.ts index d4e990d0..b2411b7e 100644 --- a/src/lib/grant/prepare.ts +++ b/src/lib/grant/prepare.ts @@ -6,7 +6,7 @@ import { type ParsedArgs, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type PayingTarget, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { assertWalletFileExists, resolveWalletPath } from '../wallet-config.ts'; +import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '../wallet-config.ts'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; import { type GrantRequest, resolveGrantRequest } from './request.ts'; @@ -49,14 +49,14 @@ export async function accountOnRecord(recordsDir: string): Promise { +export async function prepareGrant(args: ParsedArgs, root: string): Promise { const request = resolveGrantRequest(args); assertNodeRunsAccount(); - const target = resolvePayingTarget(args, 'grant', request.subcommand); + const target = resolvePayingTarget(args, 'grant', request.subcommand, root); // Refuses a network the account can't reach before anything is created. - assertAccountNetwork(target.networkConfig); - const walletName = accountWalletName(getFlag(args, 'wallet')); - const recordsDir = accountRecordsDir(target.network, walletName); + assertAccountNetwork(target.networkConfig, root); + const walletName = accountWalletName(getFlag(args, 'wallet'), () => getActiveWalletName(root)); + const recordsDir = accountRecordsDir(target.network, walletName, root); const account = await accountOnRecord(recordsDir); if (request.subcommand === 'import' && account !== null) { throw new UsageError(`Wallet "${walletName}" already has an account on ${target.network} (${account.address}); a backup is never imported over one.`); @@ -71,7 +71,7 @@ export async function prepareGrant(args: ParsedArgs): Promise { // Only a command that writes an account's first records makes their folder, // and only for a wallet there is: a command refused leaves nothing behind. if (account === null) { - assertWalletFileExists(resolveWalletPath(getFlag(args, 'wallet'))); + assertWalletFileExists(resolveWalletPath(root, getFlag(args, 'wallet'))); ensureAccountRecordsDir(recordsDir); } return { request, target, walletName, recordsDir, account }; diff --git a/src/lib/localnet.ts b/src/lib/localnet.ts index 92c16732..9e1ec35c 100644 --- a/src/lib/localnet.ts +++ b/src/lib/localnet.ts @@ -6,7 +6,6 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; import { LOCALNET_DIR_NAME, DIR_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { CancelledError, CANCELLED_MESSAGE, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import type { ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; @@ -23,10 +22,10 @@ const NODE_IMAGE = 'midnightntwrk/midnight-node:1.0.0'; const INDEXER_IMAGE = 'midnightntwrk/indexer-standalone:4.3.3'; const PROOF_SERVER_IMAGE = 'midnightntwrk/proof-server:8.1.0'; -// Built when used, under the state root the host gives; never when this module loads. -const localnetDir = (): string => join(stateRoot(), LOCALNET_DIR_NAME); -const composePath = (): string => join(localnetDir(), 'compose.yml'); -const versionPath = (): string => join(localnetDir(), '.version'); +// Built when used, under the state root the call gives; never when this module loads. +const localnetDir = (root: string): string => join(root, LOCALNET_DIR_NAME); +const composePath = (root: string): string => join(localnetDir(root), 'compose.yml'); +const versionPath = (root: string): string => join(localnetDir(root), '.version'); // Full compose.yml for midnight-local-network: the ledger-8 stack above, which // this ledger-9 build does not start. @@ -106,6 +105,8 @@ export interface DockerCall { readonly exec: ExecRunner; /** Docker's own stderr as it comes, where the call's text goes (the CLI shows it on the terminal). */ readonly onStderr: (text: string) => void; + /** The state root the localnet's compose file lives under. */ + readonly root: string; } /** @@ -167,20 +168,21 @@ export function assertLocalnetCanStart(): void { * Returns true if the file was written, false if it was already up to date. * * Every path that starts the localnet calls this first, so it is where a - * ledger-9 build refuses, before anything is written or started. + * ledger-9 build refuses, before anything is written or started. The folder + * is the one under the state root `root`. */ -export function ensureComposeFile(): boolean { +export function ensureComposeFile(root: string): boolean { assertLocalnetCanStart(); const versionMatches = - existsSync(versionPath()) && - existsSync(composePath()) && - readFileSync(versionPath(), 'utf-8').trim() === COMPOSE_VERSION; + existsSync(versionPath(root)) && + existsSync(composePath(root)) && + readFileSync(versionPath(root), 'utf-8').trim() === COMPOSE_VERSION; if (versionMatches) return false; - mkdirSync(localnetDir(), { recursive: true, mode: DIR_MODE }); - writeFileSync(composePath(), COMPOSE_YAML, 'utf-8'); - writeFileSync(versionPath(), COMPOSE_VERSION, 'utf-8'); + mkdirSync(localnetDir(root), { recursive: true, mode: DIR_MODE }); + writeFileSync(composePath(root), COMPOSE_YAML, 'utf-8'); + writeFileSync(versionPath(root), COMPOSE_VERSION, 'utf-8'); return true; } @@ -189,8 +191,8 @@ export function ensureComposeFile(): boolean { * goes to the call as it comes. Throws on non-zero exit with stderr in the * error message, and CancelledError when the call is cancelled. */ -export function dockerCompose({ signal, exec, onStderr }: DockerCall, args: readonly string[]): Promise { - return exec('docker', ['compose', '-f', composePath(), ...args], { signal, timeoutMs: DOCKER_TIMEOUT_MS, onStderr }); +export function dockerCompose({ signal, exec, onStderr, root }: DockerCall, args: readonly string[]): Promise { + return exec('docker', ['compose', '-f', composePath(root), ...args], { signal, timeoutMs: DOCKER_TIMEOUT_MS, onStderr }); } export interface ServiceStatus { @@ -298,10 +300,10 @@ const CANCELLED_LISTING_TIMEOUT_MS = 10_000; * bounded by its own time limit. When Docker can't list them, the error says * so rather than claim none were started. */ -export async function localnetUpCancelled({ exec }: Omit): Promise { +export async function localnetUpCancelled({ exec, root }: Omit): Promise { let left: ServiceStatus[]; try { - left = parseServiceStatus(await exec('docker', ['compose', '-f', composePath(), 'ps', '-a', '--format', 'json'], { + left = parseServiceStatus(await exec('docker', ['compose', '-f', composePath(root), 'ps', '-a', '--format', 'json'], { signal: new AbortController().signal, timeoutMs: CANCELLED_LISTING_TIMEOUT_MS, })); @@ -319,9 +321,9 @@ export async function localnetUpCancelled({ exec }: Omit): ); } -/** Return the compose file path (for display purposes). */ -export function getComposePath(): string { - return composePath(); +/** Return the compose file path under the state root `root` (for display purposes). */ +export function getComposePath(root: string): string { + return composePath(root); } // Container names used in compose.yml — these are the hardcoded container_name values diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index f8b19386..501fe875 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -60,12 +60,13 @@ const ENDPOINTS = [['node', 'node'], ['indexer-ws', 'indexer'], ['proof-server', * text the user confirms: each given as a parameter, or else set for the * network with `config set`. Empty when the tool takes no endpoints or none * is overridden. Without it, a transaction's proof could go to a host the - * user never saw. + * user never saw. The saved endpoints are the config's under the state root + * `root`. */ -export function endpointOverridesNote(tool: RegisteredTool, params: Readonly>): string { +export function endpointOverridesNote(tool: RegisteredTool, params: Readonly>, root: string): string { const properties = tool.inputSchema.properties; if (!ENDPOINTS.some(([param]) => Object.hasOwn(properties, param))) return ''; - const configured = getEndpointOverridesForNetwork(loadCliConfig(), resolveNetworkName({ args: toolArgv(tool, params) })); + const configured = getEndpointOverridesForNetwork(loadCliConfig(root), resolveNetworkName({ args: toolArgv(tool, params), configDir: root })); const named = ENDPOINTS.flatMap(([param, label]) => { const given = params[param]; if (typeof given === 'string' && given !== '') return [`${label} ${given}`]; @@ -83,8 +84,9 @@ export function endpointOverridesNote(tool: RegisteredTool, params: Readonly>, call: CommandRun): Promise { const found = await tool.confirmation?.check?.(params, { + host: call.host, argv: () => toolArgv(tool, params), run: async (args) => captureCommand((await tool.command.load()).default, args, call), }); - return (found ?? confirmationText(tool, params)) + endpointOverridesNote(tool, params); + return (found ?? confirmationText(tool, params)) + endpointOverridesNote(tool, params, call.host.paths().stateRoot); } diff --git a/src/lib/mcp/server-advice.ts b/src/lib/mcp/server-advice.ts index af4d1d34..71de0c61 100644 --- a/src/lib/mcp/server-advice.ts +++ b/src/lib/mcp/server-advice.ts @@ -5,10 +5,10 @@ import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; import { networksOnSdkSet } from '@kuiralabs/midnight-cli-core/lib/network'; -/** The server runs one SDK set: a call on the other set's network is told to use a server of its own. */ -export function withServerAdvice(error: Error): Error { +/** The server runs one SDK set: a call on the other set's network (by the config under the state root `root`) is told to use a server of its own. */ +export function withServerAdvice(error: Error, root: string): Error { if (!(error instanceof OtherSdkSetError)) return error; - const networks = networksOnSdkSet(error.wantedSet).join(', '); + const networks = networksOnSdkSet(error.wantedSet, root).join(', '); return new OtherSdkSetError(error.loadedSet, error.wantedSet, `This MCP server runs the ${error.loadedSet} SDK set, and ${networks} run${networks.includes(',') ? '' : 's'} on the ${error.wantedSet} set: two sets' ledgers can't share a process. Start another MCP server for ${networks} and make the call there.`); } diff --git a/src/lib/passphrase.ts b/src/lib/passphrase.ts index 6f61cfbb..052a145b 100644 --- a/src/lib/passphrase.ts +++ b/src/lib/passphrase.ts @@ -13,7 +13,6 @@ import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/e import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { currentPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { PASSPHRASE_ENV, settings } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; /** The variable a non-interactive run sets the passphrase in (named in settings.ts). */ export { PASSPHRASE_ENV }; @@ -67,7 +66,7 @@ export async function readPassphrase(source: PassphraseSource = {}): Promise(); * run. One already checked is taken again only when the environment names no * other: a changed MN_PASSPHRASE is checked afresh. */ -export async function unlockPassphrase(root: string = stateRoot(), source: PassphraseSource = {}): Promise { +export async function unlockPassphrase(root: string, source: PassphraseSource = {}): Promise { const known = unlocked.get(root); const fromEnv = source.env !== undefined ? source.env[PASSPHRASE_ENV] : settings().passphrase; if (known !== undefined && (fromEnv === undefined || fromEnv === '' || fromEnv === known)) return known; @@ -112,7 +111,7 @@ export async function unlockPassphrase(root: string = stateRoot(), source: Passp * The passphrase to seal a new secret under: the one set, or, on a machine * with none yet, a new one (asked twice at a terminal), which is then set. */ -export async function passphraseForNewSecret(root: string = stateRoot(), source: PassphraseSource = {}): Promise { +export async function passphraseForNewSecret(root: string, source: PassphraseSource = {}): Promise { if (isPassphraseSet(root)) return unlockPassphrase(root, source); const passphrase = await readPassphrase({ ...source, confirm: true }); if ([...passphrase].length < MIN_PASSPHRASE_LENGTH) { diff --git a/src/lib/seed-resolver.ts b/src/lib/seed-resolver.ts index 243048ea..e68d3ae2 100644 --- a/src/lib/seed-resolver.ts +++ b/src/lib/seed-resolver.ts @@ -52,8 +52,9 @@ export function parseSeedHex(input: string, label: string): Buffer { * `--seed ` → `MN_SEED` (env, kept off the process list) → `--wallet ` → active wallet. * Returns the seed plus the backing wallet file/config (both null for a `--seed` / `MN_SEED` * source), so a caller that caches to the wallet file can skip that when there is none. + * Wallets are the ones under the state root `root`. */ -export async function resolveSeedSource(args: ParsedArgs, opts: ResolveSeedOptions = {}): Promise { +export async function resolveSeedSource(args: ParsedArgs, root: string, opts: ResolveSeedOptions = {}): Promise { const seedFlag = getFlag(args, 'seed'); const seedSource = seedFlag ?? settings().seed; if (seedSource) { @@ -74,12 +75,12 @@ export async function resolveSeedSource(args: ParsedArgs, opts: ResolveSeedOptio ); } - const walletPath = resolveWalletPath(walletName); - const { seed, mnemonic: _mnemonic, ...config } = await unlockWallet(walletPath); + const walletPath = resolveWalletPath(root, walletName); + const { seed, mnemonic: _mnemonic, ...config } = await unlockWallet(walletPath, { root }); return { seed: Buffer.from(seed, 'hex'), walletPath, config }; } /** Just the seed — for commands that don't touch the wallet file. */ -export async function resolveSeed(args: ParsedArgs, opts?: ResolveSeedOptions): Promise { - return (await resolveSeedSource(args, opts)).seed; +export async function resolveSeed(args: ParsedArgs, root: string, opts?: ResolveSeedOptions): Promise { + return (await resolveSeedSource(args, root, opts)).seed; } diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 1d293302..1d9c9abd 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -21,6 +21,8 @@ export interface ServeHandle { } export interface ServeManagerOptions { + /** The state root the wallets, config and caches live under. */ + root: string; port?: number; network?: string; /** Explicit endpoints; they win over the network defaults and docker auto-detection. */ @@ -46,8 +48,9 @@ export function resolveServeTarget(options: ServeManagerOptions): { networkName: positionals: [], flags: { ...(options.network ? { network: options.network } : {}), ...endpointFlags(options.endpoints ?? {}) }, }, + configDir: options.root, }); - applyEndpointOverrides(networkConfig, options.endpoints ?? {}, networkName); + applyEndpointOverrides(networkConfig, options.endpoints ?? {}, networkName, options.root); return { networkName, networkConfig }; } @@ -194,7 +197,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise { +async function serveWallet(port: number, { network, root, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { startServeOrReuse } = await import('./serve-manager.ts'); const handle = await startServeOrReuse({ + root, port, network, endpoints, @@ -41,10 +42,10 @@ async function serveWallet(port: number, { network, endpoints }: PayingTarget, w * server that is running already is reused. Closing it reverts what it * balanced but never submitted. */ -async function connectWallet({ network, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options: ConnectOptions = {}): Promise { +async function connectWallet({ network, root, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options: ConnectOptions = {}): Promise { const { openConnector } = await import('./serve-manager.ts'); - const engine = await engineFor(network); - const open = () => openConnector({ network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, forceShielded: options.shielded, signal }); + const engine = await engineFor(network, root); + const open = () => openConnector({ root, network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, forceShielded: options.shielded, signal }); return sessionOver(network, await open(), (tx, stage) => engine.ledger.readTransaction(tx, stage), { reopen: open, onMessage: (msg) => progress.update(msg) }); } diff --git a/src/lib/swap/offers.ts b/src/lib/swap/offers.ts index b08b8d75..9a42f0d3 100644 --- a/src/lib/swap/offers.ts +++ b/src/lib/swap/offers.ts @@ -23,15 +23,15 @@ export interface MadeOffer { /** * Makes an offer with the session's wallet: its half of the swap, proved and - * signed, recorded among the wallet's open offers so its later spends don't - * cancel it unawares. + * signed, recorded among the wallet's open offers (under the state root + * `root`) so its later spends don't cancel it unawares. */ -export async function makeOffer(session: WalletSession, walletAddress: string, terms: SwapTerms, expiresAt: Date, now: Date = new Date()): Promise { - const engine = await engineFor(session.network); +export async function makeOffer(session: WalletSession, root: string, walletAddress: string, terms: SwapTerms, expiresAt: Date, now: Date = new Date()): Promise { + const engine = await engineFor(session.network, root); const tx = await session.makeOffer(terms.give, terms.want); const read = engine.ledger.readOffer(tx); const envelope: OfferEnvelope = { network: session.network, id: read.id, terms: read.terms, expiresAt, tx }; - recordOpenOffer(session.network, walletAddress, { id: read.id, terms: read.terms, nullifiers: read.nullifiers, madeAt: now, expiresAt }); + recordOpenOffer(root, session.network, walletAddress, { id: read.id, terms: read.terms, nullifiers: read.nullifiers, madeAt: now, expiresAt }); return { envelope, file: encodeOfferEnvelope(envelope) }; } @@ -41,13 +41,13 @@ export interface ReadOffer { contents: OfferContents; } -/** Reads an offer file's text for `network`. Throws NotAnOfferError for anything that isn't one, or says other than its bytes. */ -export async function readOfferFile(text: string, network: NetworkName): Promise { +/** Reads an offer file's text for `network`, with the engine the config under the state root `root` gives it. Throws NotAnOfferError for anything that isn't one, or says other than its bytes. */ +export async function readOfferFile(root: string, text: string, network: NetworkName): Promise { const envelope = decodeOfferEnvelope(text); if (envelope.network !== network) { throw new UsageError(`The offer is for ${envelope.network}, not ${network}: take it on ${envelope.network} (--network ${envelope.network}).`); } - const contents = (await engineFor(network)).ledger.readOffer(envelope.tx); + const contents = (await engineFor(network, root)).ledger.readOffer(envelope.tx); assertEnvelopeMatches(envelope, contents); return { envelope, contents }; } @@ -96,16 +96,17 @@ export interface ListedOffer { /** * The wallet's open offers on the network, each asked of the indexer: the - * ones taken since are closed in mn's record and listed as taken. + * ones taken since are closed in mn's record (under the state root `root`) + * and listed as taken. */ -export async function listOffers(network: NetworkName, networkConfig: NetworkConfig, walletAddress: string, now: Date = new Date(), signal?: AbortSignal): Promise { +export async function listOffers(root: string, network: NetworkName, networkConfig: NetworkConfig, walletAddress: string, now: Date = new Date(), signal?: AbortSignal): Promise { const listed: ListedOffer[] = []; - for (const offer of readOpenOffers(network, walletAddress)) { + for (const offer of readOpenOffers(root, network, walletAddress)) { const spends = await spendsOf(networkConfig, offer.nullifiers, { signal }); listed.push({ offer, expired: now.getTime() >= offer.expiresAt.getTime(), taken: spends.length > 0 }); } const taken = listed.filter((l) => l.taken).map((l) => l.offer.id); - if (taken.length > 0) closeOpenOffers(network, walletAddress, taken); + if (taken.length > 0) closeOpenOffers(root, network, walletAddress, taken); return listed; } @@ -127,21 +128,22 @@ export interface CancelOutcome { /** * Cancels the wallet's open offer with this id (or a prefix of it, 8 * characters at least): spends its coins back to the wallet, then closes it in - * mn's record. An offer found taken already is only closed. + * mn's record under the state root `root`. An offer found taken already is + * only closed. */ -export async function cancelOffer(session: WalletSession, networkConfig: NetworkConfig, walletAddress: string, id: string, signal?: AbortSignal): Promise { +export async function cancelOffer(session: WalletSession, root: string, networkConfig: NetworkConfig, walletAddress: string, id: string, signal?: AbortSignal): Promise { const wanted = id.toLowerCase(); - const matches = readOpenOffers(session.network, walletAddress).filter((o) => wanted.length >= 8 && o.id.startsWith(wanted)); + const matches = readOpenOffers(root, session.network, walletAddress).filter((o) => wanted.length >= 8 && o.id.startsWith(wanted)); if (matches.length === 0) throw new NoSuchOfferError(id); if (matches.length > 1) throw new UsageError(`${id} names ${matches.length} open offers: give more of the id`); const offer = matches[0]!; const spends = await spendsOf(networkConfig, offer.nullifiers, { signal }); if (spends.length > 0) { - closeOpenOffers(session.network, walletAddress, [offer.id]); + closeOpenOffers(root, session.network, walletAddress, [offer.id]); return { txHash: undefined, cancelled: [], alreadyTaken: [offer] }; } const cancel = await session.cancelOffers([offer]); const txHash = await session.submit(cancel); - closeOpenOffers(session.network, walletAddress, [offer.id]); + closeOpenOffers(root, session.network, walletAddress, [offer.id]); return { txHash, cancelled: [offer], alreadyTaken: [] }; } diff --git a/src/lib/swap/request.ts b/src/lib/swap/request.ts index 3b177614..7e4b7b08 100644 --- a/src/lib/swap/request.ts +++ b/src/lib/swap/request.ts @@ -36,11 +36,11 @@ export interface MakeRequest { out: string | undefined; } -export function prepareMake(args: ParsedArgs, now: Date): MakeRequest { +export function prepareMake(args: ParsedArgs, root: string, now: Date): MakeRequest { const lifetime = getFlag(args, 'expires-in') ?? String(DEFAULT_OFFER_LIFETIME_S); if (!/^[1-9][0-9]*$/.test(lifetime)) throw new UsageError(`--expires-in must be a whole number of seconds above 0, not "${lifetime}"`); return { - target: resolvePayingTarget(args, 'swap', 'make'), + target: resolvePayingTarget(args, 'swap', 'make', root), terms: termsOf(args), expiresAt: new Date(now.getTime() + Number(lifetime) * 1000), out: getFlag(args, 'out'), @@ -63,12 +63,12 @@ export async function readOfferArg(args: ParsedArgs, target: PayingTarget): Prom } catch (err) { throw new UsageError(`Can't read the offer file ${file}: ${(err as Error).message}`); } - return readOfferFile(text, target.network); + return readOfferFile(target.root, text, target.network); } /** A take, checked as far as it can be without the chain: the file, its network, the agreed terms and the expiry. */ -export async function prepareTake(args: ParsedArgs, now: Date): Promise { - const target = resolvePayingTarget(args, 'swap', 'take'); +export async function prepareTake(args: ParsedArgs, root: string, now: Date): Promise { + const target = resolvePayingTarget(args, 'swap', 'take', root); const agreed = termsOf(args); const offer = await readOfferArg(args, target); checkTerms(offer.contents.terms, agreed); diff --git a/src/lib/test/actions-runner.ts b/src/lib/test/actions-runner.ts index 30ac009f..69036c87 100644 --- a/src/lib/test/actions-runner.ts +++ b/src/lib/test/actions-runner.ts @@ -31,6 +31,8 @@ export interface ActionResult { } export interface ActionsRunnerOptions { + /** The state root whose config names the network's SDK set. */ + root: string; actions: TestAction[]; config: DappTestConfig; dappDir: string; @@ -48,7 +50,7 @@ export interface ActionsRunnerOptions { * Deploy address flows to subsequent call/state actions automatically. */ export async function runActions(options: ActionsRunnerOptions): Promise { - const { actions, config, dappDir, suiteName, networkConfig, servePort, redeploy, onActionStart, onActionComplete, onMessage } = options; + const { root, actions, config, dappDir, suiteName, networkConfig, servePort, redeploy, onActionStart, onActionComplete, onMessage } = options; const results: ActionResult[] = []; // Load cached contract address (test replay). The address is only as good @@ -103,6 +105,7 @@ export async function runActions(options: ActionsRunnerOptions): Promise }; @@ -60,6 +59,8 @@ export interface BrowserTestOptions { prompt: string; dappDir: string; logFile: string; + /** The user's home, where Claude Code keeps its config. */ + home: string; onMessage?: (msg: string) => void; /** The test's own output as it comes, to show beside the log file it also goes to. */ onOutput?: (chunk: Buffer) => void; @@ -150,7 +151,7 @@ export async function runBrowserTest(options: BrowserTestOptions): Promise { if (step === 'cache-clear') { - return stepCacheClear(config); + return stepCacheClear(config, ctx.root); } if (step === 'localnet-up') { - return stepLocalnetUp(config, callbacks); + return stepLocalnetUp(config, ctx.root, callbacks); } if (step.startsWith('balance:')) { const amount = parseInt(step.split(':')[1], 10); @@ -83,19 +83,20 @@ async function runStep( // ── Step implementations ── -async function stepCacheClear(config: DappTestConfig): Promise { +async function stepCacheClear(config: DappTestConfig, root: string): Promise { const network = config.network ?? 'undeployed'; // Clear ALL wallet caches for this network — not just the active wallet. // After a localnet restart, every wallet (including genesis) has stale state. - clearWalletCache(undefined, network); + clearWalletCache(undefined, network, root); } -async function stepLocalnetUp(config: DappTestConfig, callbacks: PrepCallbacks): Promise { +async function stepLocalnetUp(config: DappTestConfig, root: string, callbacks: PrepCallbacks): Promise { // This build can't start a localnet (no published ledger-9 indexer image), // so the step requires a running ledger-9 stack at the resolved endpoints. const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: undefined, positionals: [], flags: { network } }, + configDir: root, }); await assertLedger9StackReachable(network, networkConfig); callbacks.onMessage(`Using the ledger-9 stack at ${networkConfig.node} (indexer ${networkConfig.indexer})`); @@ -105,22 +106,23 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: undefined, positionals: [], flags: { network } }, + configDir: ctx.root, }); // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig); - const walletConfig = await unlockWallet(resolveWalletPath()); + const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; // Check current balance — use fresh cache since localnet may have restarted callbacks.onMessage('Checking balance...'); - const engine = await engineFor(network); + const engine = await engineFor(network, ctx.root); const stopListening = ctx.sdkWarnings.listen((_tag, msg) => { callbacks.onMessage(`SDK: ${msg}`); }); try { - const balance = await engine.wallet.prepNightBalance({ seed: seedBuffer, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }); + const balance = await engine.wallet.prepNightBalance({ seed: seedBuffer, root: ctx.root, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }); if (balance > 0n) { callbacks.onMessage(`Balance OK: ${balance}`); return; @@ -151,6 +153,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont onSubmitting() { callbacks.onMessage('Submitting airdrop transaction...'); }, onSyncWarning(_tag, msg) { callbacks.onMessage(`Syncing genesis... (${msg})`); }, sdkWarnings: ctx.sdkWarnings, + root: ctx.root, }); callbacks.onMessage(`Airdropped ${amount} NIGHT`); @@ -162,18 +165,19 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: undefined, positionals: [], flags: { network } }, + configDir: ctx.root, }); await assertLedgerSupported(network, networkConfig); - const walletConfig = await unlockWallet(resolveWalletPath()); + const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; // Keep the SDK's transient errors and RPC noise off the terminal while this runs. const stopListening = ctx.sdkWarnings.listen(undefined); try { - const { dustAvailable } = await (await engineFor(network)).wallet.prepDust( - { seed: seedBuffer, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }, + const { dustAvailable } = await (await engineFor(network, ctx.root)).wallet.prepDust( + { seed: seedBuffer, root: ctx.root, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }, DUST_WAIT_TIMEOUT_MS, ); // Verify dust is actually available — don't trust silent timeouts @@ -201,6 +205,7 @@ async function stepMnServe(config: DappTestConfig, ctx: PrepContext, callbacks: // than silently double-binding and falling back to whatever was there // before. const handle = await startServeOrReuse({ + root: ctx.root, port: undefined, // use default network: config.network, onMessage: (msg) => callbacks.onMessage(`[serve] ${msg}`), diff --git a/src/lib/test/types.ts b/src/lib/test/types.ts index 8a58f3ec..5581bc8d 100644 --- a/src/lib/test/types.ts +++ b/src/lib/test/types.ts @@ -144,6 +144,8 @@ export interface BuildHandle { // ── Prep context — accumulates resources for teardown ── export interface PrepContext { + /** The state root the wallets, config and caches live under. */ + root: string; /** The SDK warnings of the call that runs the prep: the steps that run the SDK listen to them. */ sdkWarnings: CallSdkWarnings; /** The run's cancellation: no step starts after it aborts, and the waits inside a step stop. */ @@ -154,9 +156,10 @@ export interface PrepContext { addCleanup(fn: () => Promise): void; } -export function createPrepContext(sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): PrepContext { +export function createPrepContext(root: string, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): PrepContext { const cleanups: (() => Promise)[] = []; return { + root, sdkWarnings, signal, cleanups, diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 828f51ad..eb40de93 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -21,8 +21,8 @@ export interface TransferRequest { shielded: boolean; } -/** `transfer [--shielded] [--wallet] [--network]`, checked without touching the chain. */ -export async function resolveTransferRequest(args: ParsedArgs): Promise { +/** `transfer [--shielded] [--wallet] [--network]`, checked without touching the chain, against the wallets and config under the state root `root`. */ +export async function resolveTransferRequest(args: ParsedArgs, root: string): Promise { const recipientInput = args.subcommand; const amountStr = args.positionals[0]; @@ -44,18 +44,18 @@ export async function resolveTransferRequest(args: ParsedArgs): Promise { +async function resolveRecipient(input: string, args: ParsedArgs, shielded: boolean, root: string): Promise { if (input.startsWith('mn_addr_') || input.startsWith('mn_shield-addr_')) { return input; } - const recipientPath = resolveWalletPath(input); - const networkName = resolveNetworkName({ args }); + const recipientPath = resolveWalletPath(root, input); + const networkName = resolveNetworkName({ args, configDir: root }); if (shielded) { - const shieldedAddr = await walletShieldedAddress(recipientPath, networkName); + const shieldedAddr = await walletShieldedAddress(recipientPath, networkName, root); if (!shieldedAddr) { throw new Error( `Wallet "${input}" has no shielded address for network "${networkName}".\n` + @@ -94,7 +94,7 @@ async function resolveRecipient(input: string, args: ParsedArgs, shielded: boole return shieldedAddr; } - const address = await walletAddress(recipientPath, networkName); + const address = await walletAddress(recipientPath, networkName, root); if (!address) { throw new Error(`Wallet "${input}" has no address for network "${networkName}". Regenerate the wallet to derive one.`); } diff --git a/src/lib/wallet-can-pay.ts b/src/lib/wallet-can-pay.ts index 32ddfa76..1abe9252 100644 --- a/src/lib/wallet-can-pay.ts +++ b/src/lib/wallet-can-pay.ts @@ -16,13 +16,13 @@ import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; * active wallet is checked, the one the command's server will use. Returns * what it found, the Dust in Specks. */ -export async function assertWalletCanPay({ network, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner, signal?: AbortSignal): Promise<{ nightBalance: bigint; dustBalance: bigint }> { +export async function assertWalletCanPay({ network, root, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner, signal?: AbortSignal): Promise<{ nightBalance: bigint; dustBalance: bigint }> { throwIfCancelled(signal); - const walletConfig = await unlockWallet(resolveWalletPath(wallet)); + const walletConfig = await unlockWallet(resolveWalletPath(root, wallet), { root }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; const { engineFor } = await import('@kuiralabs/midnight-cli-core/lib/engine'); - const { wallet: repo } = await engineFor(network); + const { wallet: repo } = await engineFor(network, root); try { // Two cheap reads through the repo: no facade, no proof server, no strict @@ -43,7 +43,7 @@ export async function assertWalletCanPay({ network, networkConfig }: PayingTarge ); } - const dustView = await repo.dustBalance(seedBuffer, networkConfig, { signal, onStatus: (s) => progress.update(s) }); + const dustView = await repo.dustBalance(seedBuffer, networkConfig, { root, signal, onStatus: (s) => progress.update(s) }); if (dustView.balance === 0n && dustView.availableCoins === 0) { progress.fail('No dust available'); throw new Error( diff --git a/src/lib/wallet-config.ts b/src/lib/wallet-config.ts index d40f8cc7..a13b7a7a 100644 --- a/src/lib/wallet-config.ts +++ b/src/lib/wallet-config.ts @@ -4,12 +4,11 @@ import * as path from 'path'; import { DEFAULT_WALLET_FILENAME, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, FILE_MODE, isValidWalletName } from '@kuiralabs/midnight-cli-core/lib/constants'; import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { loadCliConfig, saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { getDefaultWalletPath, getWalletsDir } from './wallet-paths.ts'; +import { getWalletsDir } from './wallet-paths.ts'; import { anyEngine, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; import { isSealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { FileExistsError, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; import { type PassphraseSource, unlockPassphrase } from './passphrase.ts'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** What anyone may read of a wallet: its addresses, and whether its secrets are sealed. No secret. */ @@ -81,16 +80,16 @@ export function getAddress(config: WalletConfig, network: NetworkName): string { * that network existed has none saved yet: it is unlocked, which derives and * saves it. */ -export async function walletAddress(walletPath: string, network: NetworkName): Promise { +export async function walletAddress(walletPath: string, network: NetworkName, root: string): Promise { const config = await loadWalletConfig(walletPath); - return config.addresses[network] ?? (await unlockWallet(walletPath)).addresses[network]; + return config.addresses[network] ?? (await unlockWallet(walletPath, { root })).addresses[network]; } /** A wallet's shielded address on `network`, unlocking a sealed wallet that has none saved yet (see walletAddress); undefined when the wallet keeps no shielded addresses. */ -export async function walletShieldedAddress(walletPath: string, network: NetworkName): Promise { +export async function walletShieldedAddress(walletPath: string, network: NetworkName, root: string): Promise { const config = await loadWalletConfig(walletPath); if (config.shieldedAddresses === undefined || config.shieldedAddresses[network] !== undefined) return config.shieldedAddresses?.[network]; - return (await unlockWallet(walletPath)).shieldedAddresses?.[network]; + return (await unlockWallet(walletPath, { root })).shieldedAddresses?.[network]; } /** The networks an address map has no address for: a wallet written before they existed. */ @@ -122,59 +121,59 @@ function looksLikePath(value: string): boolean { /** * Resolve a wallet name or path to an absolute file path. * - * Resolution order: + * Resolution order, under the state root `root`: * 1. If nameOrPath contains '/' or ends with '.json' → treat as path (backward compat) * 2. If nameOrPath is a simple name → resolve to ~/.midnight/wallets/.json * 3. If no argument: read active wallet from config → resolve by name * 4. If no config: use DEFAULT_WALLET_NAME → ~/.midnight/wallets/default.json */ -export function resolveWalletPath(nameOrPath?: string): string { +export function resolveWalletPath(root: string, nameOrPath?: string): string { if (nameOrPath !== undefined) { if (looksLikePath(nameOrPath)) { return path.resolve(nameOrPath); } - return path.join(getWalletsDir(), `${nameOrPath}.json`); + return path.join(getWalletsDir(root), `${nameOrPath}.json`); } // No flag provided — check config for active wallet - const config = loadCliConfig(); + const config = loadCliConfig(root); const activeWallet = config.wallet ?? DEFAULT_WALLET_NAME; - return path.join(getWalletsDir(), `${activeWallet}.json`); + return path.join(getWalletsDir(root), `${activeWallet}.json`); } /** - * Get the active wallet name from config (or default). + * Get the active wallet name from the config under the state root `root` (or default). */ -export function getActiveWalletName(): string { - const config = loadCliConfig(); +export function getActiveWalletName(root: string): string { + const config = loadCliConfig(root); return config.wallet ?? DEFAULT_WALLET_NAME; } /** - * Set the active wallet in config. + * Set the active wallet in the config under the state root `root`. */ -export function setActiveWallet(name: string): void { +export function setActiveWallet(root: string, name: string): void { if (!isValidWalletName(name)) { throw new Error( `Invalid wallet name: "${name}"\nWallet name must be a simple name (no path separators, .json suffix, or special characters).` ); } - const walletPath = path.join(getWalletsDir(), `${name}.json`); + const walletPath = path.join(getWalletsDir(root), `${name}.json`); if (!fs.existsSync(walletPath)) { throw new Error( `Wallet "${name}" not found.\nRun "midnight wallet list" to see available wallets.` ); } - const config = loadCliConfig(); + const config = loadCliConfig(root); config.wallet = name; - saveCliConfig(config); + saveCliConfig(config, root); } /** - * List all wallets in ~/.midnight/wallets/. + * List all wallets in the wallets folder under the state root `root`. */ -export async function listWallets(): Promise { - const walletsDir = getWalletsDir(); +export async function listWallets(root: string): Promise { + const walletsDir = getWalletsDir(root); if (!fs.existsSync(walletsDir)) { return []; } @@ -182,7 +181,7 @@ export async function listWallets(): Promise { let keys: EngineKeys | undefined; const engineKeys = async (): Promise => (keys ??= (await anyEngine()).keys); - const activeName = getActiveWalletName(); + const activeName = getActiveWalletName(root); const files = fs.readdirSync(walletsDir).filter(f => f.endsWith('.json')).sort(); return Promise.all(files.map(async (file) => { @@ -260,9 +259,10 @@ export function matchWalletAddress( * Convenience wrapper over matchWalletAddress + listWallets. */ export async function findWalletByAddress( + root: string, address: string, ): Promise<{ wallet: WalletInfo; network: NetworkName } | undefined> { - return matchWalletAddress(await listWallets(), address); + return matchWalletAddress(await listWallets(root), address); } /** @@ -273,13 +273,13 @@ export async function findWalletByAddress( * Throws, saying why, unless the named wallet can be removed: it exists, and * it is neither the active wallet nor the only one. Returns its file. */ -export function assertWalletRemovable(name: string): string { +export function assertWalletRemovable(root: string, name: string): string { if (!isValidWalletName(name)) { throw new Error( `Invalid wallet name: "${name}"\nWallet name must be a simple name (no path separators, .json suffix, or special characters).` ); } - const walletsDir = getWalletsDir(); + const walletsDir = getWalletsDir(root); const walletPath = path.join(walletsDir, `${name}.json`); if (!fs.existsSync(walletPath)) { @@ -288,7 +288,7 @@ export function assertWalletRemovable(name: string): string { ); } - const activeName = getActiveWalletName(); + const activeName = getActiveWalletName(root); if (name === activeName) { throw new Error( `Cannot remove the active wallet "${name}".\n` + @@ -307,8 +307,8 @@ export function assertWalletRemovable(name: string): string { return walletPath; } -export function removeWallet(name: string): void { - fs.unlinkSync(assertWalletRemovable(name)); +export function removeWallet(root: string, name: string): void { + fs.unlinkSync(assertWalletRemovable(root, name)); } /** Throws, with how to make one, when there is no wallet file at `resolvedPath`. */ @@ -326,10 +326,8 @@ export function assertWalletFileExists(resolvedPath: string): void { * Throws with an actionable message if file is missing or invalid. * Callers should use resolveWalletPath() to get the path first. */ -export async function loadWalletConfig(walletPath?: string): Promise { - const resolvedPath = walletPath - ? path.resolve(walletPath) - : getDefaultWalletPath(); +export async function loadWalletConfig(walletPath: string): Promise { + const resolvedPath = path.resolve(walletPath); assertWalletFileExists(resolvedPath); @@ -555,9 +553,9 @@ export async function protectAllWallets(root: string, passphrase: string, signal return report; } -/** How a wallet is unlocked: the state root holding mn's passphrase check (the host's, unless given), where the passphrase comes from, and where a warning goes. */ +/** How a wallet is unlocked: the state root holding mn's passphrase check, where the passphrase comes from, and where a warning goes. */ export interface UnlockOptions { - root?: string; + root: string; source?: PassphraseSource; warn?: (line: string) => void; } @@ -566,7 +564,7 @@ export interface UnlockOptions { const warnedPlain = new Set(); /** A wallet with its secrets: opened with mn's passphrase, or read as it is from a plain-text file an earlier mn wrote. */ -export async function unlockWallet(walletPath: string, options: UnlockOptions = {}): Promise { +export async function unlockWallet(walletPath: string, options: UnlockOptions): Promise { const resolvedPath = path.resolve(walletPath); const config = await loadWalletConfig(resolvedPath); const raw = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8')); @@ -579,7 +577,7 @@ export async function unlockWallet(walletPath: string, options: UnlockOptions = } return typeof raw.mnemonic === 'string' ? { ...config, seed: raw.seed, mnemonic: raw.mnemonic } : { ...config, seed: raw.seed }; } - const passphrase = await unlockPassphrase(options.root ?? stateRoot(), options.source); + const passphrase = await unlockPassphrase(options.root, options.source); const secrets = JSON.parse(openSecret(raw.sealed, passphrase, 'wallet').toString('utf8')) as WalletSecrets; // A network added since the wallet was written: now that its seed is open, // derive that network's addresses and save them beside the sealed secrets. diff --git a/src/lib/wallet-create.ts b/src/lib/wallet-create.ts index de6c4850..1ef4744c 100644 --- a/src/lib/wallet-create.ts +++ b/src/lib/wallet-create.ts @@ -27,14 +27,14 @@ export interface CreatedWallet { createdAt: string; } -/** Where the wallet called `name` is kept. */ -export function walletFilePath(name: string): string { +/** Where the wallet called `name` is kept under the state root `root`. */ +export function walletFilePath(root: string, name: string): string { if (!isValidWalletName(name)) { throw new Error( `Invalid wallet name: "${name}"\nWallet name must be a simple name (no path separators, .json suffix, or special characters).` ); } - return path.join(getWalletsDir(), `${name}.json`); + return path.join(getWalletsDir(root), `${name}.json`); } /** The secret from a given seed, a given mnemonic (checked against the English wordlist), or else a new 24-word mnemonic. */ @@ -51,11 +51,12 @@ export function walletSecretFrom(given: { seed?: Buffer; mnemonic?: string } = { } /** - * Writes the wallet `name` sealed under `passphrase` and makes it the active - * wallet. An existing wallet of that name is replaced only with `overwrite`. + * Writes the wallet `name` sealed under `passphrase` under the state root + * `root` and makes it the active wallet. An existing wallet of that name is + * replaced only with `overwrite`. */ -export async function createWallet(name: string, secret: WalletSecret, passphrase: string, { overwrite = false }: { overwrite?: boolean } = {}): Promise { - const targetPath = walletFilePath(name); +export async function createWallet(root: string, name: string, secret: WalletSecret, passphrase: string, { overwrite = false }: { overwrite?: boolean } = {}): Promise { + const targetPath = walletFilePath(root, name); const { keys } = await anyEngine(); const addresses = keys.unshieldedAddresses(secret.seed); const shieldedAddresses = keys.shieldedAddresses(secret.seed); @@ -64,7 +65,7 @@ export async function createWallet(name: string, secret: WalletSecret, passphras const secrets = secret.mnemonic ? { seed: seedHex, mnemonic: secret.mnemonic } : { seed: seedHex }; const file = writeSealedWallet(targetPath, config, secrets, passphrase, { overwrite }); - setActiveWallet(name); + setActiveWallet(root, name); const created: CreatedWallet = { name, addresses, shieldedAddresses, seed: secret.seed, file, createdAt: config.createdAt }; if (secret.mnemonic) created.mnemonic = secret.mnemonic; diff --git a/src/lib/wallet-paths.ts b/src/lib/wallet-paths.ts index f21b6347..c6ee2640 100644 --- a/src/lib/wallet-paths.ts +++ b/src/lib/wallet-paths.ts @@ -6,30 +6,25 @@ import * as fs from 'fs'; import * as path from 'path'; import { DEFAULT_WALLET_FILENAME, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { loadCliConfig, saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { stateRoot } from '@kuiralabs/midnight-cli-core/lib/state-root'; - -function getMidnightDir(): string { - return stateRoot(); -} - -export function getWalletsDir(): string { - return path.join(getMidnightDir(), WALLETS_DIR_NAME); +/** The wallets folder under the state root `root`. */ +export function getWalletsDir(root: string): string { + return path.join(root, WALLETS_DIR_NAME); } -export function getDefaultWalletPath(): string { - return path.join(getMidnightDir(), DEFAULT_WALLET_FILENAME); +/** Where an early mn kept its one wallet, under the state root `root`. */ +export function getDefaultWalletPath(root: string): string { + return path.join(root, DEFAULT_WALLET_FILENAME); } -function ensureMidnightDir(): void { - const dir = getMidnightDir(); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); +function ensureMidnightDir(root: string): void { + if (!fs.existsSync(root)) { + fs.mkdirSync(root, { recursive: true, mode: DIR_MODE }); } } -export function ensureWalletsDir(): void { - ensureMidnightDir(); - const dir = getWalletsDir(); +export function ensureWalletsDir(root: string): void { + ensureMidnightDir(root); + const dir = getWalletsDir(root); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE }); } @@ -37,13 +32,13 @@ export function ensureWalletsDir(): void { /** * Migrate old ~/.midnight/wallet.json to ~/.midnight/wallets/default.json. - * Silent, one-time migration. No-op if wallets/ already has files or old wallet doesn't exist. + * Silent, one-time migration, under the state root `root`. No-op if wallets/ already has files or old wallet doesn't exist. */ -export function migrateOldWallet(): void { - const oldPath = getDefaultWalletPath(); +export function migrateOldWallet(root: string): void { + const oldPath = getDefaultWalletPath(root); if (!fs.existsSync(oldPath)) return; - const walletsDir = getWalletsDir(); + const walletsDir = getWalletsDir(root); // If wallets/ already has files, don't migrate (user already using multi-wallet) if (fs.existsSync(walletsDir)) { @@ -52,7 +47,7 @@ export function migrateOldWallet(): void { } // Ensure wallets directory exists - ensureWalletsDir(); + ensureWalletsDir(root); // Move old wallet to wallets/default.json const newPath = path.join(walletsDir, `${DEFAULT_WALLET_NAME}.json`); @@ -61,7 +56,7 @@ export function migrateOldWallet(): void { fs.unlinkSync(oldPath); // Set active wallet to default - const config = loadCliConfig(); + const config = loadCliConfig(root); config.wallet = DEFAULT_WALLET_NAME; - saveCliConfig(config); + saveCliConfig(config, root); } diff --git a/src/lib/wallet-protector.ts b/src/lib/wallet-protector.ts index 4fbcc7f1..50fbd16b 100644 --- a/src/lib/wallet-protector.ts +++ b/src/lib/wallet-protector.ts @@ -30,9 +30,9 @@ export interface WalletProtector { /** The wallet command's call context: a command's, with the protectors `wallet protect` runs. */ export type WalletCommandContext = CallContext; -/** The shielded coin public key of the wallet `name`, unlocked with mn's passphrase. */ -export async function coinKeyOfWallet(name: string): Promise { +/** The shielded coin public key of the wallet `name` under the state root `root`, unlocked with mn's passphrase. */ +export async function coinKeyOfWallet(root: string, name: string): Promise { // The engine loads the SDK, which the other wallet subcommands don't need: loaded here, not up front. const { anyEngine } = await import('@kuiralabs/midnight-cli-core/lib/engine'); - return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(name))).seed, 'hex')); + return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(root, name), { root })).seed, 'hex')); } diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 2bff4e67..432f0472 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -110,7 +110,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { assertKnownParams(schema, params); assertParamTypes(schema, params); } catch (err) { - return errorResponse(err instanceof Error ? err : new Error(String(err))); + return errorResponse(err instanceof Error ? err : new Error(String(err)), call); } } @@ -119,7 +119,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { const token = typeof params.token === 'string' ? params.token : ''; const pending = confirmationStore.redeem(token); if (!pending) { - return errorResponse(new Error('Unknown or expired confirmation token. The first-step tool call may need to be re-issued.')); + return errorResponse(new Error('Unknown or expired confirmation token. The first-step tool call may need to be re-issued.'), call); } return executeTool(pending.tool, pending.args, call); } @@ -130,7 +130,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { try { description = await confirmationFor(tool, params, call); } catch (err) { - return errorResponse(err instanceof Error ? err : new Error(String(err))); + return errorResponse(err instanceof Error ? err : new Error(String(err)), call); } const pending = confirmationStore.create({ tool: name, args: params, description }); return { @@ -188,7 +188,7 @@ function stamp>(payload: T): T & { _serverVers async function executeTool(name: string, params: Record, call: CommandRun) { const tool = findTool(installedCommands, name); - if (!tool) return errorResponse(new Error(`Unknown tool: ${name}`)); + if (!tool) return errorResponse(new Error(`Unknown tool: ${name}`), call); try { const result = await runTool(tool, params, call); @@ -196,13 +196,13 @@ async function executeTool(name: string, params: Record, call: content: [{ type: 'text' as const, text: JSON.stringify(stamp(result), null, 2) }], }; } catch (err) { - return errorResponse(err instanceof Error ? err : new Error(String(err))); + return errorResponse(err instanceof Error ? err : new Error(String(err)), call); } } -function errorResponse(thrown: Error) { +function errorResponse(thrown: Error, call: CommandRun) { // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. - const error = withServerAdvice(withNodeReason(thrown)); + const error = withServerAdvice(withNodeReason(thrown), call.host.paths().stateRoot); const { errorCode } = classifyError(error); return { content: [{ diff --git a/src/wallet.ts b/src/wallet.ts index e036b251..c780e1c3 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -73,7 +73,7 @@ hideProjectIdsInOutput(); const host = createCliHost({ prompter: createTerminalPrompter() }); // Auto-migrate old ~/.midnight/wallet.json → wallets/default.json (silent, one-time) -migrateOldWallet(); +migrateOldWallet(host.paths().stateRoot); // Global AbortController for clean shutdown on SIGINT/SIGTERM const abortController = new AbortController(); From cf3603fcfe81b1f5654a171b4b9f55653d5002b4 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 03:40:05 -0800 Subject: [PATCH 58/88] Prompter, notices and per-host state come from the host (3B, 4 of 7) No library reads the notice sink or the prompter from module state: commands take them from their call's host, libraries in the options they already take (approvals, the engines' wallet work, the connector, the wallet session). The unlocked passphrase, the plain-text wallet warning and the RPC connection counter move into host slots, so each host keeps its own. A paying target carries its host. The approval refusal without a prompter now names createHost, not the removed setter. Five module-state allowances go; eight are left. Behaviour snapshot unchanged; suite 2567, beta 168; on the scratch chain swap pass 30/30, MCP swap probe 12/12, tx pass 25/25. --- packages/cli-core/api-report.md | 29 +++- packages/cli-core/src/lib/approval.ts | 21 ++- packages/cli-core/src/lib/engine.ts | 17 +- packages/cli-core/src/lib/notices.ts | 23 +-- packages/cli-core/src/lib/payer.ts | 12 +- packages/cli-core/src/lib/prompter.ts | 20 +-- packages/cli-core/src/lib/wallet-session.ts | 4 + packages/engine-beta/api-report.md | 13 +- packages/engine-beta/src/dapp-connector.ts | 6 +- packages/engine-beta/src/dust-export.ts | 12 +- packages/engine-beta/src/dust-register.ts | 3 +- packages/engine-beta/src/facade.ts | 6 +- packages/engine-beta/src/transfer.ts | 2 + .../engine-beta/src/wallet-data-repository.ts | 27 +-- packages/engine-beta/src/wallet.ts | 21 ++- packages/engine-rc/api-report.md | 12 +- packages/engine-rc/src/dapp-connector.ts | 6 +- packages/engine-rc/src/dust-export.ts | 12 +- packages/engine-rc/src/dust-register.ts | 3 +- packages/engine-rc/src/facade.ts | 6 +- packages/engine-rc/src/transfer.ts | 2 + .../engine-rc/src/wallet-data-repository.ts | 19 ++- packages/engine-rc/src/wallet.ts | 21 ++- scripts/check-process-safety.mjs | 7 +- src/__tests__/account-backup.test.ts | 12 +- src/__tests__/approval.test.ts | 73 ++++---- src/__tests__/command-cancellation.test.ts | 16 +- src/__tests__/contract-deploy.test.ts | 10 +- src/__tests__/dev-keys.test.ts | 10 +- src/__tests__/dust-export.test.ts | 3 + src/__tests__/engine-beta.test.ts | 7 +- src/__tests__/fixtures/record-swap-offer.ts | 2 +- src/__tests__/generate-command.test.ts | 36 ++-- src/__tests__/grant-account.test.ts | 6 +- src/__tests__/grant-prepare.test.ts | 6 +- src/__tests__/helpers/connector-stub.ts | 8 +- src/__tests__/helpers/connector-suite.ts | 137 ++++++++------- src/__tests__/host-paths.test.ts | 11 +- src/__tests__/host-slots.test.ts | 157 ++++++++++++++++++ src/__tests__/notices.test.ts | 29 ++-- src/__tests__/passphrase.test.ts | 26 +-- src/__tests__/payer.test.ts | 16 +- .../prep-runner-cancellation.test.ts | 6 +- src/__tests__/protect-account.test.ts | 14 +- src/__tests__/sealed-wallet.test.ts | 8 +- src/__tests__/seed-resolver.test.ts | 30 ++-- src/__tests__/serve-manager.test.ts | 12 +- src/__tests__/settings.test.ts | 2 +- src/__tests__/state-root.test.ts | 2 +- src/__tests__/swap-request.test.ts | 12 +- src/__tests__/transfer-request.test.ts | 6 +- src/__tests__/verbose-per-call.test.ts | 3 - src/__tests__/wallet-config.test.ts | 8 +- src/__tests__/wallet-create.test.ts | 14 +- src/__tests__/wallet-data-repository.test.ts | 54 +++--- src/__tests__/wallet-session.test.ts | 6 +- .../wallet-state-to-restore.live.test.ts | 4 +- src/__tests__/ws-rpc.test.ts | 32 +++- src/commands/address.ts | 2 +- src/commands/airdrop.ts | 11 +- src/commands/balance.ts | 2 +- src/commands/cache.ts | 2 +- src/commands/contract.definition.ts | 4 +- src/commands/contract.ts | 6 +- src/commands/dev.ts | 6 +- src/commands/dust.ts | 7 +- src/commands/generate.ts | 2 +- src/commands/grant.definition.ts | 2 +- src/commands/grant.ts | 12 +- src/commands/info.ts | 2 +- src/commands/serve.ts | 7 +- src/commands/swap.definition.ts | 4 +- src/commands/swap.ts | 16 +- src/commands/test.ts | 2 +- src/commands/transfer.definition.ts | 2 +- src/commands/transfer.ts | 8 +- src/commands/wallet.ts | 10 +- src/lib/cli-host.ts | 5 +- src/lib/dev/deploy.ts | 5 +- src/lib/dev/provision-wallets.ts | 30 ++-- src/lib/grant/account.ts | 16 +- src/lib/grant/prepare.ts | 5 +- src/lib/passphrase.ts | 37 +++-- src/lib/seed-resolver.ts | 10 +- src/lib/serve-manager.ts | 10 +- src/lib/serve-payer.ts | 7 +- src/lib/swap/request.ts | 9 +- src/lib/test/prep-runner.ts | 10 +- src/lib/test/types.ts | 6 +- src/lib/transfer-request.ts | 14 +- src/lib/wallet-can-pay.ts | 6 +- src/lib/wallet-config.ts | 31 ++-- src/lib/wallet-protector.ts | 8 +- src/lib/ws-rpc.ts | 13 +- src/ui/dev-keys.ts | 8 +- 95 files changed, 880 insertions(+), 539 deletions(-) create mode 100644 src/__tests__/host-slots.test.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index e33cd904..7704afa2 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -70,6 +70,8 @@ export declare function parseAmount(amountStr: string): number; ## `@kuiralabs/midnight-cli-core/lib/approval` ```ts +import type { NoticeSink } from "./notices.ts"; +import { type Prompter } from "./prompter.ts"; import type { FeeLimits } from "./fee-limits.ts"; export interface ApprovalDetail { label: string; @@ -87,6 +89,8 @@ export interface ApprovalOptions { autoApproveReads?: boolean; approveAll?: boolean; approveFees?: boolean; + prompter: Prompter | null; + notice: NoticeSink; } export interface ApprovalPolicy { reads: "auto"; @@ -97,11 +101,11 @@ export interface ApprovalPolicy { maxPending: number; }; } -export declare function describeApprovalPolicy(options: ApprovalOptions, feeLimits: FeeLimits): ApprovalPolicy; +export declare function describeApprovalPolicy(options: Omit, feeLimits: FeeLimits): ApprovalPolicy; export declare function isReadOnlyMethod(method: string): boolean; export declare function isPrepMethod(method: string): boolean; export declare function renderApprovalBox(request: ApprovalRequest): string; -export declare function promptApproval(request: ApprovalRequest, options?: ApprovalOptions): Promise; +export declare function promptApproval(request: ApprovalRequest, options: ApprovalOptions): Promise; ``` ## `@kuiralabs/midnight-cli-core/lib/argv` @@ -640,6 +644,7 @@ import { type NetworkConfig, type NetworkName } from "./network.ts"; import type { CallSdkWarnings } from "./sdk-warnings.ts"; import type { VerboseLog } from "./verbose.ts"; import type { ApprovalOptions } from "./approval.ts"; +import type { NoticeSink } from "./notices.ts"; import type { FeeLimits } from "./fee-limits.ts"; import type { RpcHandler } from "./connector-api.ts"; import type { Spinner } from "../ui/spinner.ts"; @@ -775,6 +780,7 @@ export interface TransferParams { sdkWarnings: CallSdkWarnings; log?: VerboseLog; root: string; + notice: NoticeSink; } export interface TransferResult { txHash: string; @@ -794,6 +800,7 @@ export interface DustRegisterOptions { sdkWarnings: CallSdkWarnings; log?: VerboseLog; root: string; + notice: NoticeSink; } export interface DustRegistration { alreadyAvailable: boolean; @@ -823,6 +830,7 @@ export interface ReadOptions { } export interface CachedReadOptions extends ReadOptions { root: string; + notice: NoticeSink; } export interface DustBalance { balance: bigint; @@ -845,6 +853,7 @@ export interface WalletSyncHooks { export interface ShieldedTransferParams extends WalletSyncHooks { seed: Buffer; root: string; + notice: NoticeSink; network: NetworkName; networkConfig: NetworkConfig; recipient: string; @@ -857,6 +866,7 @@ export interface ShieldedTransferParams extends WalletSyncHooks { export interface PrepWallet { seed: Buffer; root: string; + notice: NoticeSink; network: NetworkName; networkConfig: NetworkConfig; address: string; @@ -898,6 +908,7 @@ export interface EngineWallet { registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { root: string; + notice: NoticeSink; signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; @@ -910,6 +921,7 @@ export interface EngineWallet { openConnector(options: { seed: Buffer; root: string; + notice: NoticeSink; network: NetworkName; networkConfig: NetworkConfig; address: string; @@ -921,6 +933,7 @@ export interface EngineWallet { serveWallet(options: { seed: Buffer; root: string; + notice: NoticeSink; networkConfig: NetworkConfig; network: NetworkName; address: string; @@ -1221,9 +1234,7 @@ export declare function networkIdForName(name: NetworkName): MidnightNetworkId; ## `@kuiralabs/midnight-cli-core/lib/notices` ```ts -type NoticeSink = (line: string) => void; -export declare function setNoticeSink(next: NoticeSink | null): void; -export declare function notice(line: string): void; +export type NoticeSink = (line: string) => void; ``` ## `@kuiralabs/midnight-cli-core/lib/offer-envelope` @@ -1282,13 +1293,15 @@ import { type EndpointOverrides, type NetworkConfig, type NetworkName } from "./ import type { Spinner } from "../ui/spinner.ts"; import type { CallSdkWarnings } from "./sdk-warnings.ts"; import type { WalletSession } from "./wallet-session.ts"; +import type { Host } from "./host.ts"; export interface PayingTarget { network: NetworkName; root: string; + host: Host; networkConfig: NetworkConfig; endpoints: EndpointOverrides; } -export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string): PayingTarget; +export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string, host: Host): PayingTarget; export interface ServedWallet { port: number; stop: () => Promise; @@ -1345,8 +1358,6 @@ export interface Prompter { export declare class PromptBusyError extends Error { constructor(); } -export declare function setPrompter(next: Prompter | null): void; -export declare function currentPrompter(): Prompter | null; ``` ## `@kuiralabs/midnight-cli-core/lib/reader-cache-files` @@ -1579,6 +1590,7 @@ export declare function clearWalletCache(address: string | undefined, network: s ```ts import { type OpenedConnector, type TransactionDetail } from "./engine.ts"; import type { NetworkConfig, NetworkName } from "./network.ts"; +import type { NoticeSink } from "./notices.ts"; import type { SwapLeg } from "./swap-offer.ts"; import type { OpenOffer } from "./open-offers.ts"; export interface WalletAddresses { @@ -1631,6 +1643,7 @@ export interface OpenWalletSessionOptions { seed: Buffer; network: NetworkName; root: string; + notice: NoticeSink; networkConfig?: NetworkConfig; forceShielded?: boolean; dustWaitMs?: number; diff --git a/packages/cli-core/src/lib/approval.ts b/packages/cli-core/src/lib/approval.ts index 8cbbbba1..65e33575 100644 --- a/packages/cli-core/src/lib/approval.ts +++ b/packages/cli-core/src/lib/approval.ts @@ -1,8 +1,8 @@ // Terminal approval prompts for DApp Connector write operations -// Asks through the prompter the host sets (the CLI's uses readline, per project constraints — no inquirer) +// Asks through the prompter its caller gives (the CLI's uses readline, per project constraints — no inquirer) -import { notice } from './notices.ts'; -import { currentPrompter, PromptBusyError } from './prompter.ts'; +import type { NoticeSink } from './notices.ts'; +import { PromptBusyError, type Prompter } from './prompter.ts'; import { box } from '../ui/format.ts'; import { bold, teal, dim, yellow, green, red } from '../ui/colors.ts'; import type { FeeLimits } from './fee-limits.ts'; @@ -44,6 +44,10 @@ export interface ApprovalOptions { * terminal gets it rejected. */ approveFees?: boolean; + /** Who is asked to approve (the host's prompter); null when nobody can, and every request that needs asking is rejected. */ + prompter: Prompter | null; + /** Where what was approved without asking, and why a request was rejected, is said (the host's notices). */ + notice: NoticeSink; } /** What a server approves without asking, as `mn serve` reports it. */ @@ -62,7 +66,7 @@ export interface ApprovalPolicy { feeLimits?: { maxFeeSpecks: string; maxPending: number }; } -export function describeApprovalPolicy(options: ApprovalOptions, feeLimits: FeeLimits): ApprovalPolicy { +export function describeApprovalPolicy(options: Omit, feeLimits: FeeLimits): ApprovalPolicy { if (options.approveAll) return { reads: 'auto', balancing: 'auto', writes: 'auto' }; if (options.approveFees) { return { @@ -141,7 +145,7 @@ export function renderApprovalBox(request: ApprovalRequest): string { // ── Prompt ── /** What a server without a terminal can do about a request it can't prompt for. */ -function nonInteractiveHint(request: ApprovalRequest, options: ApprovalOptions): string { +function nonInteractiveHint(request: ApprovalRequest, options: Pick): string { if (options.approveFees) { return `--approve-fees approves only paying the Dust fee for an agent's own balanced transaction (and its submit); ${request.method} needs a terminal to approve`; } @@ -163,8 +167,9 @@ function nonInteractiveHint(request: ApprovalRequest, options: ApprovalOptions): */ export async function promptApproval( request: ApprovalRequest, - options: ApprovalOptions = {}, + options: ApprovalOptions, ): Promise { + const { notice } = options; // Auto-approve checks if (options.approveAll) { notice(dim(` Auto-approved: ${request.method}`)); @@ -182,10 +187,10 @@ export async function promptApproval( } // Non-interactive environment — reject by default - const prompter = currentPrompter(); + const { prompter } = options; if (prompter === null || !prompter.isInteractive()) { notice(red(prompter === null - ? ' Cannot prompt for approval: the host set no prompter (setPrompter)' + ? ' Cannot prompt for approval: the host gave no prompter (createHost prompter)' : ' Cannot prompt for approval: stdin is not a TTY')); notice(dim(` ${nonInteractiveHint(request, options)}`)); return 'reject'; diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 2816dd7b..297cbec2 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -11,6 +11,7 @@ import { sdkSetOfNetwork, type NetworkConfig, type NetworkName } from './network import type { CallSdkWarnings } from './sdk-warnings.ts'; import type { VerboseLog } from './verbose.ts'; import type { ApprovalOptions } from './approval.ts'; +import type { NoticeSink } from './notices.ts'; import type { FeeLimits } from './fee-limits.ts'; import type { RpcHandler } from './connector-api.ts'; import type { Spinner } from '../ui/spinner.ts'; @@ -218,6 +219,8 @@ export interface TransferParams { log?: VerboseLog; /** The state root the wallet's caches live under. */ root: string; + /** Where its lines for the person go (the host's notices). */ + notice: NoticeSink; } export interface TransferResult { @@ -248,6 +251,8 @@ export interface DustRegisterOptions { log?: VerboseLog; /** The state root the wallet's caches live under. */ root: string; + /** Where its lines for the person go (the host's notices). */ + notice: NoticeSink; } export interface DustRegistration { @@ -307,6 +312,8 @@ export interface ReadOptions { export interface CachedReadOptions extends ReadOptions { /** The state root the cache lives under. */ root: string; + /** Where its lines for the person go (the host's notices). */ + notice: NoticeSink; } /** A wallet's Dust, as mn's reader found it. */ @@ -355,6 +362,8 @@ export interface ShieldedTransferParams extends WalletSyncHooks { seed: Buffer; /** The state root the wallet's caches and open offers live under. */ root: string; + /** Where its lines for the person go (the host's notices). */ + notice: NoticeSink; network: NetworkName; networkConfig: NetworkConfig; /** The recipient's shielded address on `network`. */ @@ -376,6 +385,8 @@ export interface PrepWallet { seed: Buffer; /** The state root the wallet's caches live under. */ root: string; + /** Where its lines for the person go (the host's notices). */ + notice: NoticeSink; network: NetworkName; networkConfig: NetworkConfig; address: string; @@ -435,15 +446,15 @@ export interface EngineWallet { /** Registers a seed's NIGHT for Dust, unless it has Dust already. */ registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; /** A seed's Dust as a snapshot another wallet restores from. */ - exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { root: string; signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void }): Promise; + exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { root: string; notice: NoticeSink; signal?: AbortSignal; log?: VerboseLog; onProgress?: (eventsApplied: number, maxIdSeen: number) => void }): Promise; /** A test wallet's unshielded NIGHT after a quick sync; its state is saved when it holds some. */ prepNightBalance(wallet: PrepWallet): Promise; /** Makes sure a test wallet has Dust, registering and then waiting up to `waitMs` for it. */ prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAvailable: boolean; dustAvailable: boolean }>; /** The connector over a seed's wallet, synced and its Dust ready, for a command of mn's own. */ - openConnector(options: { seed: Buffer; root: string; network: NetworkName; networkConfig: NetworkConfig; address: string; syncMode: 'full' | 'lite'; dustWaitMs?: number; signal?: AbortSignal; onMessage: (message: string) => void }): Promise; + openConnector(options: { seed: Buffer; root: string; notice: NoticeSink; network: NetworkName; networkConfig: NetworkConfig; address: string; syncMode: 'full' | 'lite'; dustWaitMs?: number; signal?: AbortSignal; onMessage: (message: string) => void }): Promise; /** Syncs a seed's wallet strictly for mn serve and runs `serve` with it; the wallet stops when `serve` ends. */ - serveWallet(options: { seed: Buffer; root: string; networkConfig: NetworkConfig; network: NetworkName; address: string; syncMode: 'full' | 'lite' } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; + serveWallet(options: { seed: Buffer; root: string; notice: NoticeSink; networkConfig: NetworkConfig; network: NetworkName; address: string; syncMode: 'full' | 'lite' } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; } /** One SDK set, as mn uses it. */ diff --git a/packages/cli-core/src/lib/notices.ts b/packages/cli-core/src/lib/notices.ts index ee98acc4..3b6bf82e 100644 --- a/packages/cli-core/src/lib/notices.ts +++ b/packages/cli-core/src/lib/notices.ts @@ -1,19 +1,8 @@ // Lines a library has for the person at the terminal (a plain-text wallet's -// warning, a connector's progress) go here instead of to stderr. The shell -// and the MCP server send them to stderr; a consumer sends them wherever it -// likes, and with no sink they are dropped. The library never writes to the -// terminal itself. +// warning, a connector's progress) go to the notices its caller gives (the +// host's: host.notice) instead of to stderr. The shell and the MCP server send +// them to stderr; a consumer sends them wherever it likes. The library never +// writes to the terminal itself. -type NoticeSink = (line: string) => void; - -let sink: NoticeSink | null = null; - -/** Where notices go from now on; null drops them. */ -export function setNoticeSink(next: NoticeSink | null): void { - sink = next; -} - -/** One line for the person at the terminal, already formatted. */ -export function notice(line: string): void { - sink?.(line); -} +/** Where a library's lines for the person go: one line, already formatted. */ +export type NoticeSink = (line: string) => void; diff --git a/packages/cli-core/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts index 7d5d7ca2..2d721628 100644 --- a/packages/cli-core/src/lib/payer.ts +++ b/packages/cli-core/src/lib/payer.ts @@ -9,12 +9,15 @@ import { resolveNetwork } from './resolve-network.ts'; import type { Spinner } from '../ui/spinner.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; import type { WalletSession } from './wallet-session.ts'; +import type { Host } from './host.ts'; -/** The network a command acts on, with its endpoints resolved. */ +/** The network a command acts on, with its endpoints resolved, and the host it runs in. */ export interface PayingTarget { network: NetworkName; /** The state root the command's config, wallets and caches live under. */ root: string; + /** The host the command runs in: who unlocks the paying wallet, and where its notices go. */ + host: Host; networkConfig: NetworkConfig; /** The endpoints given as flags, which a server started for the command must use too. */ endpoints: EndpointOverrides; @@ -25,9 +28,10 @@ export interface PayingTarget { * undeployed (as every other command), then explicit endpoint flags over the * defaults. Without endpoint flags, `undeployed` resolves to whatever local * stack docker shows, which is ambiguous when more than one runs. The saved - * network and endpoints are the config's under the state root `root`. + * network and endpoints are the config's under the state root `root`; the + * command runs in `host`. */ -export function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string): PayingTarget { +export function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string, host: Host): PayingTarget { const network = getFlag(args, 'network'); const endpoints: EndpointOverrides = { node: getFlag(args, 'node'), @@ -39,7 +43,7 @@ export function resolvePayingTarget(args: ParsedArgs, command: string, subcomman configDir: root, }); applyEndpointOverrides(networkConfig, endpoints, name, root); - return { network: name, root, networkConfig, endpoints }; + return { network: name, root, host, networkConfig, endpoints }; } /** A wallet served over the DApp connector's WebSocket, for a script in another process to pay through. */ diff --git a/packages/cli-core/src/lib/prompter.ts b/packages/cli-core/src/lib/prompter.ts index cda8ede0..e8424dd3 100644 --- a/packages/cli-core/src/lib/prompter.ts +++ b/packages/cli-core/src/lib/prompter.ts @@ -1,7 +1,7 @@ -// How a library asks the person a question: through the prompter its host -// sets (the CLI's asks at the terminal, ui/terminal-prompter.ts). A library -// never opens a prompt itself; with no prompter, or one that can't ask, it -// does what it did with no terminal. +// How a library asks the person a question: through the prompter its caller +// gives (the host's: host.prompter; the CLI's asks at the terminal, +// ui/terminal-prompter.ts). A library never opens a prompt itself; with no +// prompter, or one that can't ask, it does what it did with no terminal. export interface Prompter { /** Whether there is someone to answer. */ @@ -20,15 +20,3 @@ export class PromptBusyError extends Error { Object.setPrototypeOf(this, PromptBusyError.prototype); } } - -let current: Prompter | null = null; - -/** The prompter libraries ask through from now on; null for none. */ -export function setPrompter(next: Prompter | null): void { - current = next; -} - -/** The prompter set, if any. */ -export function currentPrompter(): Prompter | null { - return current; -} diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index b3f9e75c..f2ab061d 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -13,6 +13,7 @@ import { engineFor, type DAppConnector, type OpenedConnector, type TransactionDetail } from './engine.ts'; import type { NetworkConfig, NetworkName } from './network.ts'; +import type { NoticeSink } from './notices.ts'; import { resolveNetwork } from './resolve-network.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; import { throwIfCancelled } from './errors.ts'; @@ -223,6 +224,8 @@ export interface OpenWalletSessionOptions { network: NetworkName; /** The state root the wallet's config and caches live under. */ root: string; + /** Where the wallet's lines for the person go (a cache it can't restore from, the connector's waits for Dust). */ + notice: NoticeSink; /** The network's endpoints; when absent, as a command without endpoint flags resolves them (the saved config, then the defaults). */ networkConfig?: NetworkConfig; /** Whether to sync the shielded wallet; off where the network has no shielded faucet, unless forced. */ @@ -249,6 +252,7 @@ export async function openWalletSession(options: OpenWalletSessionOptions): Prom const open = () => engine.wallet.openConnector({ seed, root, + notice: options.notice, network, networkConfig, address: engine.keys.unshieldedAddress(seed, network), diff --git a/packages/engine-beta/api-report.md b/packages/engine-beta/api-report.md index 99f49256..9ee762a8 100644 --- a/packages/engine-beta/api-report.md +++ b/packages/engine-beta/api-report.md @@ -67,6 +67,7 @@ export declare function generateStateScript(opts: StateScript, parts: ScriptPart ## `@kuiralabs/midnight-engine-beta/dapp-connector` ```ts +import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { FacadeState, WalletEntry } from "@midnightntwrk/wallet-sdk-facade"; import { type FacadeBundle } from "./facade.ts"; import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; @@ -80,6 +81,7 @@ export interface DAppConnectorOptions { bundle: FacadeBundle; networkConfig: NetworkConfig; approvalOptions: ApprovalOptions; + notice: NoticeSink; feeLimits?: FeeLimits; openOffers?: () => readonly OpenOffer[]; callbacks?: DAppConnectorCallbacks; @@ -199,14 +201,16 @@ export declare function validateDustCacheChainId(network: string, currentChainId import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import { type WalletDataRepository } from "./wallet-data-repository.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustExportOptions { root: string; + notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; repository?: WalletDataRepository; - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; log?: VerboseLog; } export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options: DustExportOptions): Promise; @@ -272,6 +276,7 @@ export declare function DustWallet(configuration: Parameters; +export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, cache?: WalletCacheData | null, log?: VerboseLog): Promise; export interface FacadeDustSnapshot { publicKey: { publicKey: string; @@ -497,6 +502,7 @@ export declare const betaWallet: EngineWallet; ```ts import { Buffer } from "node:buffer"; import * as ledger from "@midnightntwrk/ledger-v9"; +import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { NetworkConfig, NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; import { type FacadeState } from "@midnightntwrk/wallet-sdk-facade"; import { type FacadeBundle, type SyncMode } from "./facade.ts"; @@ -545,6 +551,7 @@ export interface RepoDeps { onProgress?: (applied: number, max: number) => void; onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; root: string; + notice: NoticeSink; log?: VerboseLog; }) => Promise; fetchChainId?: (nodeWsUrl: string) => Promise; @@ -564,7 +571,7 @@ export declare class WalletDataRepository { private readonly tipMemo; constructor(deps?: RepoDeps); private keepCachesOfThisIndexer; - walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise; + walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise; private freshWalletOnDustCheckpoint; dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise; unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; diff --git a/packages/engine-beta/src/dapp-connector.ts b/packages/engine-beta/src/dapp-connector.ts index fe9b22fb..46eaa7e8 100644 --- a/packages/engine-beta/src/dapp-connector.ts +++ b/packages/engine-beta/src/dapp-connector.ts @@ -2,7 +2,7 @@ // Factory function returns a handler map for ws-rpc.ts to dispatch import * as rx from 'rxjs'; -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk-address-format'; import * as ledger from '@midnightntwrk/ledger-v9'; import type { UnboundTransaction } from '@midnightntwrk/wallet-sdk-capabilities/proving'; @@ -41,6 +41,8 @@ export interface DAppConnectorOptions { bundle: FacadeBundle; networkConfig: NetworkConfig; approvalOptions: ApprovalOptions; + /** Where the connector's lines for the person go (the host's notices): reverted transactions, fee estimates, waits for Dust. */ + notice: NoticeSink; /** Under --approve-fees: the most a transaction may cost, and how many may wait unsubmitted. */ feeLimits?: FeeLimits; /** @@ -212,7 +214,7 @@ export function signatureScheme(tag: string): 'schnorr_bip340' { } export function createDAppConnector(options: DAppConnectorOptions): DAppConnector { - const { bundle, networkConfig, approvalOptions, callbacks } = options; + const { bundle, networkConfig, approvalOptions, callbacks, notice } = options; const feeLimits = options.feeLimits ?? DEFAULT_FEE_LIMITS; const { facade, keystore, secretKeys } = bundle; const networkId = getNetworkId(networkConfig.networkId); diff --git a/packages/engine-beta/src/dust-export.ts b/packages/engine-beta/src/dust-export.ts index b4611179..80699521 100644 --- a/packages/engine-beta/src/dust-export.ts +++ b/packages/engine-beta/src/dust-export.ts @@ -22,6 +22,7 @@ import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts' import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -29,6 +30,8 @@ export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export interface DustExportOptions { /** The state root the Dust cache lives under. */ root: string; + /** Where the export's lines for the person go (the host's notices). */ + notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; /** Injectable for tests; defaults to the process-wide repository. */ @@ -39,14 +42,14 @@ export interface DustExportOptions { * The default touches the node relay (building a facade opens its API-WS), so * tests stub this to stay offline. */ - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; /** The call's verbose lines. */ log?: VerboseLog; } /** Build a fresh facade from keys and read its base (empty) dust snapshot. */ -async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog): Promise { - const bundle = await buildFacade(seedBuffer, networkConfig, root, null, log); +async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog): Promise { + const bundle = await buildFacade(seedBuffer, networkConfig, root, notice, null, log); try { return await (bundle.facade as unknown as { dust: { serializeState(): Promise }; @@ -78,12 +81,13 @@ export async function exportDustSnapshot( const view = await repo.dust(seedBuffer, networkConfig, { root: options.root, + notice: options.notice, signal: options.signal, onProgress: options.onProgress, log: options.log, }); - const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.root, options.log); + const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.root, options.notice, options.log); // Overlay whenever at least one event has been folded in. For a wallet with no // dust events yet (lastAppliedEventId -1) the fresh base snapshot is already the diff --git a/packages/engine-beta/src/dust-register.ts b/packages/engine-beta/src/dust-register.ts index 4d30bfaf..d19182d0 100644 --- a/packages/engine-beta/src/dust-register.ts +++ b/packages/engine-beta/src/dust-register.ts @@ -14,7 +14,7 @@ export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight- export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { - const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root } = options; + const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root, notice } = options; const stopListening = sdkWarnings.listen(onSyncWarning); try { const { result, dustBalance } = await defaultRepository().withFacade( @@ -36,6 +36,7 @@ export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, o }, { root, + notice, syncMode: 'lite', requireStrictSync: true, signal, diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts index 80c08532..e5b9d941 100644 --- a/packages/engine-beta/src/facade.ts +++ b/packages/engine-beta/src/facade.ts @@ -1,5 +1,5 @@ import { ShieldedWallet } from '@midnightntwrk/wallet-sdk-shielded'; -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { UnshieldedWallet, createKeystore, @@ -75,12 +75,14 @@ export interface FacadeBundle { * since the last checkpoint, with the Dust checkpoint kept under the state * root `root` bridged in when it is ahead. * - * Its diagnostics go to `log`, the call's verbose lines. + * Its diagnostics go to `log`, the call's verbose lines; a cache it can't + * restore from is said through `notice` before it builds from scratch. */ export async function buildFacade( seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, + notice: NoticeSink, cache?: WalletCacheData | null, log?: VerboseLog, ): Promise { diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index aa670349..86d665d8 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -437,6 +437,7 @@ export async function executeTransfer(params: TransferParams): Promise void; /** The state root of the caches; the native sidecar keeps its checkpoint beside them. */ root: string; + /** Where the read's lines for the person go (the host's notices). */ + notice: NoticeSink; /** The call's verbose lines. */ log?: VerboseLog; }, @@ -231,15 +233,15 @@ export class WalletDataRepository { * read under the state root `root`. Building that new wallet's diagnostics * go to `log`. */ - async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise { return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, root) - ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, root, log); + ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, root, notice, log); } - private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise { const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), root); if (!checkpoint || checkpoint.lastAppliedEventId < 0) return null; - const fresh = await buildFacade(seed, network, root, null, log); + const fresh = await buildFacade(seed, network, root, notice, null, log); try { const { shielded, unshielded, dust } = fresh.facade as unknown as Record<'shielded' | 'unshielded' | 'dust', { serializeState(): Promise }>; const [shieldedState, unshieldedState, dustState] = await Promise.all([shielded.serializeState(), unshielded.serializeState(), dust.serializeState()]); @@ -302,6 +304,7 @@ export class WalletDataRepository { result = await this.fetchDust(seed, network, { root: opts.root, + notice: opts.notice, startFromId, initialState: cached?.state, initialRetention: cached?.retention, @@ -438,7 +441,7 @@ export class WalletDataRepository { // near-tip. Read-only borrowers skip it. if (writeMode && !opts.noPrime && !opts.forceFresh) { try { - await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, notice: opts.notice, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch (err) { // Pre-prime is best-effort — the actual sync below will re-attempt // anyway. Surface the error only via onSyncWarning if anyone cares. @@ -461,8 +464,8 @@ export class WalletDataRepository { throwIfCancelled(opts.signal); const cacheBeforeBuild = opts.forceFresh ? null - : await this.walletStateToRestore(seed, network, networkName, opts.root, opts.log); - bundle = await buildFacade(seed, network, opts.root, cacheBeforeBuild, opts.log); + : await this.walletStateToRestore(seed, network, networkName, opts.root, opts.notice, opts.log); + bundle = await buildFacade(seed, network, opts.root, opts.notice, cacheBeforeBuild, opts.log); try { syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, @@ -485,7 +488,7 @@ export class WalletDataRepository { // Re-prime the dust cache so the next attempt restores from a // current checkpoint instead of a full SDK resync. try { - await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, notice: opts.notice, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch { /* best-effort */ } continue; } @@ -530,7 +533,7 @@ export class WalletDataRepository { await new Promise((r) => setTimeout(r, COLD_START_DELAY_MS)); throwIfCancelled(opts.signal); const retryCache = loadWalletCache(address, networkName, opts.root); - bundle = await buildFacade(seed, network, opts.root, retryCache, opts.log); + bundle = await buildFacade(seed, network, opts.root, opts.notice, retryCache, opts.log); syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, onSyncDetail: opts.onSyncDetail, @@ -699,11 +702,11 @@ let saidWasmDust = false; async function nativeOrWasmDustFetcher( seed: Buffer, network: NetworkConfig, - opts: Parameters[2], + opts: Parameters>[2], ): Promise { if (!nativeDustSyncAvailable() && opts.startFromId === 0 && !saidWasmDust) { saidWasmDust = true; - notice(` Reading ${network.networkId}'s Dust history in WASM: no native sidecar runs ledger 9 yet, so a first sync takes a few minutes (about 2.5 on stagenet), then it is cached.`); + opts.notice(` Reading ${network.networkId}'s Dust history in WASM: no native sidecar runs ledger 9 yet, so a first sync takes a few minutes (about 2.5 on stagenet), then it is cached.`); } if (nativeDustSyncAvailable()) { try { diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index 369e2d4c..cc8ee2b2 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -35,7 +35,7 @@ import { createDAppConnector } from './dapp-connector.ts'; const HOUR_MS = 60 * 60 * 1000; async function shieldedTransfer(params: ShieldedTransferParams): Promise { - const { seed, root, network, networkConfig, amount, progress, signal } = params; + const { seed, root, notice, network, networkConfig, amount, progress, signal } = params; const networkId = getNetworkId(networkConfig.networkId); const nightToken = ledger.unshieldedToken().raw; const receiverAddress = decodeShieldedAddress(params.recipient, network); @@ -99,6 +99,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise }, { root, + notice, syncMode: 'full', log: params.log, requireStrictSync: true, @@ -113,7 +114,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise /** The wallet a test's preparation checks, built from its saved state and synced quickly (no shielded sync). */ async function syncedPrepWallet(wallet: PrepWallet, reportSync: boolean, beforeSync?: () => void) { bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS, wallet.root); - const bundle = await buildFacade(wallet.seed, wallet.networkConfig, wallet.root, loadWalletCache(wallet.address, wallet.network, wallet.root)); + const bundle = await buildFacade(wallet.seed, wallet.networkConfig, wallet.root, wallet.notice, loadWalletCache(wallet.address, wallet.network, wallet.root)); try { beforeSync?.(); const state = await startAndSyncFacade(bundle, { @@ -178,7 +179,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv } const openConnector: EngineWallet['openConnector'] = async (options): Promise => { - const { seed, root, network, networkConfig, address, syncMode, signal, onMessage } = options; + const { seed, root, notice, network, networkConfig, address, syncMode, signal, onMessage } = options; // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig, undefined, signal); // A failure before the connector is handed back stops what was started, so @@ -196,12 +197,12 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise { - const { seed, root, networkConfig, network, address, syncMode } = options; + const { seed, root, notice, networkConfig, network, address, syncMode } = options; // The repository owns validating the caches, priming Dust, building the // facade, syncing (with retries) and stopping it. Its save is skipped: mn // serve saves only when no transaction is pending, since the SDK drops @@ -279,6 +282,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { bundle, networkConfig, approvalOptions, + notice, feeLimits, callbacks, // Reads answer from the state this sync ended on, and from every later @@ -291,6 +295,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { return serve(session); }, { root, + notice, syncMode, // serve accepts write requests from dApps — must be strictly synced. requireStrictSync: true, diff --git a/packages/engine-rc/api-report.md b/packages/engine-rc/api-report.md index f37d4d91..c78b63b0 100644 --- a/packages/engine-rc/api-report.md +++ b/packages/engine-rc/api-report.md @@ -67,6 +67,7 @@ export declare function generateStateScript(opts: StateScript, parts: ScriptPart ## `@kuiralabs/midnight-engine-rc/dapp-connector` ```ts +import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { FacadeState, WalletEntry } from "@midnightntwrk/wallet-sdk/facade"; import { type FacadeBundle } from "./facade.ts"; import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; @@ -80,6 +81,7 @@ export interface DAppConnectorOptions { bundle: FacadeBundle; networkConfig: NetworkConfig; approvalOptions: ApprovalOptions; + notice: NoticeSink; feeLimits?: FeeLimits; openOffers?: () => readonly OpenOffer[]; callbacks?: DAppConnectorCallbacks; @@ -199,14 +201,16 @@ export declare function validateDustCacheChainId(network: string, currentChainId import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import { type WalletDataRepository } from "./wallet-data-repository.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustExportOptions { root: string; + notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; repository?: WalletDataRepository; - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; log?: VerboseLog; } export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options: DustExportOptions): Promise; @@ -272,6 +276,7 @@ export declare function DustWallet(configuration: Parameters; +export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, cache?: WalletCacheData | null, log?: VerboseLog): Promise; export interface FacadeDustSnapshot { publicKey: { publicKey: string; @@ -514,6 +519,7 @@ import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-ca import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subscription"; import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; +import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; @@ -574,7 +580,7 @@ export declare class WalletDataRepository { private readonly tipMemo; constructor(deps?: RepoDeps); private keepCachesOfThisIndexer; - walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise; + walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise; private freshWalletOnDustCheckpoint; dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise; unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; diff --git a/packages/engine-rc/src/dapp-connector.ts b/packages/engine-rc/src/dapp-connector.ts index f575c922..801a277a 100644 --- a/packages/engine-rc/src/dapp-connector.ts +++ b/packages/engine-rc/src/dapp-connector.ts @@ -2,7 +2,7 @@ // Factory function returns a handler map for ws-rpc.ts to dispatch import * as rx from 'rxjs'; -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { TransactionStage, WalletTransaction } from '@midnightntwrk/wallet-sdk'; import type { FacadeState, WalletEntry } from '@midnightntwrk/wallet-sdk/facade'; @@ -42,6 +42,8 @@ export interface DAppConnectorOptions { bundle: FacadeBundle; networkConfig: NetworkConfig; approvalOptions: ApprovalOptions; + /** Where the connector's lines for the person go (the host's notices): reverted transactions, fee estimates, waits for Dust. */ + notice: NoticeSink; /** Under --approve-fees: the most a transaction may cost, and how many may wait unsubmitted. */ feeLimits?: FeeLimits; /** @@ -210,7 +212,7 @@ export function signatureScheme(tag: string): 'schnorr_bip340' { } export function createDAppConnector(options: DAppConnectorOptions): DAppConnector { - const { bundle, networkConfig, approvalOptions, callbacks } = options; + const { bundle, networkConfig, approvalOptions, callbacks, notice } = options; const feeLimits = options.feeLimits ?? DEFAULT_FEE_LIMITS; const { facade, keystore } = bundle; const networkId = getNetworkId(networkConfig.networkId); diff --git a/packages/engine-rc/src/dust-export.ts b/packages/engine-rc/src/dust-export.ts index b4611179..80699521 100644 --- a/packages/engine-rc/src/dust-export.ts +++ b/packages/engine-rc/src/dust-export.ts @@ -22,6 +22,7 @@ import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts' import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -29,6 +30,8 @@ export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; export interface DustExportOptions { /** The state root the Dust cache lives under. */ root: string; + /** Where the export's lines for the person go (the host's notices). */ + notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; /** Injectable for tests; defaults to the process-wide repository. */ @@ -39,14 +42,14 @@ export interface DustExportOptions { * The default touches the node relay (building a facade opens its API-WS), so * tests stub this to stay offline. */ - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog) => Promise; + buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; /** The call's verbose lines. */ log?: VerboseLog; } /** Build a fresh facade from keys and read its base (empty) dust snapshot. */ -async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, log?: VerboseLog): Promise { - const bundle = await buildFacade(seedBuffer, networkConfig, root, null, log); +async function defaultBuildBaseDust(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog): Promise { + const bundle = await buildFacade(seedBuffer, networkConfig, root, notice, null, log); try { return await (bundle.facade as unknown as { dust: { serializeState(): Promise }; @@ -78,12 +81,13 @@ export async function exportDustSnapshot( const view = await repo.dust(seedBuffer, networkConfig, { root: options.root, + notice: options.notice, signal: options.signal, onProgress: options.onProgress, log: options.log, }); - const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.root, options.log); + const baseDust = await (options.buildBaseDust ?? defaultBuildBaseDust)(seedBuffer, networkConfig, options.root, options.notice, options.log); // Overlay whenever at least one event has been folded in. For a wallet with no // dust events yet (lastAppliedEventId -1) the fresh base snapshot is already the diff --git a/packages/engine-rc/src/dust-register.ts b/packages/engine-rc/src/dust-register.ts index 4d30bfaf..d19182d0 100644 --- a/packages/engine-rc/src/dust-register.ts +++ b/packages/engine-rc/src/dust-register.ts @@ -14,7 +14,7 @@ export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight- export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { - const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root } = options; + const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root, notice } = options; const stopListening = sdkWarnings.listen(onSyncWarning); try { const { result, dustBalance } = await defaultRepository().withFacade( @@ -36,6 +36,7 @@ export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, o }, { root, + notice, syncMode: 'lite', requireStrictSync: true, signal, diff --git a/packages/engine-rc/src/facade.ts b/packages/engine-rc/src/facade.ts index 14454a2f..5f01127c 100644 --- a/packages/engine-rc/src/facade.ts +++ b/packages/engine-rc/src/facade.ts @@ -1,5 +1,5 @@ import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { UnshieldedWallet, createKeystore, @@ -74,12 +74,14 @@ export interface FacadeBundle { * since the last checkpoint, with the Dust checkpoint kept under the state * root `root` bridged in when it is ahead. * - * Its diagnostics go to `log`, the call's verbose lines. + * Its diagnostics go to `log`, the call's verbose lines; a cache it can't + * restore from is said through `notice` before it builds from scratch. */ export async function buildFacade( seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, + notice: NoticeSink, cache?: WalletCacheData | null, log?: VerboseLog, ): Promise { diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index 3ee7d20f..f0d64504 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -436,6 +436,7 @@ export async function executeTransfer(params: TransferParams): Promise { + async walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise { return loadWalletCache(deriveUnshieldedAddress(seed, networkName), networkName, root) - ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, root, log); + ?? await this.freshWalletOnDustCheckpoint(seed, network, networkName, root, notice, log); } - private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, log?: VerboseLog): Promise { + private async freshWalletOnDustCheckpoint(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise { const checkpoint = loadDustCache(networkName, dustPublicKeyHexFromSeed(seed), root); if (!checkpoint || checkpoint.lastAppliedEventId < 0) return null; - const fresh = await buildFacade(seed, network, root, null, log); + const fresh = await buildFacade(seed, network, root, notice, null, log); try { const { shielded, unshielded, dust } = fresh.facade as unknown as Record<'shielded' | 'unshielded' | 'dust', { serializeState(): Promise }>; const [shieldedState, unshieldedState, dustState] = await Promise.all([shielded.serializeState(), unshielded.serializeState(), dust.serializeState()]); @@ -437,7 +438,7 @@ export class WalletDataRepository { // near-tip. Read-only borrowers skip it. if (writeMode && !opts.noPrime && !opts.forceFresh) { try { - await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, notice: opts.notice, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch (err) { // Pre-prime is best-effort — the actual sync below will re-attempt // anyway. Surface the error only via onSyncWarning if anyone cares. @@ -460,8 +461,8 @@ export class WalletDataRepository { throwIfCancelled(opts.signal); const cacheBeforeBuild = opts.forceFresh ? null - : await this.walletStateToRestore(seed, network, networkName, opts.root, opts.log); - bundle = await buildFacade(seed, network, opts.root, cacheBeforeBuild, opts.log); + : await this.walletStateToRestore(seed, network, networkName, opts.root, opts.notice, opts.log); + bundle = await buildFacade(seed, network, opts.root, opts.notice, cacheBeforeBuild, opts.log); try { syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, @@ -484,7 +485,7 @@ export class WalletDataRepository { // Re-prime the dust cache so the next attempt restores from a // current checkpoint instead of a full SDK resync. try { - await this.dust(seed, network, { root: opts.root, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); + await this.dust(seed, network, { root: opts.root, notice: opts.notice, signal: opts.signal, onStatus: opts.onStatus, log: opts.log }); } catch { /* best-effort */ } continue; } @@ -529,7 +530,7 @@ export class WalletDataRepository { await new Promise((r) => setTimeout(r, COLD_START_DELAY_MS)); throwIfCancelled(opts.signal); const retryCache = loadWalletCache(address, networkName, opts.root); - bundle = await buildFacade(seed, network, opts.root, retryCache, opts.log); + bundle = await buildFacade(seed, network, opts.root, opts.notice, retryCache, opts.log); syncedState = await startAndSyncFacade(bundle, { onProgress: opts.onSyncProgress, onSyncDetail: opts.onSyncDetail, diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index a47732cd..70f689f3 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -35,7 +35,7 @@ import { createDAppConnector } from './dapp-connector.ts'; const HOUR_MS = 60 * 60 * 1000; async function shieldedTransfer(params: ShieldedTransferParams): Promise { - const { seed, root, network, networkConfig, amount, progress, signal } = params; + const { seed, root, notice, network, networkConfig, amount, progress, signal } = params; const networkId = getNetworkId(networkConfig.networkId); const nightToken = ledger.unshieldedToken().raw; const receiverAddress = decodeShieldedAddress(params.recipient, network); @@ -98,6 +98,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise }, { root, + notice, syncMode: 'full', log: params.log, requireStrictSync: true, @@ -112,7 +113,7 @@ async function shieldedTransfer(params: ShieldedTransferParams): Promise /** The wallet a test's preparation checks, built from its saved state and synced quickly (no shielded sync). */ async function syncedPrepWallet(wallet: PrepWallet, reportSync: boolean, beforeSync?: () => void) { bindCachesToIndexer(wallet.network, wallet.networkConfig.indexerWS, wallet.root); - const bundle = await buildFacade(wallet.seed, wallet.networkConfig, wallet.root, loadWalletCache(wallet.address, wallet.network, wallet.root)); + const bundle = await buildFacade(wallet.seed, wallet.networkConfig, wallet.root, wallet.notice, loadWalletCache(wallet.address, wallet.network, wallet.root)); try { beforeSync?.(); const state = await startAndSyncFacade(bundle, { @@ -177,7 +178,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv } const openConnector: EngineWallet['openConnector'] = async (options): Promise => { - const { seed, root, network, networkConfig, address, syncMode, signal, onMessage } = options; + const { seed, root, notice, network, networkConfig, address, syncMode, signal, onMessage } = options; // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig, undefined, signal); // A failure before the connector is handed back stops what was started, so @@ -195,12 +196,12 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise { - const { seed, root, networkConfig, network, address, syncMode } = options; + const { seed, root, notice, networkConfig, network, address, syncMode } = options; // The repository owns validating the caches, priming Dust, building the // facade, syncing (with retries) and stopping it. Its save is skipped: mn // serve saves only when no transaction is pending, since the SDK drops @@ -278,6 +281,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { bundle, networkConfig, approvalOptions, + notice, feeLimits, callbacks, // Reads answer from the state this sync ended on, and from every later @@ -290,6 +294,7 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { return serve(session); }, { root, + notice, syncMode, // serve accepts write requests from dApps — must be strictly synced. requireStrictSync: true, diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index a0174002..cc2a7384 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -83,24 +83,19 @@ export const ALLOWED = { // why. A call's state is allowed only until it moves into the call's context; what is shared on purpose holds no call's state. export const ALLOWED_STATE = { // Shared on purpose: none holds a call's state. - 'lib/passphrase.ts': { unlocked: 'shared on purpose: the passphrase this process has unlocked, by state root (one prompt per run)' }, 'engine/rc/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, 'engine/beta/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls', saidWasmDust: 'shared on purpose: the WASM Dust notice is said once per process', }, 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, - 'lib/ws-rpc.ts': { connectionCounter: 'shared on purpose: the RPC connection id counter, unique across servers in the process' }, 'lib/engine.ts': { loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)', loader: 'shared on purpose: the host sets the engine loader once', preferred: 'shared on purpose: the set work every set does alike loads while no engine is loaded, the set of the call it runs for', }, - 'lib/wallet-config.ts': { warnedPlain: 'shared on purpose: each plain-text wallet is warned about once per run' }, - // The host sources, set once by the host at start (handlers see them through the context). + // The host source, set once by the host at start (handlers see it through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, - 'lib/notices.ts': { sink: 'shared on purpose: the host sets the notice sink once' }, - 'lib/prompter.ts': { current: 'shared on purpose: the host sets the prompter once' }, }; /** diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index dab1fcf0..e2be42e7 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -22,6 +22,10 @@ import { createPendingDevice, openAccountKey, ownDeviceCode, sealedDeviceList } import { parseDeviceCode } from '../lib/grant/device-code.ts'; import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStatePassword } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -37,11 +41,11 @@ let there: string; let fromDir: string; let toDir: string; let backup: string; -const source = (passphrase = PASSPHRASE) => ({ env: { [PASSPHRASE_ENV]: passphrase }, prompter: null }); +const source = (passphrase = PASSPHRASE) => ({ env: { [PASSPHRASE_ENV]: passphrase } }); const accountsOf = (home: string) => path.join(home, '.midnight', 'accounts', 'undeployed', 'alice'); const privateStateIn = async (home: string, dir: string) => { - const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), source: source() }); + const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: source() }); const providers = accountProviders(account.context, wallet, privateStateLocationOf(dir, () => account.location.password() as string)); providers.privateStateProvider.setContractAddress(ACCOUNT); return { account, privateState: providers.privateStateProvider }; @@ -87,7 +91,7 @@ describe("an account's backup", () => { establishPassphrase(stateRootIn(there), PASSPHRASE); expect(await importAccount(toDir, 'undeployed', PASSPHRASE, backup)).toEqual({ contractAddress: ACCOUNT }); const { account, privateState } = await privateStateIn(there, toDir); - const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), source: source() }); + const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), host, source: source() }); expect(account.store.readOwner()).toEqual(RECORD); expect(account.store.readRoster()).toEqual(ROSTER); expect(account.keys.read()?.pk).toEqual(original.keys.read()?.pk); @@ -117,7 +121,7 @@ describe("a backup made for another device", () => { await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, { forDevice: parseDeviceCode(pendingCode) }); await importAccount(toDir, 'undeployed', PASSPHRASE, backup); const { account, privateState } = await privateStateIn(there, toDir); - const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), source: source() }); + const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), host, source: source() }); expect(account.store.readOwner()).toEqual(RECORD); expect(account.keys.read()?.pk).toEqual(pending.pk); expect(account.keys.read()?.pk).not.toEqual(original.keys.read()?.pk); diff --git a/src/__tests__/approval.test.ts b/src/__tests__/approval.test.ts index b9c6b78f..297a1f84 100644 --- a/src/__tests__/approval.test.ts +++ b/src/__tests__/approval.test.ts @@ -1,8 +1,7 @@ import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; -import { setPrompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { PassThrough } from 'node:stream'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describeApprovalPolicy, renderApprovalBox, @@ -153,18 +152,13 @@ describe('approval', () => { details: [], }; - // What approval says goes out as notices; with no prompter set, there is no terminal to ask at. + // What approval says goes out as the notices it is given; with no prompter, there is no terminal to ask at. let stderrOutput: string[]; + let asker: { prompter: Prompter | null; notice: (line: string) => void }; beforeEach(() => { stderrOutput = []; - setNoticeSink((line) => stderrOutput.push(line + '\n')); - setPrompter(null); - }); - - afterEach(() => { - setNoticeSink(null); - setPrompter(null); + asker = { prompter: null, notice: (line) => stderrOutput.push(line + '\n') }; }); /** A terminal that answers through a stream, and the stream to type into. */ @@ -174,17 +168,17 @@ describe('approval', () => { const output = new PassThrough(); shown = ''; output.on('data', (chunk: Buffer) => { shown += chunk.toString('utf8'); }); - setPrompter(createTerminalPrompter({ input, output, isTTY: true })); + asker.prompter = createTerminalPrompter({ input, output, isTTY: true }); return input; }; it('auto-approves when approveAll is true', async () => { - const result = await promptApproval(baseRequest, { approveAll: true }); + const result = await promptApproval(baseRequest, { ...asker, approveAll: true }); expect(result).toBe('approve'); }); it('logs auto-approval for approveAll', async () => { - await promptApproval(baseRequest, { approveAll: true }); + await promptApproval(baseRequest, { ...asker, approveAll: true }); const written = stripAnsi(stderrOutput.join('')); expect(written).toContain('Auto-approved: makeTransfer'); }); @@ -195,7 +189,7 @@ describe('approval', () => { network: 'undeployed', details: [], }; - const result = await promptApproval(readRequest, { autoApproveReads: true }); + const result = await promptApproval(readRequest, { ...asker, autoApproveReads: true }); expect(result).toBe('approve'); }); @@ -205,7 +199,7 @@ describe('approval', () => { network: 'undeployed', details: [], }; - await promptApproval(readRequest, { autoApproveReads: true }); + await promptApproval(readRequest, { ...asker, autoApproveReads: true }); const written = stripAnsi(stderrOutput.join('')); expect(written).toContain('Auto-approved (read-only)'); }); @@ -217,7 +211,7 @@ describe('approval', () => { 'prompts for %s even with autoApproveReads (no terminal: rejected), naming the flags that would approve it', async (method) => { try { - const result = await promptApproval({ method, network: 'undeployed', details: [] }, { autoApproveReads: true }); + const result = await promptApproval({ method, network: 'undeployed', details: [] }, { ...asker, autoApproveReads: true }); expect(result).toBe('reject'); const written = stripAnsi(stderrOutput.join('')); expect(written).not.toContain('Auto-approved'); @@ -228,7 +222,7 @@ describe('approval', () => { ); it.each(['balanceUnsealedTransaction', 'balanceSealedTransaction'])('approves %s with --approve-all', async (method) => { - expect(await promptApproval({ method, network: 'undeployed', details: [] }, { approveAll: true, autoApproveReads: true })).toBe('approve'); + expect(await promptApproval({ method, network: 'undeployed', details: [] }, { ...asker, approveAll: true, autoApproveReads: true })).toBe('approve'); }); it('does not auto-approve balancing when autoApproveReads is false', async () => { @@ -238,14 +232,14 @@ describe('approval', () => { network: 'undeployed', details: [], }; - const result = await promptApproval(prepRequest, { autoApproveReads: false }); + const result = await promptApproval(prepRequest, { ...asker, autoApproveReads: false }); expect(result).toBe('reject'); // falls through to non-TTY rejection }); it('does not auto-approve write methods when only autoApproveReads is set', async () => { // Non-TTY stdin will cause immediate rejection - const result = await promptApproval(baseRequest, { autoApproveReads: true }); + const result = await promptApproval(baseRequest, { ...asker, autoApproveReads: true }); expect(result).toBe('reject'); }); @@ -256,7 +250,7 @@ describe('approval', () => { it.each(['balanceUnsealedTransaction', 'balanceSealedTransaction', 'submitTransaction'])( 'auto-approves a fee-only %s and says why', async (method) => { - const result = await promptApproval({ ...baseRequest, method, feeOnly: true }, { approveFees: true }); + const result = await promptApproval({ ...baseRequest, method, feeOnly: true }, { ...asker, approveFees: true }); expect(result).toBe('approve'); expect(stripAnsi(stderrOutput.join(''))).toContain(`Auto-approved (fee-only): ${method}`); }, @@ -265,21 +259,21 @@ describe('approval', () => { it.each(['makeTransfer', 'makeIntent', 'signData', 'submitTransaction', 'balanceUnsealedTransaction'])( 'rejects %s when it is not fee-only', async (method) => { - const result = await promptApproval({ ...baseRequest, method }, { approveFees: true }); + const result = await promptApproval({ ...baseRequest, method }, { ...asker, approveFees: true }); expect(result).toBe('reject'); }, ); it('grants nothing from a fee-only request when the server was not started with --approve-fees', async () => { - const result = await promptApproval({ ...baseRequest, method: 'submitTransaction', feeOnly: true }, {}); + const result = await promptApproval({ ...baseRequest, method: 'submitTransaction', feeOnly: true }, asker); expect(result).toBe('reject'); }); }); it('rejects when stdin is not a TTY', async () => { - setPrompter(createTerminalPrompter({ input: new PassThrough(), output: new PassThrough(), isTTY: false })); + asker.prompter = createTerminalPrompter({ input: new PassThrough(), output: new PassThrough(), isTTY: false }); - const result = await promptApproval(baseRequest); + const result = await promptApproval(baseRequest, asker); expect(result).toBe('reject'); const written = stripAnsi(stderrOutput.join('')); @@ -287,23 +281,23 @@ describe('approval', () => { }); it('rejects when the host set no prompter, saying so', async () => { - const result = await promptApproval(baseRequest); + const result = await promptApproval(baseRequest, asker); expect(result).toBe('reject'); const written = stripAnsi(stderrOutput.join('')); - expect(written).toContain('Cannot prompt for approval: the host set no prompter (setPrompter)'); + expect(written).toContain('Cannot prompt for approval: the host gave no prompter (createHost prompter)'); }); describe('without a terminal, the hint names what the server could have been started with', () => { it('suggests --approve-all, or --approve-fees for a fee wallet, on a server with neither', async () => { - expect(await promptApproval(baseRequest)).toBe('reject'); + expect(await promptApproval(baseRequest, asker)).toBe('reject'); const written = stripAnsi(stderrOutput.join('')); expect(written).toContain('makeTransfer needs a terminal to approve: use --approve-all for non-interactive environments, or --approve-fees for a fee wallet'); }); it('on a fee wallet, says the request is outside --approve-fees and names the method', async () => { - expect(await promptApproval(baseRequest, { approveFees: true })).toBe('reject'); + expect(await promptApproval(baseRequest, { ...asker, approveFees: true })).toBe('reject'); const written = stripAnsi(stderrOutput.join('')); expect(written).toContain("--approve-fees approves only paying the Dust fee for an agent's own balanced transaction"); expect(written).toContain('makeTransfer needs a terminal to approve'); @@ -313,10 +307,10 @@ describe('approval', () => { it('rejects concurrent prompts when one is already active', async () => { const input = terminal(); - const first = promptApproval(baseRequest); + const first = promptApproval(baseRequest, asker); // The second call rejects at once while the first is waiting for its answer. - expect(await promptApproval(baseRequest)).toBe('reject'); + expect(await promptApproval(baseRequest, asker)).toBe('reject'); expect(stripAnsi(stderrOutput.join(''))).toContain('another approval prompt is active'); input.write('a\n'); @@ -325,7 +319,7 @@ describe('approval', () => { it('asks at the terminal, showing the request: Enter approves, r rejects, and an ended input rejects', async () => { let input = terminal(); - const approving = promptApproval(baseRequest); + const approving = promptApproval(baseRequest, asker); input.write('\n'); expect(await approving).toBe('approve'); // The request is shown as part of the question, whatever the host does with notices. @@ -334,18 +328,21 @@ describe('approval', () => { expect(stderrOutput.join('')).not.toContain('makeTransfer'); input = terminal(); - const rejecting = promptApproval(baseRequest); + const rejecting = promptApproval(baseRequest, asker); input.write('r\n'); expect(await rejecting).toBe('reject'); input = terminal(); - const ended = promptApproval(baseRequest); + const ended = promptApproval(baseRequest, asker); input.end(); expect(await ended).toBe('reject'); }); }); }); +/** What a server is started with: the approval options but who asks and where it is said. */ +type ApprovalFlags = Omit; + describe('describeApprovalPolicy (what mn serve reports, in its header and --json)', () => { const limits = { maxFeeSpecks: 10n ** 15n / 2n, maxPending: 3 }; @@ -366,10 +363,8 @@ describe('describeApprovalPolicy (what mn serve reports, in its header and --jso describe('matches what promptApproval decides without a terminal', () => { // No prompter: no terminal to ask at. What approval says is dropped. - beforeEach(() => setPrompter(null)); - - const decide = (method: string, options: ApprovalOptions, feeOnly = false) => - promptApproval({ method, network: 'undeployed', details: [], feeOnly }, options); + const decide = (method: string, flags: ApprovalFlags, feeOnly = false) => + promptApproval({ method, network: 'undeployed', details: [], feeOnly }, { ...flags, prompter: null, notice: () => {} }); // What each claim means for a request of that kind: 'auto' approves anything, // 'fee-only' approves only a fee-only request, 'prompt' approves nothing. const expectedFor = (claim: string, feeOnly: boolean) => @@ -380,7 +375,7 @@ describe('describeApprovalPolicy (what mn serve reports, in its header and --jso [{ approveFees: true, autoApproveReads: true }], [{ autoApproveReads: true }], [{}], - ] as Array<[ApprovalOptions]>)('%j', async (options) => { + ] as Array<[ApprovalFlags]>)('%j', async (options) => { const policy = describeApprovalPolicy(options, limits); for (const feeOnly of [false, true]) { for (const method of ['balanceUnsealedTransaction', 'balanceSealedTransaction']) { diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 01300443..48416372 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -16,7 +16,7 @@ import * as path from 'node:path'; import { Buffer } from 'node:buffer'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; -import { setPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { establishPassphrase, isPassphraseSet } from '../lib/passphrase.ts'; import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; @@ -33,6 +33,7 @@ import cacheCommand from '../commands/cache.ts'; import testCommand from '../commands/test.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { testHost } from './helpers/test-host.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; @@ -53,7 +54,6 @@ beforeEach(() => { afterEach(() => { io.restore(); - setPrompter(null); process.env.HOME = originalHome; if (originalPassphrase === undefined) delete process.env.MN_PASSPHRASE; else process.env.MN_PASSPHRASE = originalPassphrase; @@ -231,10 +231,9 @@ describe('commands that write check the call before each whole write', () => { it('generate: cancelled while the passphrase is asked for, it writes no wallet', async () => { const call = new AbortController(); const prompter = cancellingPrompter(call); - setPrompter(prompter); const target = path.join(home, 'legacy-wallet.json'); - await expect(cliCall(generateCommand, parseArgs(['generate', '--output', target, '--json']), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(cliCall(generateCommand, parseArgs(['generate', '--output', target, '--json']), { signal: call.signal, host: testHost({ prompter }) })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(prompter.asked).toBeGreaterThan(0); expect(fs.existsSync(target)).toBe(false); @@ -245,9 +244,8 @@ describe('commands that write check the call before each whole write', () => { it('wallet generate: cancelled while the passphrase is asked for, it writes no wallet', async () => { const call = new AbortController(); const prompter = cancellingPrompter(call); - setPrompter(prompter); - await expect(cliCall(walletCommand, parseArgs(['wallet', 'generate', 'alice', '--json']), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(cliCall(walletCommand, parseArgs(['wallet', 'generate', 'alice', '--json']), { signal: call.signal, host: testHost({ prompter }) })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(prompter.asked).toBeGreaterThan(0); expect(fs.existsSync(path.join(stateRootIn(home), 'wallets', 'alice.json'))).toBe(false); @@ -269,9 +267,8 @@ describe('commands that write check the call before each whole write', () => { it('cancelled while the passphrase is asked for: no wallet is sealed', async () => { const files = [plainWallet('alice', 'a1'), plainWallet('bob', 'b2')]; const call = new AbortController(); - setPrompter(cancellingPrompter(call)); - await expect(cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { signal: call.signal, host: testHost({ prompter: cancellingPrompter(call) }) })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(await Promise.all(files.map(isSealed))).toEqual([false, false]); expect(io.stdout()).toBe(''); @@ -321,9 +318,8 @@ describe('commands that write check the call before each whole write', () => { fs.mkdirSync(path.dirname(cache), { recursive: true }); fs.writeFileSync(cache, '{}'); const call = new AbortController(); - setPrompter(cancellingPrompter(call)); - await expect(cliCall(cacheCommand, parseArgs(['cache', 'clear', '--wallet', 'alice', '--network', 'undeployed', '--json']), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(cliCall(cacheCommand, parseArgs(['cache', 'clear', '--wallet', 'alice', '--network', 'undeployed', '--json']), { signal: call.signal, host: testHost({ prompter: cancellingPrompter(call) }) })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(fs.existsSync(cache)).toBe(true); expect(io.stdout()).toBe(''); diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 77e632a1..c87aab7b 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -15,6 +15,10 @@ import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -45,7 +49,7 @@ describe('deployContract', () => { const said: string[] = []; await expect(deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home)), + target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host), wallet: 'nobody', // Never reached: serving would be the step after the funds check. payer: servePayerAt(1), @@ -66,7 +70,7 @@ describe('deployContract', () => { const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); await expect(deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home)), + target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host), wallet: 'external', payer: ownPayer, progress: () => silentSpinner(), @@ -91,7 +95,7 @@ describe('deployContract', () => { const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); await expect(deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home)), + target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host), wallet: 'external', payer: ownPayer, progress: () => silentSpinner(), diff --git a/src/__tests__/dev-keys.test.ts b/src/__tests__/dev-keys.test.ts index 2863717d..ccfb4adb 100644 --- a/src/__tests__/dev-keys.test.ts +++ b/src/__tests__/dev-keys.test.ts @@ -34,7 +34,7 @@ describe('startKeyDispatcher', () => { it('returns a no-op dispatcher when stdin is not a TTY', async () => { (process.stdin as any).isTTY = false; const { startKeyDispatcher } = await import('../ui/dev-keys.ts'); - const d = startKeyDispatcher({ actions: { d: () => {} }, onInterrupt: () => {} }); + const d = startKeyDispatcher({ actions: { d: () => {} }, onInterrupt: () => {}, notice: () => {} }); expect(typeof d.stop).toBe('function'); d.stop(); // must not throw }); @@ -45,6 +45,7 @@ describe('startKeyDispatcher', () => { const d = startKeyDispatcher({ actions: { d: dAction }, onInterrupt: vi.fn(), + notice: () => {}, }); process.stdin.emit('data', 'D'); await Promise.resolve(); @@ -55,7 +56,7 @@ describe('startKeyDispatcher', () => { it('calls onInterrupt on Ctrl+C', async () => { const { startKeyDispatcher } = await loadWithRawSupport(); const onInterrupt = vi.fn(); - const d = startKeyDispatcher({ actions: {}, onInterrupt }); + const d = startKeyDispatcher({ actions: {}, onInterrupt, notice: () => {} }); process.stdin.emit('data', '\u0003'); expect(onInterrupt).toHaveBeenCalledTimes(1); d.stop(); @@ -64,7 +65,7 @@ describe('startKeyDispatcher', () => { it('invokes onUnknown for unbound keys', async () => { const { startKeyDispatcher } = await loadWithRawSupport(); const onUnknown = vi.fn(); - const d = startKeyDispatcher({ actions: { d: () => {} }, onInterrupt: () => {}, onUnknown }); + const d = startKeyDispatcher({ actions: { d: () => {} }, onInterrupt: () => {}, onUnknown, notice: () => {} }); process.stdin.emit('data', 'x'); expect(onUnknown).toHaveBeenCalledWith('x'); d.stop(); @@ -77,6 +78,7 @@ describe('startKeyDispatcher', () => { actions: { d: async () => { throw new Error('boom'); } }, onInterrupt: () => {}, onError, + notice: () => {}, }); process.stdin.emit('data', 'd'); // Wait for the microtask queue to drain so the promise catch fires. @@ -89,7 +91,7 @@ describe('startKeyDispatcher', () => { it('stop() is idempotent', async () => { const { startKeyDispatcher } = await loadWithRawSupport(); - const d = startKeyDispatcher({ actions: {}, onInterrupt: () => {} }); + const d = startKeyDispatcher({ actions: {}, onInterrupt: () => {}, notice: () => {} }); d.stop(); d.stop(); // should not throw }); diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index e388cdce..69d7b78e 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -141,6 +141,7 @@ describe('exportDustSnapshot', () => { const repo = fakeRepo(fakeDust(ownedState, { lastAppliedEventId: 42, balance: 500n, partial: true })); const res = await exportDustSnapshot(EXPORT_SEED, 'undeployed', EXPORT_NETWORK, { root: EXPORT_TMP, + notice: () => {}, repository: repo, buildBaseDust: async () => baseSnapshot('0'), }); @@ -159,6 +160,7 @@ describe('exportDustSnapshot', () => { const repo = fakeRepo(fakeDust(ownedState, { lastAppliedEventId: 100, eventCount: 100, partial: false })); const res = await exportDustSnapshot(EXPORT_SEED, 'undeployed', EXPORT_NETWORK, { root: EXPORT_TMP, + notice: () => {}, repository: repo, buildBaseDust: async () => baseSnapshot('0'), }); @@ -173,6 +175,7 @@ describe('exportDustSnapshot', () => { const base = baseSnapshot('0'); const res = await exportDustSnapshot(EXPORT_SEED, 'undeployed', EXPORT_NETWORK, { root: EXPORT_TMP, + notice: () => {}, repository: repo, buildBaseDust: async () => base, }); diff --git a/src/__tests__/engine-beta.test.ts b/src/__tests__/engine-beta.test.ts index 56b90341..7be86fb8 100644 --- a/src/__tests__/engine-beta.test.ts +++ b/src/__tests__/engine-beta.test.ts @@ -11,6 +11,7 @@ import type { FacadeBundle } from '@kuiralabs/midnight-engine-beta/facade'; import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-beta/derive-address'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { NO_TERMINAL } from './helpers/connector-stub.ts'; // The beta set's own address classes, as the engine resolves them: the // repository's root holds the rc set's. @@ -75,7 +76,7 @@ describe('the beta engine', () => { describe('the beta engine\'s connector', () => { it('refuses transaction work before the wallet\'s first state, as the rc engine does', async () => { - const connector = createDAppConnector({ bundle: bundleWith(rx.NEVER), networkConfig: STAGENET, approvalOptions: { approveAll: true } }); + const connector = createDAppConnector({ bundle: bundleWith(rx.NEVER), networkConfig: STAGENET, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); try { await expect(connector.handlers.makeTransfer({ desiredOutputs: [{ kind: 'unshielded', type: NIGHT, value: '1', recipient: RECIPIENT }] }, ctx())) .rejects.toMatchObject({ code: 'Disconnected', reason: 'Wallet not synced yet' }); @@ -87,7 +88,7 @@ describe('the beta engine\'s connector', () => { it('hands the facade the wallet\'s secret keys to build a transfer and a swap', async () => { const bundle = bundleWith(rx.of(stateWithFunds())); - const connector = createDAppConnector({ bundle, networkConfig: STAGENET, approvalOptions: { approveAll: true } }); + const connector = createDAppConnector({ bundle, networkConfig: STAGENET, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); try { const output = { kind: 'unshielded', type: NIGHT, value: '1', recipient: RECIPIENT }; await expect(connector.handlers.makeTransfer({ desiredOutputs: [output] }, ctx())).resolves.toEqual({ tx: 'abcd' }); @@ -100,7 +101,7 @@ describe('the beta engine\'s connector', () => { }); it('refuses a transaction it can\'t read as ledger 9 as the caller\'s mistake', async () => { - const connector = createDAppConnector({ bundle: bundleWith(rx.of(stateWithFunds())), networkConfig: STAGENET, approvalOptions: { approveAll: true } }); + const connector = createDAppConnector({ bundle: bundleWith(rx.of(stateWithFunds())), networkConfig: STAGENET, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); try { await expect(connector.handlers.balanceUnsealedTransaction({ tx: 'beef' }, ctx())).rejects.toMatchObject({ code: 'InvalidRequest' }); } finally { diff --git a/src/__tests__/fixtures/record-swap-offer.ts b/src/__tests__/fixtures/record-swap-offer.ts index ec674e19..07fe2641 100644 --- a/src/__tests__/fixtures/record-swap-offer.ts +++ b/src/__tests__/fixtures/record-swap-offer.ts @@ -40,7 +40,7 @@ setEngineLoader(loadInstalledEngine); const engine = await engineFor('undeployed', root); const ctx = { notify: () => {}, connectionId: 'record', requestId: 1, metadata: {} }; const open = (seed: Buffer) => engine.wallet.openConnector({ - seed, root, network: 'undeployed', networkConfig, address: engine.keys.unshieldedAddress(seed, 'undeployed'), syncMode: 'full', + seed, root, notice: () => {}, network: 'undeployed', networkConfig, address: engine.keys.unshieldedAddress(seed, 'undeployed'), syncMode: 'full', onMessage: (m) => { if (!/\d+\/\d+/.test(m)) process.stderr.write(` ${m}\n`); }, }); diff --git a/src/__tests__/generate-command.test.ts b/src/__tests__/generate-command.test.ts index cc7c91cc..a6b305e3 100644 --- a/src/__tests__/generate-command.test.ts +++ b/src/__tests__/generate-command.test.ts @@ -10,6 +10,10 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const TEST_DIR = path.join(os.tmpdir(), `midnight-generate-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; @@ -41,7 +45,7 @@ describe('generate command — random mode', () => { it('writes no seed or mnemonic in the clear: both are sealed under the passphrase', async () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); await cliCall(generateCommand, parseArgs(['generate', '--network', 'undeployed', '--output', walletFile])); - const { seed, mnemonic } = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const { seed, mnemonic } = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); const text = fs.readFileSync(walletFile, 'utf8'); expect(text).not.toContain(seed); expect(text).not.toContain(mnemonic!.split(' ')[0]! + ' ' + mnemonic!.split(' ')[1]!); @@ -53,7 +57,7 @@ describe('generate command — random mode', () => { await cliCall(generateCommand, args); expect(fs.existsSync(walletFile)).toBe(true); - const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); expect(config.addresses.undeployed).toBeDefined(); expect(config.mnemonic).toBeDefined(); expect(config.mnemonic!.split(' ').length).toBe(24); @@ -91,7 +95,7 @@ describe('generate command — seed mode', () => { const args = parseArgs(['generate', '--network', 'preprod', '--seed', TEST_SEED, '--output', walletFile]); await cliCall(generateCommand, args); - const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); expect(config.seed).toBe(TEST_SEED); expect(config.addresses.preprod).toBeDefined(); expect(config.mnemonic).toBeUndefined(); @@ -106,8 +110,8 @@ describe('generate command — seed mode', () => { io.clearStdout(); await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--seed', TEST_SEED, '--output', file2])); - const config1 = (await unlockWallet(file1, { root: stateRootIn(TEST_DIR) })); - const config2 = (await unlockWallet(file2, { root: stateRootIn(TEST_DIR) })); + const config1 = (await unlockWallet(file1, { root: stateRootIn(TEST_DIR) , host})); + const config2 = (await unlockWallet(file2, { root: stateRootIn(TEST_DIR) , host})); expect(config1.addresses.preprod).toBe(config2.addresses.preprod); expect(config1.seed).toBe(config2.seed); }); @@ -133,9 +137,9 @@ describe('generate command — seed mode', () => { // any implementation deriving Midnight addresses from this mnemonic // must land here, so --seed and --mnemonic must both produce it. const golden = 'mn_addr_preview1dwv2rta0a2skyhrvukaw2q9r2sq6yc4jhj63rf7afxpkrrv6g35q4y8xms'; - expect((await unlockWallet(fromSeed, { root: stateRootIn(TEST_DIR) })).addresses.preview).toBe(golden); - expect((await unlockWallet(fromMnemonic, { root: stateRootIn(TEST_DIR) })).addresses.preview).toBe(golden); - expect((await unlockWallet(fromSeed, { root: stateRootIn(TEST_DIR) })).seed).toBe(seedHex); + expect((await unlockWallet(fromSeed, { root: stateRootIn(TEST_DIR) , host})).addresses.preview).toBe(golden); + expect((await unlockWallet(fromMnemonic, { root: stateRootIn(TEST_DIR) , host})).addresses.preview).toBe(golden); + expect((await unlockWallet(fromSeed, { root: stateRootIn(TEST_DIR) , host})).seed).toBe(seedHex); }); it('does not include mnemonic in seed mode', async () => { @@ -150,7 +154,7 @@ describe('generate command — seed mode', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--seed', '0x' + TEST_SEED, '--output', walletFile])); - const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); expect(config.seed).toBe(TEST_SEED); }); @@ -159,7 +163,7 @@ describe('generate command — seed mode', () => { process.env.MN_SEED = TEST_SEED; await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--output', walletFile])); - const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); expect(config.seed).toBe(TEST_SEED); expect(config.mnemonic).toBeUndefined(); }); @@ -169,7 +173,7 @@ describe('generate command — seed mode', () => { process.env.MN_SEED = '0000000000000000000000000000000000000000000000000000000000000009'; await cliCall(generateCommand, parseArgs(['generate', '--network', 'preprod', '--seed', TEST_SEED, '--output', walletFile])); - const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); expect(config.seed).toBe(TEST_SEED); }); }); @@ -183,7 +187,7 @@ describe('generate command — mnemonic mode', () => { const args = parseArgs(['generate', '--network', 'preview', '--mnemonic', VALID_MNEMONIC, '--output', walletFile]); await cliCall(generateCommand, args); - const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) }); + const config = await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host}); expect(config.addresses.preview).toBeDefined(); expect(config.mnemonic).toBe(VALID_MNEMONIC); expect(config.addresses.preview.startsWith('mn_addr_preview1')).toBe(true); @@ -196,8 +200,8 @@ describe('generate command — mnemonic mode', () => { await cliCall(generateCommand, parseArgs(['generate', '--network', 'preview', '--mnemonic', VALID_MNEMONIC, '--output', file1])); await cliCall(generateCommand, parseArgs(['generate', '--network', 'preview', '--mnemonic', VALID_MNEMONIC, '--output', file2])); - const config1 = (await unlockWallet(file1, { root: stateRootIn(TEST_DIR) })); - const config2 = (await unlockWallet(file2, { root: stateRootIn(TEST_DIR) })); + const config1 = (await unlockWallet(file1, { root: stateRootIn(TEST_DIR) , host})); + const config2 = (await unlockWallet(file2, { root: stateRootIn(TEST_DIR) , host})); expect(config1.addresses.preview).toBe(config2.addresses.preview); expect(config1.seed).toBe(config2.seed); }); @@ -251,13 +255,13 @@ describe('generate command — overwrite protection', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); // Create the file first await cliCall(generateCommand, parseArgs(['generate', '--network', 'undeployed', '--seed', TEST_SEED, '--output', walletFile])); - const config1 = (await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) })); + const config1 = (await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host})); io.clearStdout(); // Generate again with --force and a different seed const newSeed = '0000000000000000000000000000000000000000000000000000000000000003'; await cliCall(generateCommand, parseArgs(['generate', '--network', 'undeployed', '--seed', newSeed, '--force', '--output', walletFile])); - const config2 = (await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) })); + const config2 = (await unlockWallet(walletFile, { root: stateRootIn(TEST_DIR) , host})); expect(config2.seed).toBe(newSeed); expect(config2.seed).not.toBe(config1.seed); diff --git a/src/__tests__/grant-account.test.ts b/src/__tests__/grant-account.test.ts index 8ea2cc04..1c5de166 100644 --- a/src/__tests__/grant-account.test.ts +++ b/src/__tests__/grant-account.test.ts @@ -14,6 +14,10 @@ import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { openGrantAccount } from '../lib/grant/account.ts'; import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const PASSPHRASE = 'correct horse battery staple'; const RECORD = { contractAddress: '5e'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }; @@ -22,7 +26,7 @@ const NETWORK = getNetworkConfig('undeployed'); let home: string; let dir: string; const open = (passphrase = PASSPHRASE, warn: (line: string) => void = () => {}) => - openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), source: { env: { [PASSPHRASE_ENV]: passphrase }, prompter: null }, warn }); + openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: passphrase } }, warn }); beforeEach(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-grant-account-')); diff --git a/src/__tests__/grant-prepare.test.ts b/src/__tests__/grant-prepare.test.ts index 777187c5..9db88df3 100644 --- a/src/__tests__/grant-prepare.test.ts +++ b/src/__tests__/grant-prepare.test.ts @@ -11,6 +11,10 @@ import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { UnreachableByAccountError } from '../lib/grant/account.ts'; import { NoAccountError, prepareGrant } from '../lib/grant/prepare.ts'; import { createAccountKey, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -23,7 +27,7 @@ let origHome: string | undefined; const accounts = () => path.join(home, '.midnight', 'accounts'); const recordsOf = (wallet: string) => path.join(accounts(), 'undeployed', wallet); -const prepare = (...argv: string[]) => prepareGrant(parseArgs(['grant', ...argv, ...ENDPOINTS]), path.join(home, '.midnight')); +const prepare = (...argv: string[]) => prepareGrant(parseArgs(['grant', ...argv, ...ENDPOINTS]), path.join(home, '.midnight'), host); const asAlice = (...argv: string[]) => prepare(...argv, '--wallet', 'alice'); // A wallet file, as far as preparing needs one: that it is there. const aliceWallet = () => { diff --git a/src/__tests__/helpers/connector-stub.ts b/src/__tests__/helpers/connector-stub.ts index 38e33188..1d107cac 100644 --- a/src/__tests__/helpers/connector-stub.ts +++ b/src/__tests__/helpers/connector-stub.ts @@ -9,6 +9,9 @@ import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +/** A connector test's host: nobody at a terminal to ask, and the connector's lines dropped. */ +export const NO_TERMINAL = { prompter: null, notice: (_line: string): void => {} } as const; + /** A DApp connector, as both engines make one. */ export interface StubConnector { handlers: Record Promise>; @@ -139,11 +142,14 @@ export function connectorStub(engine: StubEngine) { bundleOverrides?: BundleOverrides; networkConfig?: NetworkConfig; approvalOptions?: ApprovalOptions; + /** Where the connector's lines go; dropped when not given. */ + notice?: (line: string) => void; }): StubConnector { return engine.createDAppConnector({ bundle: createBundleStub(overrides?.bundleOverrides), networkConfig: overrides?.networkConfig ?? TEST_NETWORK_CONFIG, - approvalOptions: overrides?.approvalOptions ?? { approveAll: true }, + approvalOptions: overrides?.approvalOptions ?? { ...NO_TERMINAL, approveAll: true }, + notice: overrides?.notice ?? NO_TERMINAL.notice, }); } diff --git a/src/__tests__/helpers/connector-suite.ts b/src/__tests__/helpers/connector-suite.ts index 47003479..32ae2f71 100644 --- a/src/__tests__/helpers/connector-suite.ts +++ b/src/__tests__/helpers/connector-suite.ts @@ -14,7 +14,7 @@ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vite import * as rx from 'rxjs'; // The wallet SDK's copy of Effect (both engines' SDKs share it): its submit runs on it. import { Effect } from 'effect'; -import { HISTORY, TEST_NETWORK_CONFIG, connectorStub, type BundleOverrides, type StubConnector, type StubEngine } from './connector-stub.ts'; +import { HISTORY, NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub, type BundleOverrides, type StubConnector, type StubEngine } from './connector-stub.ts'; import { startLocalIndexer, type LocalIndexer } from './local-indexer.ts'; import { ledgerTx, type Ledger } from './ledger-tx.ts'; import { SWAP_OFFER_HEX, OFFER_GIVE } from '../fixtures/swap-offer.ts'; @@ -28,7 +28,6 @@ import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; /** What the suite takes from an engine. */ @@ -269,9 +268,10 @@ export function connectorSuite(engine: ConnectorEngine): void { function connectorWith(history: unknown[], indexerUrl = TEST_NETWORK_CONFIG.indexer): StubConnector { return engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle: createBundleStub({ getAllFromTxHistory: () => Promise.resolve(history as any[]) }), networkConfig: { ...TEST_NETWORK_CONFIG, indexer: indexerUrl }, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); } @@ -381,7 +381,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it.each(calls(() => AGENT_TX))('%s refuses as Disconnected, naming the wallet behind the ledger-9 fork, before touching the facade', async (method, params) => { const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ protocolVersion: DUST_BEHIND })) }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err: any = await (connector.handlers as any)[method](params(), ctx()).catch((e: any) => e); @@ -393,7 +393,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('accepts transactions once the lagging wallet crosses the fork', async () => { const states = new rx.BehaviorSubject(mockState({ protocolVersion: DUST_BEHIND })); const bundle = createBundleStub({ stateFn: () => states }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toMatchObject({ code: 'Disconnected' }); states.next(mockState()); @@ -404,7 +404,7 @@ export function connectorSuite(engine: ConnectorEngine): void { // The beta SDK has one ledger: there is no fork to wait for, only the wallet's first state. it.each(calls(() => AGENT_TX))('%s refuses as Disconnected before the wallet\'s first state, before touching the facade', async (method, params) => { const bundle = createBundleStub({ stateFn: () => rx.NEVER }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err: any = await (connector.handlers as any)[method](params(), ctx()).catch((e: any) => e); @@ -416,7 +416,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('accepts transactions once the first state comes', async () => { const states = new rx.Subject(); const bundle = createBundleStub({ stateFn: () => states.asObservable() }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toMatchObject({ code: 'Disconnected' }); states.next(mockState()); @@ -427,7 +427,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('does not require a strictly synced state, which an idle chain\'s dust wallet never reports', async () => { const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ isSynced: false })) }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).resolves.toHaveProperty('tx'); }); @@ -451,9 +451,10 @@ export function connectorSuite(engine: ConnectorEngine): void { const quiet = new rx.Subject(); const synced = { unshielded: { balances: { ['00'.repeat(32)]: 5n } } }; connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle: createBundleStub({ stateFn: () => quiet.asObservable() }), networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, initialState: synced as any, }); expect(await connector.handlers.getUnshieldedBalances({}, ctx())).toEqual({ ['00'.repeat(32)]: 5n }); @@ -462,9 +463,10 @@ export function connectorSuite(engine: ConnectorEngine): void { it('moves on to each later state that is current by the caller\'s rule, not only by the SDK\'s', async () => { const states = new rx.Subject(); connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle: createBundleStub({ stateFn: () => states.asObservable() }), networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, initialState: { unshielded: { balances: {} } } as any, isCurrent: (state: any) => state.caughtUp === true, }); @@ -495,7 +497,7 @@ export function connectorSuite(engine: ConnectorEngine): void { describe('write method approval', () => { it('proceeds when approveAll is true', async () => { - connector = createConnector({ approvalOptions: { approveAll: true } }); + connector = createConnector({ approvalOptions: { ...NO_TERMINAL, approveAll: true } }); const result = await connector.handlers.signData({ data: 'deadbeef', options: { encoding: 'hex', keyType: 'unshielded' }, @@ -511,7 +513,7 @@ export function connectorSuite(engine: ConnectorEngine): void { process.stderr.write = (() => true) as any; try { - connector = createConnector({ approvalOptions: {} }); + connector = createConnector({ approvalOptions: { ...NO_TERMINAL } }); await expect(connector.handlers.signData({ data: 'deadbeef', options: { encoding: 'hex', keyType: 'unshielded' }, @@ -527,7 +529,7 @@ export function connectorSuite(engine: ConnectorEngine): void { process.stderr.write = (() => true) as any; try { - connector = createConnector({ approvalOptions: {} }); + connector = createConnector({ approvalOptions: { ...NO_TERMINAL } }); try { await connector.handlers.submitTransaction({ tx: 'aabb' }, ctx()); expect.unreachable('should have thrown'); @@ -546,7 +548,7 @@ export function connectorSuite(engine: ConnectorEngine): void { describe('signData', () => { it('refuses data that is not valid in its encoding before the operator is asked', async () => { // No approveAll and no TTY: reaching the approval step would fail as Rejected instead. - connector = createConnector({ approvalOptions: {} }); + connector = createConnector({ approvalOptions: { ...NO_TERMINAL } }); const origIsTTY = process.stdin.isTTY; Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); try { @@ -562,9 +564,10 @@ export function connectorSuite(engine: ConnectorEngine): void { it('handles hex encoding', async () => { const bundle = createBundleStub(); connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); const result = await connector.handlers.signData({ @@ -581,9 +584,10 @@ export function connectorSuite(engine: ConnectorEngine): void { it('handles base64 encoding', async () => { const bundle = createBundleStub(); connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); const b64Data = Buffer.from('hello world').toString('base64'); @@ -601,9 +605,10 @@ export function connectorSuite(engine: ConnectorEngine): void { it('handles text encoding', async () => { const bundle = createBundleStub(); connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); const result = await connector.handlers.signData({ @@ -629,7 +634,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const spendData = intent.signatureData(1); const bundle = createBundleStub(); (bundle as any).keystore = keystore; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const result = await connector.handlers.signData({ data: Buffer.from(spendData).toString('hex'), options: { encoding: 'hex', keyType: 'unshielded' }, @@ -736,7 +741,7 @@ export function connectorSuite(engine: ConnectorEngine): void { ['an address for another network', output({ recipient: engine.deriveUnshieldedAddress(RECIPIENT_SEED, 'preprod') }), 'is not an unshielded address on Undeployed'], ])('makeTransfer refuses %s as InvalidRequest without prompting', async (_name, desired, message) => { const transfer = vi.fn(); - const c = connector = createConnector({ bundleOverrides: { transferTransaction: transfer }, approvalOptions: {} }); + const c = connector = createConnector({ bundleOverrides: { transferTransaction: transfer }, approvalOptions: { ...NO_TERMINAL } }); const err: any = await withoutOperator(() => c.handlers.makeTransfer({ desiredOutputs: [desired] }, ctx()).catch((e: any) => e)); @@ -761,7 +766,7 @@ export function connectorSuite(engine: ConnectorEngine): void { ['an input token type that is not hex', { kind: 'unshielded', type: 'night', value: '5' }, 'Invalid token type: "night"'], ])('makeIntent refuses %s as InvalidRequest without building a swap', async (_name, input, message) => { const initSwap = vi.fn(); - const c = connector = createConnector({ bundleOverrides: { initSwap }, approvalOptions: {} }); + const c = connector = createConnector({ bundleOverrides: { initSwap }, approvalOptions: { ...NO_TERMINAL } }); const err: any = await withoutOperator(() => c.handlers.makeIntent({ desiredInputs: [input], desiredOutputs: [], options: { intentId: 'random', payFees: true }, @@ -808,7 +813,7 @@ export function connectorSuite(engine: ConnectorEngine): void { ] as const)('%s reads the hex at stage %s and balances that handle', async (method, stage, sdkMethod) => { const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); const bundle = createBundleStub({ [sdkMethod]: balance }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const tx = stage === 'Unbound' ? AGENT_TX : SEALED_AGENT_TX; await connector.handlers[method]({ tx }, ctx()); @@ -824,7 +829,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('submitTransaction reads the hex as a finalized transaction and submits that handle', async () => { const submit = vi.fn().mockResolvedValue('tx-id'); const bundle = createBundleStub({ submitTransaction: submit }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const result = await connector.handlers.submitTransaction({ tx: SEALED_AGENT_TX }, ctx()); @@ -842,7 +847,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const sdkFailure = Effect.runPromise(Effect.fail(new engine.SubmissionError({ message: 'Transaction submission error', cause: nodeAnswer }))); sdkFailure.catch(() => {}); const bundle = createBundleStub({ submitTransaction: () => sdkFailure }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err: any = await connector.handlers.submitTransaction({ tx: SEALED_AGENT_TX }, ctx()).catch((e: any) => e); @@ -855,7 +860,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const bundle = createBundleStub({ balanceUnboundTransaction: balance }); // The rc SDK's reader, as it refuses another ledger version's bytes; the beta engine's ledger refuses these on its own. if (engine.readsThroughFacade) (bundle.facade as any).adoptTransaction = () => { throw new Error('unknown tag midnight:transaction[v99]'); }; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: 'aabb' }, ctx()).catch((e: any) => e); @@ -867,7 +872,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('rejects non-hex input before it reaches the SDK', async () => { const bundle = createBundleStub(); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: 'not-hex' }, ctx()).catch((e: any) => e); @@ -921,7 +926,7 @@ export function connectorSuite(engine: ConnectorEngine): void { // Tests the error path through processRecipe — finalizeRecipe rejection // propagates correctly through Promise.race and surfaces to the caller. connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { finalizeRecipe: () => Promise.reject(new Error('ZK proof generation timed out')), }, @@ -933,7 +938,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('returns serialized tx when finalizeRecipe resolves', async () => { connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { finalizeRecipe: () => Promise.resolve(sealedTx(6)), }, @@ -945,7 +950,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('propagates signRecipe errors', async () => { connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { signRecipe: () => Promise.reject(new Error('signing failed')), }, @@ -957,7 +962,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('propagates finalizeRecipe errors', async () => { connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { finalizeRecipe: () => Promise.reject(new Error('proof generation failed')), }, @@ -1023,7 +1028,7 @@ export function connectorSuite(engine: ConnectorEngine): void { process.stderr.write = (() => true) as any; let callCount = 0; connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { balanceUnboundTransaction: () => { callCount++; @@ -1049,7 +1054,7 @@ export function connectorSuite(engine: ConnectorEngine): void { }); let callCount = 0; connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { balanceUnboundTransaction: () => (++callCount === 1 ? Promise.reject(dustShortage) : Promise.resolve({ type: 'UNBOUND' })), }, @@ -1068,7 +1073,7 @@ export function connectorSuite(engine: ConnectorEngine): void { _tag: 'Wallet.InsufficientFunds', tokenType: '00', }); const balance = vi.fn().mockRejectedValue(nightShortage); - connector = createConnector({ approvalOptions: { approveAll: true }, bundleOverrides: { balanceUnboundTransaction: balance } }); + connector = createConnector({ approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { balanceUnboundTransaction: balance } }); await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toBe(nightShortage); expect(balance).toHaveBeenCalledTimes(1); @@ -1077,7 +1082,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('does not retry on non-dust errors', async () => { process.stderr.write = (() => true) as any; connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { balanceUnboundTransaction: () => Promise.reject(new Error('some other error')), }, @@ -1092,7 +1097,7 @@ export function connectorSuite(engine: ConnectorEngine): void { process.stderr.write = (() => true) as any; let callCount = 0; connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { balanceUnboundTransaction: () => { callCount++; @@ -1133,10 +1138,9 @@ export function connectorSuite(engine: ConnectorEngine): void { it('waits the time the wallet takes to generate the rest, then pays', async () => { vi.useFakeTimers(); const written: string[] = []; - setNoticeSink((line) => written.push(line)); // 1 DUST: 0.65 more and a little over, 89 seconds at this rate. const balance = vi.fn().mockRejectedValueOnce(shortOf(SPECK)).mockResolvedValue({ type: 'UNBOUND' }); - connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance } }); + connector = createConnector({ bundleOverrides: { stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance }, notice: (line) => written.push(line) }); const paid = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); await vi.advanceTimersByTimeAsync(88_000); @@ -1146,7 +1150,6 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(balance).toHaveBeenCalledTimes(2); expect(written.join('')).toContain('Dust: 0.35 of the 1.00 DUST this fee takes; waiting about 2 minutes for the rest...'); vi.useRealTimers(); - setNoticeSink(null); }); it('refuses at once, with the time, when that is longer than a request waits', async () => { @@ -1169,9 +1172,10 @@ export function connectorSuite(engine: ConnectorEngine): void { process.stderr.write = (() => true) as any; const balance = vi.fn().mockRejectedValueOnce(shortOf(2n * SPECK)).mockResolvedValue({ type: 'UNBOUND' }); connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle: createBundleStub({ stateFn: growingFrom(Date.now()), balanceUnboundTransaction: balance }), networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, dustWaitMs: 5 * 60_000, }); @@ -1232,7 +1236,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const attemptedAt: number[] = []; const started = Date.now(); connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { // No Dust coin is free until one second in, when a pending transaction lands and releases its coin. stateFn: () => rx.concat(rx.of(mockState({ dustBalance: 0n })), rx.timer(1_000).pipe(rx.map(() => mockState({ dustBalance: 1000n })))), @@ -1260,7 +1264,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const attemptedAt: number[] = []; const started = Date.now(); connector = createConnector({ - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, bundleOverrides: { // The wallet state shows Dust throughout; the fourth attempt finds it has grown enough. balanceUnboundTransaction: () => { @@ -1325,12 +1329,12 @@ export function connectorSuite(engine: ConnectorEngine): void { /** A connector in fee-wallet mode over a bundle whose unshielded key is WALLET_VK. */ function feeWallet( overrides?: BundleOverrides, - approvalOptions: ApprovalOptions = { approveFees: true, autoApproveReads: true }, + approvalOptions: ApprovalOptions = { ...NO_TERMINAL, approveFees: true, autoApproveReads: true }, feeLimits?: FeeLimits, ) { const bundle = createBundleStub(overrides); (bundle.keystore as any).getPublicKey = () => WALLET_VK; - const feeConnector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions, feeLimits }); + const feeConnector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions, feeLimits, notice: NO_TERMINAL.notice }); connector = feeConnector; return { bundle, connector: feeConnector }; } @@ -1445,7 +1449,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const estimate = vi.fn().mockResolvedValue(10n * ONE_DUST); const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); const { connector } = feeWallet({ balanceUnboundTransaction: balance, estimateTransactionFee: estimate }, - { approveAll: true }, { maxFeeSpecks: 1n, maxPending: 1 }); + { ...NO_TERMINAL, approveAll: true }, { maxFeeSpecks: 1n, maxPending: 1 }); await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()); expect(estimate).not.toHaveBeenCalled(); @@ -1469,7 +1473,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('approves a fee-only balance as fee-only, not as a prep step, so it holds with --no-auto-approve-reads', async () => { const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); - const { connector } = feeWallet({ balanceUnboundTransaction: balance }, { approveFees: true, autoApproveReads: false }); + const { connector } = feeWallet({ balanceUnboundTransaction: balance }, { ...NO_TERMINAL, approveFees: true, autoApproveReads: false }); const result = await connector.handlers.balanceUnsealedTransaction({ tx: hex(await unsealedBytes(agentPaysMerchant())) }, ctx()) as any; @@ -1511,7 +1515,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('rejects submitting a transaction this server balanced, but not fee-only', async () => { const submit = vi.fn(); - const opts: ApprovalOptions = { approveAll: true }; + const opts: ApprovalOptions = { ...NO_TERMINAL, approveAll: true }; const { connector } = feeWallet({ submitTransaction: submit }, opts); const balanced = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('agent')) as any; @@ -1602,7 +1606,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const validate = vi.fn().mockResolvedValue(undefined); const balance = vi.fn().mockResolvedValue({ type: 'RECIPE', blockData: 'block' }); const bundle = createBundleStub({ validateTransaction: validate, balanceFinalizedTransaction: balance }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); expect(await connector.takeOffer('taker', SWAP_OFFER_HEX)).toBe(FINALIZED_HEX); @@ -1619,7 +1623,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('refuses an offer whose signatures or proofs don\'t check, before building anything', async () => { const balance = vi.fn(); const bundle = createBundleStub({ validateTransaction: vi.fn().mockRejectedValue(new Error('invalid proof')), balanceFinalizedTransaction: balance }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err = await connector.takeOffer('taker', SWAP_OFFER_HEX).catch((e: unknown) => e); @@ -1630,7 +1634,7 @@ export function connectorSuite(engine: ConnectorEngine): void { it('refuses a transaction that is no offer before validating anything', async () => { const validate = vi.fn(); - connector = engine.createDAppConnector({ bundle: createBundleStub({ validateTransaction: validate }), networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle: createBundleStub({ validateTransaction: validate }), networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.takeOffer('taker', SEALED_AGENT_TX)).rejects.toBeInstanceOf(NotAnOfferError); expect(validate).not.toHaveBeenCalled(); @@ -1641,7 +1645,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const built = offerTx(); const bundle = createBundleStub({ finalizeRecipe: () => Promise.resolve(built) }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true }, openOffers: () => [openOffer()] }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, openOffers: () => [openOffer()], notice: NO_TERMINAL.notice }); const err = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: unknown) => e); @@ -1657,7 +1661,7 @@ export function connectorSuite(engine: ConnectorEngine): void { transferTransaction: transfer, finalizeRecipe: () => Promise.resolve(offerTx()), }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true }, openOffers: () => [openOffer()] }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, openOffers: () => [openOffer()], notice: NO_TERMINAL.notice }); expect(await connector.cancelOffers('maker', [openOffer()])).toBe(SWAP_OFFER_HEX); const [[outputs]] = transfer.mock.calls; @@ -1676,7 +1680,7 @@ export function connectorSuite(engine: ConnectorEngine): void { finalizeRecipe: () => Promise.resolve(sealedTx(5)), }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.cancelOffers('maker', [openOffer()])).rejects.toMatchObject({ code: 'InvalidRequest' }); expect(revertFn).toHaveBeenCalled(); @@ -1698,9 +1702,10 @@ export function connectorSuite(engine: ConnectorEngine): void { (bundle.facade as any).revert = revertFn; connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); const connId = 'conn_hex_test'; @@ -1731,9 +1736,10 @@ export function connectorSuite(engine: ConnectorEngine): void { (bundle.facade as any).revert = revertFn; connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); const connId = 'conn_revert_test'; @@ -1753,7 +1759,7 @@ export function connectorSuite(engine: ConnectorEngine): void { process.stderr.write = (() => true) as any; const bundle = createBundleStub({ finalizeRecipe: () => Promise.resolve(sealedTx(5)) }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const built = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('conn_offer')) as { tx: string }; expect(connector.handOffPendingTx('conn_offer', built.tx)).toBe(true); @@ -1781,8 +1787,9 @@ export function connectorSuite(engine: ConnectorEngine): void { // Use a single connector — approvalOptions is a mutable object reference. // Balance with approveAll, then remove it so submit rejects via non-TTY. - const opts: Record = { approveAll: true }; + const opts: Record = { ...NO_TERMINAL, approveAll: true }; connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: opts, @@ -1825,7 +1832,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const balance = vi.fn(); const bundle = createBundleStub({ balanceUnboundTransaction: balance }); // No approveAll and no TTY: reaching the approval step would fail as Rejected instead. - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: {} }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL }, notice: NO_TERMINAL.notice }); const origIsTTY = process.stdin.isTTY; Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); try { @@ -1863,7 +1870,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const balance = vi.fn().mockResolvedValue({ type: 'RECIPE' }); const bundle = createBundleStub({ balanceUnboundTransaction: balance }); (bundle.keystore as any).getPublicKey = () => WALLET_VK; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveFees: true, autoApproveReads: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveFees: true, autoApproveReads: true }, notice: NO_TERMINAL.notice }); await connector.handlers.balanceUnsealedTransaction({ tx: await signedWithSurplus() }, ctx()); @@ -1878,7 +1885,7 @@ export function connectorSuite(engine: ConnectorEngine): void { signRecipe: () => Promise.reject(new engine.PartlySignedTransactionError()), }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const err: any = await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()).catch((e: any) => e); @@ -1901,7 +1908,7 @@ export function connectorSuite(engine: ConnectorEngine): void { }))).toString('hex'); const balance = vi.fn(); const bundle = createBundleStub({ [balanceMethod]: balance }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { autoApproveReads: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, autoApproveReads: true }, notice: NO_TERMINAL.notice }); const origIsTTY = process.stdin.isTTY; Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); try { @@ -1945,7 +1952,7 @@ export function connectorSuite(engine: ConnectorEngine): void { signRecipe: () => Promise.reject(new Error('signer unavailable')), }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toThrow('signer unavailable'); expect(revertFn).toHaveBeenCalledWith(recipe); @@ -1962,7 +1969,7 @@ export function connectorSuite(engine: ConnectorEngine): void { finalizeRecipe: () => Promise.reject(new Error('proof server unreachable')), }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); await expect(connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx())).rejects.toThrow('proof server unreachable'); expect(revertFn).toHaveBeenCalledWith(recipe); @@ -1980,7 +1987,7 @@ export function connectorSuite(engine: ConnectorEngine): void { finalizeRecipe: () => new Promise((resolve) => { finishProof = resolve; }), }); (bundle.facade as any).revert = revertFn; - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const call = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); const outcome = expect(call).rejects.toThrow('ZK proof generation timed out'); @@ -2012,9 +2019,10 @@ export function connectorSuite(engine: ConnectorEngine): void { (bundle.facade as any).revert = revertFn; connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); const connId = 'conn_abandon'; @@ -2040,9 +2048,10 @@ export function connectorSuite(engine: ConnectorEngine): void { (bundle.facade as any).revert = revertFn; connector = engine.createDAppConnector({ + notice: NO_TERMINAL.notice, bundle, networkConfig: TEST_NETWORK_CONFIG, - approvalOptions: { approveAll: true }, + approvalOptions: { ...NO_TERMINAL, approveAll: true }, }); await connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx('conn_dispose')); diff --git a/src/__tests__/host-paths.test.ts b/src/__tests__/host-paths.test.ts index 4e909b9b..3eab648e 100644 --- a/src/__tests__/host-paths.test.ts +++ b/src/__tests__/host-paths.test.ts @@ -44,9 +44,10 @@ function hostAt(home: string): Host { return createHost({ paths: { stateRoot: path.join(home, MIDNIGHT_DIR), home } }); } -/** A wallet created under `root`, sealed under the passphrase set there. */ -async function walletIn(root: string, name: string): Promise { - const passphrase = await passphraseForNewSecret(root, { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }); +/** A wallet created under `host`'s state root, sealed under the passphrase set there. */ +async function walletIn(host: Host, name: string): Promise { + const root = host.paths().stateRoot; + const passphrase = await passphraseForNewSecret(host, root, { env: { [PASSPHRASE_ENV]: PASSPHRASE } }); await createWallet(root, name, walletSecretFrom({ seed: Buffer.alloc(32, name.length) }), passphrase); } @@ -80,8 +81,8 @@ describe('two hosts with different state roots', () => { }); it('each create, list and activate their own wallets', async () => { - await walletIn(rootA, 'alice'); - await walletIn(rootB, 'bob'); + await walletIn(hostA, 'alice'); + await walletIn(hostB, 'bob'); expect((await listWallets(rootA)).map((w) => w.name)).toEqual(['alice']); expect((await listWallets(rootB)).map((w) => w.name)).toEqual(['bob']); diff --git a/src/__tests__/host-slots.test.ts b/src/__tests__/host-slots.test.ts new file mode 100644 index 00000000..1cbf1664 --- /dev/null +++ b/src/__tests__/host-slots.test.ts @@ -0,0 +1,157 @@ +// Two hosts in one process ask, say and remember apart: an approval asks its +// own host's prompter and says what it decided through its own host's +// notices; a passphrase one host unlocked is not unlocked in the other (same +// state root); a plain-text wallet is warned about once per host; and each +// host's RPC servers number their connections from their own count. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { WebSocket } from 'ws'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; +import { NoPassphraseError, PASSPHRASE_ENV, establishPassphrase, unlockPassphrase } from '../lib/passphrase.ts'; +import { unlockWallet } from '../lib/wallet-config.ts'; +import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { stateRootIn } from './helpers/state-root-in.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; + +/** A prompter at a terminal that answers every question with `answer`, keeping the questions. */ +function answering(answer: string): Prompter & { questions: string[] } { + const questions: string[] = []; + return { + questions, + isInteractive: () => true, + ask: async (question) => { questions.push(question); return answer; }, + askSecret: async (question) => { questions.push(question); return answer; }, + }; +} + +/** A host whose notices land in `lines`, asking through `prompter`. */ +const hostSaying = (lines: string[], prompter: Prompter | null = null): Host => + createHost({ notice: (line) => lines.push(line), prompter }); + +let home: string; + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-host-slots-')); +}); +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +describe('an approval', () => { + it("asks its own host's prompter, and says what it decided through its own host's notices", async () => { + const promptedA = answering('a'); + const promptedB = answering('r'); + const saidA: string[] = []; + const saidB: string[] = []; + const hostA = hostSaying(saidA, promptedA); + const hostB = hostSaying(saidB, promptedB); + const request = (method: string) => ({ method, network: 'undeployed', details: [] }); + + // Both at once: each host's prompter answers its own, neither waits on the other's. + const [a, b] = await Promise.all([ + promptApproval(request('makeTransfer'), { prompter: hostA.prompter, notice: hostA.notice }), + promptApproval(request('signData'), { prompter: hostB.prompter, notice: hostB.notice }), + ]); + + expect([a, b]).toEqual(['approve', 'reject']); + expect(promptedA.questions).toHaveLength(1); + expect(promptedA.questions[0]).toContain('makeTransfer'); + expect(promptedB.questions).toHaveLength(1); + expect(promptedB.questions[0]).toContain('signData'); + + await promptApproval(request('makeIntent'), { approveAll: true, prompter: hostB.prompter, notice: hostB.notice }); + expect(saidA).toEqual([]); + expect(saidB.join('\n')).toContain('Auto-approved: makeIntent'); + expect(promptedB.questions).toHaveLength(1); + }); +}); + +describe('the unlocked passphrase', () => { + it('is kept by the host that unlocked it: another host, over the same state root, asks again', async () => { + const root = stateRootIn(home); + establishPassphrase(root, PASSPHRASE); + const hostA = createHost(); + const hostB = createHost(); + + expect(await unlockPassphrase(hostA, root, { env: { [PASSPHRASE_ENV]: PASSPHRASE } })).toBe(PASSPHRASE); + // Neither host has a prompter, and the environment names none now: only one that unlocked it before has it. + expect(await unlockPassphrase(hostA, root, { env: {} })).toBe(PASSPHRASE); + await expect(unlockPassphrase(hostB, root, { env: {} })).rejects.toThrow(NoPassphraseError); + }); +}); + +describe('the plain-text wallet warning', () => { + it("is said once per host, through that host's notices", async () => { + const root = stateRootIn(home); + const wallet = saveWalletConfig( + { seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-11-03T00:00:00.000Z' }, + path.join(root, 'wallets', 'plain.json'), + ); + const saidA: string[] = []; + const saidB: string[] = []; + const hostA = hostSaying(saidA); + const hostB = hostSaying(saidB); + + await unlockWallet(wallet, { root, host: hostA }); + await unlockWallet(wallet, { root, host: hostA }); + await unlockWallet(wallet, { root, host: hostB }); + + expect(saidA).toHaveLength(1); + expect(saidA[0]).toMatch(/Warning: wallet .*plain\.json is not protected: its seed is in plain text/); + expect(saidB).toEqual(saidA); + }); +}); + +describe('RPC connection ids', () => { + const servers: RpcServer[] = []; + const clients: WebSocket[] = []; + afterEach(async () => { + for (const ws of clients) ws.close(); + clients.length = 0; + await Promise.all(servers.map((server) => server.close())); + servers.length = 0; + }); + + /** A server of `host`'s on a free port, and the ids of the connections it accepts. */ + async function serverOf(host: Host): Promise<{ port: number; ids: string[] }> { + const ids: string[] = []; + const server = createRpcServer({ host, port: 0, handlers: {}, onConnect: (conn) => ids.push(conn.id) }); + servers.push(server); + await server.ready; + return { port: (server.wss.address() as { port: number }).port, ids }; + } + + const connect = (port: number): Promise => new Promise((resolve, reject) => { + const ws = new WebSocket(`ws://127.0.0.1:${port}`); + clients.push(ws); + ws.on('open', () => resolve()); + ws.on('error', reject); + }); + + it("count per host: each host's servers number their connections from its own count", async () => { + const hostA = createHost(); + const hostB = createHost(); + const a1 = await serverOf(hostA); + const a2 = await serverOf(hostA); + const b = await serverOf(hostB); + + await connect(a1.port); + await connect(b.port); + await connect(a2.port); + await connect(b.port); + // The server sees a connection once its handshake is done, a moment after the client does. + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect([...a1.ids, ...a2.ids]).toEqual(['conn_1', 'conn_2']); + expect(b.ids).toEqual(['conn_1', 'conn_2']); + }); +}); diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index 6924df31..07588c04 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -1,13 +1,13 @@ -// What a library has for the person at the terminal goes to the notice sink -// its host sets, never to stderr directly: with no sink it is dropped, and -// the CLI's sink writes it to stderr as before. HOME is a temporary folder. +// What a library has for the person at the terminal goes to the notices its +// host takes, never to stderr directly: a host that takes none drops it, and +// the CLI's host writes it to stderr as before. HOME is a temporary folder. import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { notice, setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { unlockWallet } from '../lib/wallet-config.ts'; import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; @@ -23,7 +23,6 @@ beforeEach(() => { process.env.HOME = home; }); afterEach(() => { - setNoticeSink(null); process.env.HOME = originalHome; fs.rmSync(home, { recursive: true, force: true }); }); @@ -32,21 +31,13 @@ const plainWallet = (name: string): string => saveWalletConfig({ seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-10-19T00:00:00.000Z' }, path.join(home, '.midnight', 'wallets', `${name}.json`)); describe('notices', () => { - it('reach the sink that is set, and are dropped with none', () => { + it("carry a library's warning to its host's notices when its caller gives no warn of its own, and nowhere when the host takes none", async () => { const lines: string[] = []; - notice('before any sink'); - setNoticeSink((line) => lines.push(line)); - notice('one line'); - setNoticeSink(null); - notice('after the sink is gone'); - expect(lines).toEqual(['one line']); - }); - - it("carry a library's warning when its caller gives no warn of its own", async () => { - const lines: string[] = []; - setNoticeSink((line) => lines.push(line)); - await unlockWallet(plainWallet('notice-alice'), { root: path.join(home, '.midnight') }); - expect(lines.join('\n')).toMatch(/not protected: its seed is in plain text/); + const wallet = plainWallet('notice-alice'); + await unlockWallet(wallet, { root: path.join(home, '.midnight'), host: createHost() }); + await unlockWallet(wallet, { root: path.join(home, '.midnight'), host: createHost({ notice: (line) => lines.push(line) }) }); + expect(lines).toHaveLength(1); + expect(lines[0]).toMatch(/not protected: its seed is in plain text/); }); it('reach stderr through the CLI, as before', () => { diff --git a/src/__tests__/passphrase.test.ts b/src/__tests__/passphrase.test.ts index 66699e0f..759fb919 100644 --- a/src/__tests__/passphrase.test.ts +++ b/src/__tests__/passphrase.test.ts @@ -22,6 +22,10 @@ import { import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const PASSPHRASE = 'correct horse battery staple'; let home: string; @@ -45,13 +49,13 @@ const terminal = (...lines: string[]) => { describe('reading the passphrase', () => { it('takes MN_PASSPHRASE when it is set, asking nothing', async () => { - const value = await readPassphrase({ env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }); + const value = await readPassphrase(null, { env: { [PASSPHRASE_ENV]: PASSPHRASE } }); expect(value).toBe(PASSPHRASE); }); it('asks at a terminal, without echoing what is typed', async () => { const { io, written } = terminal(PASSPHRASE); - const reading = readPassphrase(io); + const reading = readPassphrase(io.prompter, io); io.typeNext(); expect(await reading).toBe(PASSPHRASE); expect(written()).toContain('Passphrase'); @@ -60,14 +64,14 @@ describe('reading the passphrase', () => { it('asks twice when setting it, and refuses two that differ', async () => { const { io } = terminal(PASSPHRASE, 'something else'); - const reading = readPassphrase({ ...io, confirm: true }); + const reading = readPassphrase(io.prompter, { ...io, confirm: true }); io.typeNext(); setTimeout(io.typeNext, 10); await expect(reading).rejects.toThrow(/do not match/); }); it('refuses where it can neither read the variable nor ask', async () => { - await expect(readPassphrase({ env: {}, prompter: null })).rejects.toThrow(NoPassphraseError); + await expect(readPassphrase(null, { env: {} })).rejects.toThrow(NoPassphraseError); }); }); @@ -83,18 +87,18 @@ describe('the one passphrase', () => { it('unlocks with the passphrase it was set with', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - expect(await unlockPassphrase(stateRootIn(home), { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null })).toBe(PASSPHRASE); + expect(await unlockPassphrase(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: PASSPHRASE } })).toBe(PASSPHRASE); }); it('refuses any other passphrase once set', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - await expect(unlockPassphrase(stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'another one' }, prompter: null })).rejects.toThrow(WrongPassphraseError); + await expect(unlockPassphrase(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'another one' } })).rejects.toThrow(WrongPassphraseError); }); it('checks a changed MN_PASSPHRASE afresh, never taking the one checked before', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - await unlockPassphrase(stateRootIn(home), { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }); - await expect(unlockPassphrase(stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'another one' }, prompter: null })).rejects.toThrow(WrongPassphraseError); + await unlockPassphrase(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: PASSPHRASE } }); + await expect(unlockPassphrase(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'another one' } })).rejects.toThrow(WrongPassphraseError); }); it('is not set a second time over the first', () => { @@ -105,19 +109,19 @@ describe('the one passphrase', () => { describe('a new secret', () => { it('sets the passphrase on a machine with none, and is sealed under it', async () => { - const passphrase = await passphraseForNewSecret(stateRootIn(home), { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }); + const passphrase = await passphraseForNewSecret(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: PASSPHRASE } }); expect(passphrase).toBe(PASSPHRASE); expect(isPassphraseSet(stateRootIn(home))).toBe(true); }); it(`refuses a new passphrase shorter than ${MIN_PASSPHRASE_LENGTH} characters, setting nothing`, async () => { - await expect(passphraseForNewSecret(stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'too short' }, prompter: null })).rejects.toThrow(/at least/); + await expect(passphraseForNewSecret(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'too short' } })).rejects.toThrow(/at least/); expect(isPassphraseSet(stateRootIn(home))).toBe(false); }); it('takes the passphrase already set, and no other', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - await expect(passphraseForNewSecret(stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'another passphrase' }, prompter: null })).rejects.toThrow(WrongPassphraseError); + await expect(passphraseForNewSecret(host, stateRootIn(home), { env: { [PASSPHRASE_ENV]: 'another passphrase' } })).rejects.toThrow(WrongPassphraseError); }); }); diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index 01598d78..22385461 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -21,6 +21,10 @@ import contractCommand from '../commands/contract.ts'; import grantCommand from '../commands/grant.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -40,7 +44,7 @@ afterEach(() => { describe('resolvePayingTarget', () => { it('acts on undeployed when no network is given, with the endpoints given as flags', () => { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home), host); expect(target.network).toBe('undeployed'); expect(target.endpoints).toEqual({ node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', proofServer: 'http://localhost:26300' }); expect(target.networkConfig.node).toBe('ws://localhost:29944'); @@ -50,8 +54,8 @@ describe('resolvePayingTarget', () => { it('acts on the network set with config set network when none is given, as every other command does', () => { saveCliConfig({ network: 'preprod' }, stateRootIn(home)); - expect(resolvePayingTarget(parseArgs(['contract', 'deploy']), 'contract', 'deploy', stateRootIn(home)).network).toBe('preprod'); - expect(resolvePayingTarget(parseArgs(['contract', 'deploy', '--network', 'preview']), 'contract', 'deploy', stateRootIn(home)).network).toBe('preview'); + expect(resolvePayingTarget(parseArgs(['contract', 'deploy']), 'contract', 'deploy', stateRootIn(home), host).network).toBe('preprod'); + expect(resolvePayingTarget(parseArgs(['contract', 'deploy', '--network', 'preview']), 'contract', 'deploy', stateRootIn(home), host).network).toBe('preview'); }); }); @@ -100,7 +104,7 @@ describe('the serve payer', () => { const serve = await runningServe(); const said: string[] = []; try { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home), host); const served = await servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings, undefined); expect(served.port).toBe(serve.port); expect(said).toEqual([`Reusing existing mn serve on port ${serve.port}`, `mn serve ready (port ${serve.port})`]); @@ -115,7 +119,7 @@ describe('the serve payer', () => { const serve = await runningServe(); const said: string[] = []; try { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home), host); const controller = new AbortController(); controller.abort(); await expect(servePayerAt(serve.port).serve(target, undefined, silentSpinner((message) => said.push(message)), createSdkWarningRouter().openCall().warnings, controller.signal)).rejects.toBeInstanceOf(CancelledError); @@ -126,7 +130,7 @@ describe('the serve payer', () => { }); it('checks no wallet for a call already cancelled', async () => { - const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home)); + const target = resolvePayingTarget(parseArgs(['contract', 'deploy', ...ENDPOINTS]), 'contract', 'deploy', stateRootIn(home), host); const controller = new AbortController(); controller.abort(); // Not cancelled, this would fail on the missing wallet file. diff --git a/src/__tests__/prep-runner-cancellation.test.ts b/src/__tests__/prep-runner-cancellation.test.ts index d51ed1fa..e4680f91 100644 --- a/src/__tests__/prep-runner-cancellation.test.ts +++ b/src/__tests__/prep-runner-cancellation.test.ts @@ -6,6 +6,10 @@ import { runPrepSteps } from '../lib/test/prep-runner.ts'; import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const config = { network: 'undeployed', prep: ['dust', 'mn-serve'] } as unknown as DappTestConfig; @@ -14,7 +18,7 @@ describe('runPrepSteps', () => { const controller = new AbortController(); controller.abort(); const started: string[] = []; - await expect(runPrepSteps(config, '/nonexistent', createPrepContext('/nonexistent/.midnight', createSdkWarningRouter().openCall().warnings, controller.signal), { + await expect(runPrepSteps(config, '/nonexistent', createPrepContext('/nonexistent/.midnight', host, createSdkWarningRouter().openCall().warnings, controller.signal), { onStepStart: (step) => started.push(step), onStepComplete: () => {}, onMessage: () => {}, diff --git a/src/__tests__/protect-account.test.ts b/src/__tests__/protect-account.test.ts index 02d8c7df..2e8d2097 100644 --- a/src/__tests__/protect-account.test.ts +++ b/src/__tests__/protect-account.test.ts @@ -18,6 +18,10 @@ import { LEGACY_STORE_PASSWORD, openGrantAccount, privateStateLocationOf } from import { AccountMigrationInterruptedError, protectAccount } from '../lib/grant/protect-account.ts'; import { isSealedAccount } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -34,7 +38,7 @@ const wallet = { getCoinPublicKey: () => COIN_KEY } as unknown as FeeWallet; // The account package's providers over the account's private state, under `password`. const privateStateUnder = async (password: string) => { - const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), source: { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }, warn: () => {} }); + const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } }, warn: () => {} }); const providers = accountProviders(account.context, wallet, privateStateLocationOf(dir, () => password)); providers.privateStateProvider.setContractAddress(ACCOUNT); return providers.privateStateProvider; @@ -69,7 +73,7 @@ describe('protecting an account an earlier mn made in plain text', () => { expect(await protectAccount(dir, PASSPHRASE, COIN_KEY)).toBe('sealed-now'); expect(isSealedAccount(dir)).toBe(true); expect(plainTextLeft()).toEqual([]); - const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), source: { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null } }); + const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); expect(account.protection).toBe('sealed'); expect(account.store.readOwner()).toEqual(RECORD); expect(account.store.readRoster()).toEqual(ROSTER); @@ -79,7 +83,7 @@ describe('protecting an account an earlier mn made in plain text', () => { it('moves its private state onto a password of its own, off the public one', async () => { await writePlainAccount(); await protectAccount(dir, PASSPHRASE, COIN_KEY); - const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), source: { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null } }); + const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); const own = await account.location.password(); expect(own).not.toBe(LEGACY_STORE_PASSWORD); expect(await (await privateStateUnder(own)).get(PRIVATE_STATE_ID)).toEqual(PRIVATE_STATE); @@ -102,9 +106,9 @@ describe('protecting an account an earlier mn made in plain text', () => { // A run that stopped after moving the private state, before the account was sealed. await protectAccount(dir, PASSPHRASE, COIN_KEY, { stopBeforeSealing: true }); expect(isSealedAccount(dir)).toBe(false); - await expect(openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), warn: () => {} })).rejects.toThrow(AccountMigrationInterruptedError); + await expect(openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, warn: () => {} })).rejects.toThrow(AccountMigrationInterruptedError); expect(await protectAccount(dir, PASSPHRASE, COIN_KEY)).toBe('sealed-now'); - const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), source: { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null } }); + const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); expect(await (await privateStateUnder(await account.location.password())).get(PRIVATE_STATE_ID)).toEqual(PRIVATE_STATE); expect(plainTextLeft()).toEqual([]); }); diff --git a/src/__tests__/sealed-wallet.test.ts b/src/__tests__/sealed-wallet.test.ts index 559ee191..ac3710d1 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/src/__tests__/sealed-wallet.test.ts @@ -14,6 +14,10 @@ import { loadWalletConfig, protectAllWallets, sealWalletInPlace, unlockWallet, w import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; const MNEMONIC = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; @@ -26,7 +30,7 @@ const PUBLIC = { let home: string; let file: string; -const withPassphrase = (passphrase: string) => ({ root: stateRootIn(home), source: { env: { [PASSPHRASE_ENV]: passphrase }, prompter: null } }); +const withPassphrase = (passphrase: string) => ({ root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: passphrase } } }); beforeEach(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-sealed-wallet-')); @@ -82,7 +86,7 @@ describe('a wallet an earlier mn wrote in plain text', () => { it('still opens, saying it is not protected', async () => { writePlain(); const warnings: string[] = []; - const wallet = await unlockWallet(file, { root: stateRootIn(home), warn: (line) => warnings.push(line) }); + const wallet = await unlockWallet(file, { root: stateRootIn(home), host, warn: (line) => warnings.push(line) }); expect(wallet.seed).toBe(SEED); expect((await loadWalletConfig(file)).isSealed).toBe(false); expect(warnings.join('\n')).toMatch(/not protected[\s\S]*midnight wallet protect/); diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 8c2c7ebf..5d4f0ca1 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -11,6 +11,10 @@ import { parseSeedHex, resolveSeedSource, resolveSeed } from '../lib/seed-resolv import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const PASSPHRASE = 'correct horse battery staple'; const ORIGINAL_HOME = process.env.HOME; @@ -63,7 +67,7 @@ describe('parseSeedHex', () => { describe('resolveSeedSource', () => { it('reads --seed, with no backing wallet file/config', async () => { - const r = await resolveSeedSource(argsFor(['--seed', SEED_A]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor(['--seed', SEED_A]), stateRootIn(TMP), host); expect(r.seed.toString('hex')).toBe(SEED_A); expect(r.walletPath).toBeNull(); expect(r.config).toBeNull(); @@ -71,46 +75,46 @@ describe('resolveSeedSource', () => { it('reads MN_SEED when --seed is absent', async () => { process.env.MN_SEED = SEED_A; - const r = await resolveSeedSource(argsFor([]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor([]), stateRootIn(TMP), host); expect(r.seed.toString('hex')).toBe(SEED_A); expect(r.walletPath).toBeNull(); }); it('lets --seed win over MN_SEED', async () => { process.env.MN_SEED = SEED_B; - const r = await resolveSeedSource(argsFor(['--seed', SEED_A]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor(['--seed', SEED_A]), stateRootIn(TMP), host); expect(r.seed.toString('hex')).toBe(SEED_A); }); it('strips 0x and trims a trailing newline (MN_SEED from $(cat seed.hex))', async () => { process.env.MN_SEED = `0x${SEED_A}\n`; - const r = await resolveSeedSource(argsFor([]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor([]), stateRootIn(TMP), host); expect(r.seed.toString('hex')).toBe(SEED_A); }); it('rejects a bad-length --seed', async () => { - await expect(resolveSeedSource(argsFor(['--seed', 'aabb']), stateRootIn(TMP))).rejects.toThrow(/64 or 128 hex characters/); + await expect(resolveSeedSource(argsFor(['--seed', 'aabb']), stateRootIn(TMP), host)).rejects.toThrow(/64 or 128 hex characters/); }); it('accepts a 128-hex (64-byte BIP-39) --seed', async () => { const seed64 = '33'.repeat(64); - const r = await resolveSeedSource(argsFor(['--seed', seed64]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor(['--seed', seed64]), stateRootIn(TMP), host); expect(r.seed.length).toBe(64); expect(r.seed.toString('hex')).toBe(seed64); }); it('rejects in-between lengths (only 32- and 64-byte seeds occur)', async () => { - await expect(resolveSeedSource(argsFor(['--seed', '44'.repeat(48)]), stateRootIn(TMP))).rejects.toThrow(/64 or 128 hex characters/); + await expect(resolveSeedSource(argsFor(['--seed', '44'.repeat(48)]), stateRootIn(TMP), host)).rejects.toThrow(/64 or 128 hex characters/); }); it('names MN_SEED in the error when MN_SEED is the bad source', async () => { process.env.MN_SEED = 'zz'; - await expect(resolveSeedSource(argsFor([]), stateRootIn(TMP))).rejects.toThrow(/MN_SEED/); + await expect(resolveSeedSource(argsFor([]), stateRootIn(TMP), host)).rejects.toThrow(/MN_SEED/); }); it('reads a wallet file via --wallet, exposing walletPath + config', async () => { const p = walletFile(SEED_B); - const r = await resolveSeedSource(argsFor(['--wallet', p]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor(['--wallet', p]), stateRootIn(TMP), host); expect(r.seed.toString('hex')).toBe(SEED_B); expect(r.walletPath).toBe(p); expect(r.config).not.toHaveProperty('seed'); @@ -123,7 +127,7 @@ describe('resolveSeedSource', () => { try { establishPassphrase(stateRootIn(TMP), PASSPHRASE); const p = writeSealedWallet(join(TMP, 'sealed.json'), { addresses: {} as WalletPublic['addresses'], createdAt: new Date().toISOString() }, { seed: SEED_B }, PASSPHRASE); - const r = await resolveSeedSource(argsFor(['--wallet', p]), stateRootIn(TMP)); + const r = await resolveSeedSource(argsFor(['--wallet', p]), stateRootIn(TMP), host); expect(r.seed.toString('hex')).toBe(SEED_B); expect(r.config?.isSealed).toBe(true); } finally { @@ -134,15 +138,15 @@ describe('resolveSeedSource', () => { it('requireExplicit throws a labeled error naming every source when none is given', async () => { // No --seed / MN_SEED / --wallet, and requireExplicit disables the active fallback. - await expect(resolveSeedSource(argsFor([]), stateRootIn(TMP), { requireExplicit: true, label: 'address' })) + await expect(resolveSeedSource(argsFor([]), stateRootIn(TMP), host, { requireExplicit: true, label: 'address' })) .rejects.toThrow(/address needs a seed source/); - const msg = await resolveSeedSource(argsFor([]), stateRootIn(TMP), { requireExplicit: true, label: 'address' }).then(() => '', (e: Error) => e.message); + const msg = await resolveSeedSource(argsFor([]), stateRootIn(TMP), host, { requireExplicit: true, label: 'address' }).then(() => '', (e: Error) => e.message); expect(msg).toContain('--seed'); expect(msg).toContain('MN_SEED'); expect(msg).toContain('--wallet'); }); it('resolveSeed returns just the seed buffer', async () => { - expect((await resolveSeed(argsFor(['--seed', SEED_A]), stateRootIn(TMP))).toString('hex')).toBe(SEED_A); + expect((await resolveSeed(argsFor(['--seed', SEED_A]), stateRootIn(TMP), host)).toString('hex')).toBe(SEED_A); }); }); diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index 84a03167..c0278457 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -11,6 +11,10 @@ import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const scratch = { node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws' }; @@ -100,7 +104,7 @@ describe('startServeOrReuse against a running serve', () => { const serve = await fakeServe({ substrateNodeUri: requested.node, indexerWsUri: requested.indexerWS }); try { const messages: string[] = []; - const handle = await startServeOrReuse({ root: emptyRoot, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, onMessage: (m) => messages.push(m) }); + const handle = await startServeOrReuse({ root: emptyRoot, host, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, onMessage: (m) => messages.push(m) }); expect(handle.port).toBe(serve.port); expect(messages).toContain(`Reusing existing mn serve on port ${serve.port}`); await handle.stop(); // a no-op for a reused serve: the fake must still answer @@ -115,7 +119,7 @@ describe('startServeOrReuse against a running serve', () => { const { startServeOrReuse } = await import('../lib/serve-manager.ts'); const serve = await fakeServe({ substrateNodeUri: 'ws://localhost:9944', indexerWsUri: 'ws://localhost:8088/api/v4/graphql/ws' }); try { - await expect(startServeOrReuse({ root: emptyRoot, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested })) + await expect(startServeOrReuse({ root: emptyRoot, host, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested })) .rejects.toThrow(/on a different undeployed chain: node ws:\/\/localhost:9944 \(need ws:\/\/localhost:29944\)/); } finally { await serve.close(); @@ -151,7 +155,7 @@ describe('startServeOrReuse against a running serve', () => { const { startServeOrReuse } = await import('../lib/serve-manager.ts'); const serve = await fakeServe(sameChain, deriveAllAddresses(TWO).undeployed); try { - const handle = await startServeOrReuse({ root: stateRootIn(home), port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' }); + const handle = await startServeOrReuse({ root: stateRootIn(home), host, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' }); expect(handle.port).toBe(serve.port); } finally { await serve.close(); @@ -165,7 +169,7 @@ describe('startServeOrReuse against a running serve', () => { const bob = deriveAllAddresses(BOB).undeployed; const serve = await fakeServe(sameChain, bob); try { - await expect(startServeOrReuse({ root: stateRootIn(home), port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' })) + await expect(startServeOrReuse({ root: stateRootIn(home), host, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' })) .rejects.toThrow(`can't pay for this command: it serves the wallet at ${bob}, and this command pays from two (${deriveAllAddresses(TWO).undeployed})`); } finally { await serve.close(); diff --git a/src/__tests__/settings.test.ts b/src/__tests__/settings.test.ts index 07e8c5cd..4b52b22c 100644 --- a/src/__tests__/settings.test.ts +++ b/src/__tests__/settings.test.ts @@ -42,7 +42,7 @@ describe('a library with no settings source', () => { process.env.MN_PASSPHRASE = 'set in the environment'; try { setSettingsSource(null); - await expect(readPassphrase({ prompter: null })).rejects.toThrow(NoPassphraseError); + await expect(readPassphrase(null)).rejects.toThrow(NoPassphraseError); } finally { delete process.env.MN_PASSPHRASE; } diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index d864ffbb..bf748600 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -43,7 +43,7 @@ async function writeEveryOwnersFiles(root: string): Promise { setConfigValue('network', 'preview', root); setConfigValue('node', 'ws://localhost:29944', root, 'undeployed'); bindCachesToIndexer('undeployed', 'ws://localhost:28088/api/v4/graphql/ws', root); - await createWallet(root, 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret(root)); + await createWallet(root, 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret(createHost(), root)); fs.mkdirSync(accountRecordsDir('undeployed', 'alice', root), { recursive: true }); } diff --git a/src/__tests__/swap-request.test.ts b/src/__tests__/swap-request.test.ts index 7e20c3ef..6cd3af83 100644 --- a/src/__tests__/swap-request.test.ts +++ b/src/__tests__/swap-request.test.ts @@ -13,6 +13,10 @@ import { NotAnOfferError, TermsMismatchError } from '@kuiralabs/midnight-cli-cor import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../lib/swap/request.ts'; import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const NOW = new Date('2026-11-02T12:00:00.000Z'); // A state root with no config: the networks' own endpoints. @@ -41,9 +45,9 @@ describe('the terms', () => { describe('make', () => { it('expires a day on unless --expires-in says', () => { - expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed']), ROOT, NOW).expiresAt).toEqual(new Date(NOW.getTime() + DEFAULT_OFFER_LIFETIME_S * 1000)); - expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', '60']), ROOT, NOW).expiresAt).toEqual(new Date(NOW.getTime() + 60_000)); - expect(() => prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', 'soon']), ROOT, NOW)).toThrow('--expires-in must be a whole number of seconds'); + expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed']), ROOT, host, NOW).expiresAt).toEqual(new Date(NOW.getTime() + DEFAULT_OFFER_LIFETIME_S * 1000)); + expect(prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', '60']), ROOT, host, NOW).expiresAt).toEqual(new Date(NOW.getTime() + 60_000)); + expect(() => prepareMake(parseArgs(['swap', 'make', ...TERMS, '--network', 'undeployed', '--expires-in', 'soon']), ROOT, host, NOW)).toThrow('--expires-in must be a whole number of seconds'); }); }); @@ -61,7 +65,7 @@ describe('take', () => { })); return file; }; - const take = (file: string, terms = TERMS) => prepareTake(parseArgs(['swap', 'take', file, ...terms, '--network', 'undeployed']), ROOT, NOW); + const take = (file: string, terms = TERMS) => prepareTake(parseArgs(['swap', 'take', file, ...terms, '--network', 'undeployed']), ROOT, host, NOW); it('reads a real offer file at the agreed terms', async () => { const { offer, agreed, target } = await take(offerFile()); diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index 1de69fd1..07786070 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -13,6 +13,10 @@ import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midni import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '@kuiralabs/midnight-cli-core/lib/constants'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const HOME = path.join(os.tmpdir(), `midnight-transfer-request-test-${process.pid}`); const WALLETS = path.join(HOME, MIDNIGHT_DIR, WALLETS_DIR_NAME); @@ -34,7 +38,7 @@ function saveWallet(name: string, seed: Buffer, shielded = false): string { return file; } -const request = (...argv: string[]) => resolveTransferRequest(parseArgs(['transfer', ...argv]), path.join(HOME, MIDNIGHT_DIR)); +const request = (...argv: string[]) => resolveTransferRequest(parseArgs(['transfer', ...argv]), path.join(HOME, MIDNIGHT_DIR), host); beforeEach(() => { origHome = process.env.HOME; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 572db67e..8baff4f0 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -11,7 +11,6 @@ import { Buffer } from 'node:buffer'; import { captureCommand } from '../lib/run-command.ts'; import { callDiagnostics } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; @@ -38,13 +37,11 @@ beforeEach(() => { process.env.HOME = home; process.env.MN_NO_LOCAL_DETECT = '1'; notices = []; - setNoticeSink((line) => notices.push(line)); io = captureOutput(); }); afterEach(() => { io.restore(); - setNoticeSink(null); delete process.env.MN_NO_LOCAL_DETECT; process.env.HOME = originalHome; rmSync(home, { recursive: true, force: true }); diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 4a223ce6..98b94b56 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -8,6 +8,10 @@ import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './help import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const TEST_DIR = path.join(os.tmpdir(), `midnight-wallet-test-${process.pid}`); @@ -22,7 +26,7 @@ const VALID_CONFIG: WalletConfig = { const PASSPHRASE = 'correct horse battery staple'; // Unlocking in the test's own home, a plain-text wallet's warning kept out of the output. -const UNLOCK = { root: stateRootIn(TEST_DIR), source: { env: { [PASSPHRASE_ENV]: PASSPHRASE }, prompter: null }, warn: () => {} }; +const UNLOCK = { root: stateRootIn(TEST_DIR), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } }, warn: () => {} }; beforeEach(() => { fs.mkdirSync(TEST_DIR, { recursive: true }); @@ -236,7 +240,7 @@ describe('a wallet written before stagenet', () => { const config = await loadWalletConfig(filePath); expect(config.addresses.stagenet).toBe(stagenetAddress); expect(JSON.parse(fs.readFileSync(filePath, 'utf-8')).addresses).toEqual(VALID_ADDRESSES); - expect(await walletAddress(filePath, 'stagenet', stateRootIn(TEST_DIR))).toBe(stagenetAddress); + expect(await walletAddress(filePath, 'stagenet', stateRootIn(TEST_DIR), host)).toBe(stagenetAddress); }); it('keeps a sealed wallet as written until it is unlocked, then derives and saves its stagenet addresses beside the sealed secret', async () => { diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index b9b3b783..4f71792d 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -13,6 +13,10 @@ import { getActiveWalletName, unlockWallet } from '../lib/wallet-config.ts'; import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); const CHOSEN = 'correct horse battery staple'; // The passphrase as a caller gets it: the first secret in a new home sets it. @@ -27,7 +31,7 @@ beforeEach(async () => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-wallet-create-')); process.env.HOME = home; process.env[PASSPHRASE_ENV] = CHOSEN; - PASSPHRASE = await passphraseForNewSecret(stateRootIn(home)); + PASSPHRASE = await passphraseForNewSecret(host, stateRootIn(home)); }); afterEach(() => { @@ -43,7 +47,7 @@ describe('createWallet', () => { expect(created.file).toBe(walletFilePath(stateRootIn(home), 'alice')); expect(created.mnemonic!.split(' ')).toHaveLength(24); expect(fs.readFileSync(created.file, 'utf8')).not.toContain(created.seed.toString('hex')); - const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) }); + const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) , host}); expect(unlocked.seed).toBe(created.seed.toString('hex')); expect(unlocked.mnemonic).toBe(created.mnemonic); expect(getActiveWalletName(stateRootIn(home))).toBe('alice'); @@ -57,7 +61,7 @@ describe('createWallet', () => { it('keeps a given seed and no mnemonic', async () => { const seed = Buffer.alloc(32, 2); const created = await createWallet(stateRootIn(home), 'carol', walletSecretFrom({ seed }), PASSPHRASE); - const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) }); + const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) , host}); expect(unlocked.seed).toBe(seed.toString('hex')); expect(unlocked.mnemonic).toBeUndefined(); }); @@ -65,10 +69,10 @@ describe('createWallet', () => { it('replaces an existing wallet only when asked', async () => { const first = await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE); await expect(createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE)).rejects.toThrow(`Wallet file already exists: ${first.file}`); - expect((await unlockWallet(first.file, { root: stateRootIn(home) })).seed).toBe(Buffer.alloc(32, 1).toString('hex')); + expect((await unlockWallet(first.file, { root: stateRootIn(home) , host})).seed).toBe(Buffer.alloc(32, 1).toString('hex')); await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, { overwrite: true }); - expect((await unlockWallet(first.file, { root: stateRootIn(home) })).seed).toBe(Buffer.alloc(32, 2).toString('hex')); + expect((await unlockWallet(first.file, { root: stateRootIn(home) , host})).seed).toBe(Buffer.alloc(32, 2).toString('hex')); }); it('refuses a name that is not a simple name, and an invalid mnemonic', () => { diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index 51d5fbe8..1c9acfa1 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -63,6 +63,8 @@ function fakeDustResult(overrides: Partial = {}): DustDirectRe } let TMP: string; +// The repository's lines for the person are dropped: its reads are tested by what they return. +const dropNotice = (): void => {}; beforeEach(() => { TMP = mkdtempSync(join(tmpdir(), 'mn-repo-test-')); }); afterEach(() => { rmSync(TMP, { recursive: true, force: true }); }); @@ -78,7 +80,7 @@ describe('WalletDataRepository — ledger guard', () => { fetchDust, }); - await expect(repo.dust(SEED, NETWORK, { root: TMP })).rejects.toBeInstanceOf(UnsupportedLedgerError); + await expect(repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice })).rejects.toBeInstanceOf(UnsupportedLedgerError); expect(fetchDust).not.toHaveBeenCalled(); }); }); @@ -172,8 +174,8 @@ describe('WalletDataRepository — dust reads', () => { fetchDust: async () => { fetchCalls++; return fakeDustResult(); }, }); - await repo.dust(SEED, NETWORK, { root: TMP }); - const second = await repo.dust(SEED, NETWORK, { root: TMP }); + await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); + const second = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(second.fromCache).toBe(true); expect(fetchCalls).toBe(1); }); @@ -191,11 +193,11 @@ describe('WalletDataRepository — dust reads', () => { }, }); // Before the reset: the cache reaches event 500. - await new WalletDataRepository(deps(null, [], 500)).dust(SEED, NETWORK, { root: TMP }); + await new WalletDataRepository(deps(null, [], 500)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); // After it: the chain's latest event is 106, so the cache can't be from this chain. const startIds: number[] = []; - const view = await new WalletDataRepository(deps(106, startIds, 106)).dust(SEED, NETWORK, { root: TMP }); + const view = await new WalletDataRepository(deps(106, startIds, 106)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startIds).toEqual([0]); expect(view.fromCache).toBe(false); @@ -214,8 +216,8 @@ describe('WalletDataRepository — dust reads', () => { fetchEventTip: async () => eventTip, fetchDust: async (_seed, _net, opts) => { startIds.push(opts.startFromId); return fakeDustResult({ lastAppliedEventId: lastId }); }, }); - await new WalletDataRepository(deps(null, 100)).dust(SEED, NETWORK, { root: TMP }); - await new WalletDataRepository(deps(150, 150)).dust(SEED, NETWORK, { root: TMP }); + await new WalletDataRepository(deps(null, 100)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); + await new WalletDataRepository(deps(150, 150)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startIds).toEqual([0, 101]); }); @@ -243,7 +245,7 @@ describe('WalletDataRepository — dust reads', () => { }, }); - const view = await repo.dust(SEED, NETWORK, { root: TMP }); + const view = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startIds).toEqual([0, 250, 500, 750]); // each call resumed from prior checkpoint expect(view.eventsApplied).toBe(1000); // sum across 4 calls expect(view.fromCache).toBe(false); // we started cold @@ -268,7 +270,7 @@ describe('WalletDataRepository — dust reads', () => { }, }); - const view = await repo.dust(SEED, NETWORK, { root: TMP }); + const view = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(calls).toBe(21); expect(view.partial).toBe(false); expect(view.eventsApplied).toBe(21 * 80_000); @@ -290,7 +292,7 @@ describe('WalletDataRepository — dust reads', () => { }, }); - const view = await repo.dust(SEED, NETWORK, { root: TMP }); + const view = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(calls).toBe(4); expect(view.partial).toBe(true); expect(view.lastAppliedEventId).toBe(499); @@ -306,7 +308,7 @@ describe('WalletDataRepository — dust reads', () => { fetchDust: async () => fakeDustResult({ lastAppliedEventId: 77, eventCount: 78 }), }); - const view = await repo.dust(SEED, NETWORK, { root: TMP }); + const view = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(view.lastAppliedEventId).toBe(77); expect(view.partial).toBe(false); }); @@ -319,7 +321,7 @@ describe('WalletDataRepository — dust reads', () => { fetchDust: async () => fakeDustResult({ lastAppliedEventId: 4242, eventCount: 4243, partial: false }), }); - const view = await repo.dust(SEED, NETWORK, { root: TMP }); + const view = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(view.partial).toBe(false); expect(view.lastAppliedEventId).toBe(4242); }); @@ -351,7 +353,7 @@ describe('WalletDataRepository — dust reads', () => { }, }); - const view = await repo.dust(SEED, NETWORK, { root: TMP }); + const view = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(view.partial).toBe(true); expect(calls).toBe(6); // it used its hour, and no more expect(view.lastAppliedEventId).toBe(nextLastEventId - 250); // the checkpoint it got to @@ -372,12 +374,12 @@ describe('WalletDataRepository — dust reads', () => { const cold = await new WalletDataRepository( deps(async () => fakeDustResult({ lastAppliedEventId: 900, eventCount: 901 })), - ).dust(SEED, NETWORK, { root: TMP }); + ).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(cold.lastAppliedEventId).toBe(900); const warm = await new WalletDataRepository( deps(async () => fakeDustResult({ lastAppliedEventId: -1, eventCount: 0 })), - ).dust(SEED, NETWORK, { root: TMP }); + ).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(warm.lastAppliedEventId).toBe(900); expect(warm.fromCache).toBe(true); }); @@ -396,9 +398,9 @@ describe('WalletDataRepository — dust reads', () => { }, }); - await repo.dust(SEED, NETWORK, { root: TMP }); // 1st: starts at 0 + await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); // 1st: starts at 0 expect(lastStartFromId).toBe(0); - await repo.dust(SEED, NETWORK, { root: TMP, forceFresh: true }); // forceFresh: start back at 0, ignore disk + await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice, forceFresh: true }); // forceFresh: start back at 0, ignore disk expect(fetchCalls).toBe(2); expect(lastStartFromId).toBe(0); }); @@ -414,14 +416,14 @@ describe('WalletDataRepository — invalidation', () => { fetchDust: async () => { dustCalls++; return fakeDustResult(); }, }); - await repo.dust(SEED, NETWORK, { root: TMP }); + await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); await repo.unshielded(SEED, NETWORK); expect(dustCalls).toBe(1); expect(unshieldedCalls).toBe(1); repo.invalidate({ network: NETWORK, root: TMP, seed: SEED }); - await repo.dust(SEED, NETWORK, { root: TMP }); + await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); await repo.unshielded(SEED, NETWORK); expect(dustCalls).toBe(2); expect(unshieldedCalls).toBe(2); @@ -436,12 +438,12 @@ describe('WalletDataRepository — invalidation', () => { fetchDust: async () => { dustCalls++; return fakeDustResult(); }, }); - await repo.dust(SEED, NETWORK, { root: TMP }); + await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); await repo.unshielded(SEED, NETWORK); repo.invalidate({ network: NETWORK, root: TMP, seed: SEED, kinds: ['dust'] }); - const dustAgain = await repo.dust(SEED, NETWORK, { root: TMP }); + const dustAgain = await repo.dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); const unshieldedAgain = await repo.unshielded(SEED, NETWORK); // Network was hit again for dust (memo dropped), but the disk checkpoint // from the first call survived → fromCache is true (delta-resume counts). @@ -481,12 +483,12 @@ describe('WalletDataRepository — dust cache chain-reset guard', () => { }); it('persists the chain genesis hash into the dust cache on save', async () => { - await mkRepo('0xchainA', async () => fakeDustResult()).dust(SEED, NETWORK, { root: TMP }); + await mkRepo('0xchainA', async () => fakeDustResult()).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(readDustCacheFile()?.chainId).toBe('0xchainA'); }); it('wipes a cache from a different chain and re-syncs fresh from event 0', async () => { - await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK, { root: TMP }); + await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(readDustCacheFile()?.chainId).toBe('0xchainA'); // Chain reset: node now reports genesis hash B. A fresh repo must WIPE the @@ -495,7 +497,7 @@ describe('WalletDataRepository — dust cache chain-reset guard', () => { const view = await mkRepo('0xchainB', async (_s, _n, opts) => { startFromSeen = opts.startFromId; return fakeDustResult({ lastAppliedEventId: 2 }); - }).dust(SEED, NETWORK, { root: TMP }); + }).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startFromSeen).toBe(0); // wiped → fresh, not resumed expect(view.fromCache).toBe(false); @@ -503,13 +505,13 @@ describe('WalletDataRepository — dust cache chain-reset guard', () => { }); it('resumes (does NOT wipe) when the genesis hash is unchanged', async () => { - await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK, { root: TMP }); + await mkRepo('0xchainA', async () => fakeDustResult({ lastAppliedEventId: 5 })).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); let startFromSeen = -999; const view = await mkRepo('0xchainA', async (_s, _n, opts) => { startFromSeen = opts.startFromId; return fakeDustResult({ lastAppliedEventId: 5 }); - }).dust(SEED, NETWORK, { root: TMP }); + }).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startFromSeen).toBe(6); // resumed from lastAppliedEventId + 1 expect(view.fromCache).toBe(true); diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts index f6e03e0a..647bc3bd 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/src/__tests__/wallet-session.test.ts @@ -8,7 +8,7 @@ import { DustAddress, MidnightBech32m, ShieldedAddress, UnshieldedAddress } from import { sessionOver, type WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; import { deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; +import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; @@ -34,7 +34,7 @@ function openSession(options: { bundleOverrides?: Parameters { connector.dispose(); }); const session: WalletSession = sessionOver('undeployed', { connector, stop }, options.readTransaction ?? (() => [])); return { session, bundle, revert, stop }; @@ -146,7 +146,7 @@ describe('wallet session', () => { /** A wallet opened in this process whose swaps answer as `initSwap` says, and its stop. */ function openedWith(initSwap: () => Promise) { const bundle = createBundleStub({ initSwap }); - const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { approveAll: true } }); + const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); return { connector, stop: vi.fn(async () => { connector.dispose(); }) }; } diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index dd716cf1..5c35ea50 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -39,7 +39,7 @@ describe('walletStateToRestore', () => { const checkpoint = ledger.DustLocalState.deserialize(Buffer.from(DUST_STATE_OWNED_HEX, 'hex')); saveDustCache('undeployed', dustPublicKeyHexFromSeed(SEED), checkpoint, 395_185, root); - const state = await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root); + const state = await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root, () => {}); expect(state, 'a wallet to restore, not one built from its keys').not.toBeNull(); const dust = JSON.parse(state!.dust) as { offset: string; state: string }; @@ -48,6 +48,6 @@ describe('walletStateToRestore', () => { }, 30_000); it('with no saved wallet and no checkpoint, is null: the wallet is built from its keys', async () => { - expect(await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root)).toBeNull(); + expect(await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root, () => {})).toBeNull(); }); }); diff --git a/src/__tests__/ws-rpc.test.ts b/src/__tests__/ws-rpc.test.ts index d8634ca1..ec7260df 100644 --- a/src/__tests__/ws-rpc.test.ts +++ b/src/__tests__/ws-rpc.test.ts @@ -1,6 +1,10 @@ import { describe, it, expect, afterEach } from 'vitest'; import { WebSocket } from 'ws'; import { createRpcServer, createApiError, type RpcServer } from '../lib/ws-rpc.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +// The host the servers run in: notices dropped. +const host = createHost(); // Test helpers function sendRpc(ws: WebSocket, id: number, method: string, params?: Record): void { @@ -48,6 +52,7 @@ describe('ws-rpc', () => { it('starts a WebSocket server on the given port', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, }); @@ -59,7 +64,7 @@ describe('ws-rpc', () => { it('with refuseBrowsers, refuses a connection carrying an Origin (any web page) and accepts mn\'s own scripts', async () => { const port = nextPort(); - server = createRpcServer({ port, handlers: {}, refuseBrowsers: true }); + server = createRpcServer({ host, port, handlers: {}, refuseBrowsers: true }); await server.ready; const fromPage = new WebSocket(`ws://127.0.0.1:${port}`, { origin: 'https://evil.example' }); @@ -78,7 +83,7 @@ describe('ws-rpc', () => { it('without refuseBrowsers, a browser dApp with an Origin still connects (plain mn serve)', async () => { const port = nextPort(); - server = createRpcServer({ port, handlers: {} }); + server = createRpcServer({ host, port, handlers: {} }); await server.ready; const fromPage = new WebSocket(`ws://127.0.0.1:${port}`, { origin: 'http://localhost:5173' }); await new Promise((resolve, reject) => { fromPage.once('open', resolve); fromPage.once('error', reject); }); @@ -89,6 +94,7 @@ describe('ws-rpc', () => { it('dispatches method calls to handlers', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: { echo: async (params) => params, @@ -110,6 +116,7 @@ describe('ws-rpc', () => { it('returns method not found for unknown methods', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, }); @@ -129,7 +136,7 @@ describe('ws-rpc', () => { 'treats %s, inherited from Object.prototype, as an unknown method', async (method) => { const port = nextPort(); - server = createRpcServer({ port, handlers: { getDustBalance: async () => 'ok' } }); + server = createRpcServer({ host, port, handlers: { getDustBalance: async () => 'ok' } }); const ws = await connectClient(port); clients.push(ws); @@ -145,6 +152,7 @@ describe('ws-rpc', () => { it('returns parse error for invalid JSON', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, }); @@ -162,6 +170,7 @@ describe('ws-rpc', () => { it('returns invalid request for malformed JSON-RPC', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, }); @@ -179,6 +188,7 @@ describe('ws-rpc', () => { it('serializes bigint values as strings in responses', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: { getBalance: async () => ({ balance: 5000000n }), @@ -198,6 +208,7 @@ describe('ws-rpc', () => { it('maps APIError to JSON-RPC error with data', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: { reject: async () => { @@ -224,6 +235,7 @@ describe('ws-rpc', () => { it('tracks connections', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, }); @@ -241,6 +253,7 @@ describe('ws-rpc', () => { it('returns internal error for non-APIError exceptions', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: { broken: async () => { throw new TypeError('Cannot read property of undefined'); }, @@ -263,6 +276,7 @@ describe('ws-rpc', () => { const disconnections: string[] = []; const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, onDisconnect: (conn) => disconnections.push(conn.id), @@ -284,6 +298,7 @@ describe('ws-rpc', () => { const events: string[] = []; server = createRpcServer({ + host, port, handlers: {}, onConnect: () => events.push('connect'), @@ -305,6 +320,7 @@ describe('ws-rpc', () => { const port = nextPort(); const counts: number[] = []; server = createRpcServer({ + host, port, handlers: { ping: async () => 'pong', @@ -331,6 +347,7 @@ describe('ws-rpc', () => { const port = nextPort(); const responses: Array<{ method: string; result: unknown; error?: { message: string; code?: string } }> = []; server = createRpcServer({ + host, port, handlers: { echo: async (params) => params, @@ -356,6 +373,7 @@ describe('ws-rpc', () => { const port = nextPort(); const responses: Array<{ method: string; result?: unknown; error?: { message: string; code?: string } }> = []; server = createRpcServer({ + host, port, handlers: { fail: async () => { throw new Error('broken'); }, @@ -381,6 +399,7 @@ describe('ws-rpc', () => { const port = nextPort(); let capturedDuration = -1; server = createRpcServer({ + host, port, handlers: { slow: async () => { @@ -408,6 +427,7 @@ describe('ws-rpc', () => { const port = nextPort(); let capturedId = ''; server = createRpcServer({ + host, port, handlers: { whoami: async (_params, context) => { @@ -453,6 +473,7 @@ describe('ws-rpc', () => { it('closes all connections and the server', async () => { const port = nextPort(); server = createRpcServer({ + host, port, handlers: {}, }); @@ -472,6 +493,7 @@ describe('ws-rpc', () => { const disconnections: string[] = []; const p = nextPort(); server = createRpcServer({ + host, port: p, handlers: {}, onDisconnect: (conn) => disconnections.push(conn.id), @@ -494,7 +516,7 @@ describe('createRpcServer readiness', () => { // `mn serve` must not report ready (or keep running) when its port is taken: // a client would then talk to whatever already listens there. it('resolves ready once listening', async () => { - const server = createRpcServer({ port: 0, handlers: {} }); + const server = createRpcServer({ host, port: 0, handlers: {} }); await expect(server.ready).resolves.toBeUndefined(); await server.close(); }); @@ -507,7 +529,7 @@ describe('createRpcServer readiness', () => { const origWrite = process.stderr.write; process.stderr.write = (() => true) as any; try { - const server = createRpcServer({ port, handlers: {} }); + const server = createRpcServer({ host, port, handlers: {} }); await expect(server.ready).rejects.toMatchObject({ code: 'EADDRINUSE' }); await server.close(); } finally { diff --git a/src/commands/address.ts b/src/commands/address.ts index 5da3bcbc..63088021 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -12,7 +12,7 @@ import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context' export default async function addressCommand(args: ParsedArgs, ctx: CallContext): Promise { // `address` is a seed-derivation tool with no active-wallet notion → requireExplicit. const root = ctx.config.paths.stateRoot; - const seedBuffer = await resolveSeed(args, root, { requireExplicit: true, label: 'address' }); + const seedBuffer = await resolveSeed(args, root, ctx.host, { requireExplicit: true, label: 'address' }); const indexStr = getFlag(args, 'index'); const keyIndex = indexStr !== undefined ? parseInt(indexStr, 10) : 0; diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 1a51d688..3d45a69e 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -11,7 +11,7 @@ import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAddress } from '../lib/wallet-config.ts'; +import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAddress, type UnlockHost } from '../lib/wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -61,7 +61,7 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) const walletFlag = getFlag(args, 'wallet'); const isShielded = hasFlag(args, 'shielded') || (walletFlag !== undefined && walletFlag.startsWith('mn_shield-addr_')); - const destination = await resolveDestination(args, root, networkName, networkConfig, isShielded); + const destination = await resolveDestination(args, root, networkName, networkConfig, isShielded, ctx.host); if (isShielded) { return shieldedAirdrop(args, destination as ShieldedDestination, amountNight, networkName, networkConfig, ctx); @@ -93,6 +93,7 @@ async function resolveDestination( networkName: NetworkName, networkConfig: NetworkConfig, isShielded: boolean, + host: UnlockHost, ): Promise { const walletFlag = getFlag(args, 'wallet'); @@ -106,13 +107,13 @@ async function resolveDestination( if (isShielded) { // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase // (unless the network was added after the wallet was written). - const stored = await walletShieldedAddress(walletPath, networkName, root); + const stored = await walletShieldedAddress(walletPath, networkName, root, host); if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${networkName}.`); const decoded = await resolveAddressDestination(stored, root, networkName, true) as ShieldedDestination; return { kind: 'wallet', bech32m: decoded.bech32m, walletPath }; } - return { kind: 'address', address: await walletAddress(walletPath, networkName, root) }; + return { kind: 'address', address: await walletAddress(walletPath, networkName, root, host) }; } async function resolveAddressDestination( @@ -181,6 +182,7 @@ async function unshieldedAirdrop( try { const result = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.airdrop({ root: ctx.config.paths.stateRoot, + notice: ctx.host.notice, networkConfig, recipientAddress, amountNight, @@ -283,6 +285,7 @@ async function shieldedAirdrop( const txHash = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.shieldedTransfer({ seed: genesisSeedBuffer, root: ctx.config.paths.stateRoot, + notice: ctx.host.notice, network: networkName, networkConfig, recipient: userShieldedAddrStr, diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 15a7f233..96f7dcfb 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -176,7 +176,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); ctx.diagnostics.line('balance', `network=${networkName} indexerWS=${networkConfig.indexerWS}`); // Seed source: --seed → MN_SEED → --wallet → active wallet (shared resolver). - const { seed: seedBuffer, walletPath, config } = await resolveSeedSource(args, root); + const { seed: seedBuffer, walletPath, config } = await resolveSeedSource(args, root, ctx.host); ctx.diagnostics.line('balance', `wallet path=${walletPath ?? '(from --seed/MN_SEED)'}`); // Derive the unshielded address from the seed so a --seed/MN_SEED caller (no wallet // file) behaves identically to a named wallet — for a wallet this equals the stored one. diff --git a/src/commands/cache.ts b/src/commands/cache.ts index 9b20a8c0..15c43853 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -29,7 +29,7 @@ export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): if (walletFlag) { // Clear cache for a specific wallet const walletPath = resolveWalletPath(root, walletFlag); - const config = await unlockWallet(walletPath, { root }); + const config = await unlockWallet(walletPath, { root, host: ctx.host }); // Cancelled while the wallet was unlocked: no cache is cleared. throwIfCancelled(ctx.signal); const networkName = resolveNetworkName({ args, configDir: root }); diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index d352ec39..dbc7d0d2 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -219,7 +219,7 @@ export const contractDefinition: CommandDefinition = { const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; - await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy', root).network, root); + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy', root, call.host).network, root); await checkSendingWallet(params, root); }, }, @@ -254,7 +254,7 @@ export const contractDefinition: CommandDefinition = { const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; - await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call', root).network, root); + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call', root, call.host).network, root); await checkSendingWallet(params, root); }, }, diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 026b849d..c1c4f757 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -118,7 +118,7 @@ async function handleDeploy(args: ParsedArgs, payer: Payer, ctx: CallContext): P ctx.output.stderr('\n' + header('Contract Deploy') + '\n\n'); } - const target = resolvePayingTarget(args, 'contract', 'deploy', ctx.config.paths.stateRoot); + const target = resolvePayingTarget(args, 'contract', 'deploy', ctx.config.paths.stateRoot, ctx.host); const { network } = target; await assertContractRunsOn(info, network, target.root); @@ -192,7 +192,7 @@ async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Pro ctx.output.stderr('\n' + header('Contract Call') + '\n\n'); } - const target = resolvePayingTarget(args, 'contract', 'call', ctx.config.paths.stateRoot); + const target = resolvePayingTarget(args, 'contract', 'call', ctx.config.paths.stateRoot, ctx.host); const { network } = target; await assertContractRunsOn(info, network, target.root); @@ -238,7 +238,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { const { runState } = await import('../lib/contract/runner.ts'); - const { network, root, networkConfig } = resolvePayingTarget(args, 'contract', 'state', ctx.config.paths.stateRoot); + const { network, root, networkConfig } = resolvePayingTarget(args, 'contract', 'state', ctx.config.paths.stateRoot, ctx.host); if (!jsonMode) { ctx.output.stderr('\n' + header('Contract State') + '\n\n'); diff --git a/src/commands/dev.ts b/src/commands/dev.ts index f54cebe0..4a15d595 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -73,6 +73,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr amountNight: DEFAULT_DEV_AIRDROP_AMOUNT, signal, sdkWarnings: ctx.sdkWarnings, + host: ctx.host, onProgress: (name, phase) => { const label = { creating: 'generating', @@ -155,7 +156,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr // Unlock mn's passphrase now, while stdin is still a plain terminal: once the // dispatcher reads keys in raw mode, a passphrase typed for [d]'s deploy would // be read as dev keystrokes too. Asked once per run; MN_PASSPHRASE asks nothing. - if (isPassphraseSet(ctx.config.paths.stateRoot)) await unlockPassphrase(ctx.config.paths.stateRoot); + if (isPassphraseSet(ctx.config.paths.stateRoot)) await unlockPassphrase(ctx.host, ctx.config.paths.stateRoot); const abortController = new AbortController(); const stopRequest = () => { @@ -211,6 +212,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr q: () => stopRequest(), }, onInterrupt: stopRequest, + notice: ctx.host.notice, }); await new Promise((resolvePromise) => { @@ -245,7 +247,7 @@ async function deployContract(project: ProjectInfo, ctx: CallContext): Promise spinner.update( @@ -262,6 +263,7 @@ async function dustRegister( try { const result = await (await engineFor(network, ctx.config.paths.stateRoot)).wallet.registerDust(seedBuffer, networkConfig, { root: ctx.config.paths.stateRoot, + notice: ctx.host.notice, signal: ctx.signal, sdkWarnings: ctx.sdkWarnings, log: ctx.diagnostics.line, @@ -324,6 +326,7 @@ async function dustStatusDirect( try { const view = await (await engineFor(network, ctx.config.paths.stateRoot)).wallet.dustBalance(seedBuffer, networkConfig, { root: ctx.config.paths.stateRoot, + notice: ctx.host.notice, forceFresh: !useCache, signal: ctx.signal, log: ctx.diagnostics.line, diff --git a/src/commands/generate.ts b/src/commands/generate.ts index 9f942011..644a74f3 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -76,7 +76,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext }; const secrets = mnemonic ? { seed: seedBuffer.toString('hex'), mnemonic } : { seed: seedBuffer.toString('hex') }; - const passphrase = await passphraseForNewSecret(root, { signal: ctx.signal }); + const passphrase = await passphraseForNewSecret(ctx.host, root, { signal: ctx.signal }); // Cancelled while the passphrase was asked for: no wallet is written, and no new passphrase saved. throwIfCancelled(ctx.signal); const savedPath = writeSealedWallet(targetPath, config, secrets, passphrase, { overwrite: hasFlag(args, 'force') }); diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index 66ed780a..67a575fd 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -6,7 +6,7 @@ import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmati async function checkGrant(params: Readonly>, call: ToolCheckCall) { const { prepareGrant } = await import('../lib/grant/prepare.ts'); const root = call.host.paths().stateRoot; - const prepared = await prepareGrant(call.argv(), root); + const prepared = await prepareGrant(call.argv(), root, call.host); const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined)); return prepared; diff --git a/src/commands/grant.ts b/src/commands/grant.ts index b84b2d8a..dec5c296 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -52,7 +52,7 @@ function shortOfShieldedNight(held: bigint, value: bigint): UsageError { } export default async function grantCommand(args: ParsedArgs, ctx: CallContext): Promise { - const { request, target, walletName, recordsDir, account } = await prepareGrant(args, ctx.config.paths.stateRoot); + const { request, target, walletName, recordsDir, account } = await prepareGrant(args, ctx.config.paths.stateRoot, ctx.host); const jsonMode = hasFlag(args, 'json'); const walletFlag = getFlag(args, 'wallet'); const spinnerFor = (label: string): Spinner => (jsonMode ? ctx.progress.silent() : ctx.progress.start(label)); @@ -94,7 +94,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, if (request.subcommand === 'device' && request.action === 'new') { const { createPendingDevice, openAccountKey, ownJoinCode } = await import('../lib/grant/sealed-account.ts'); const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('../lib/passphrase.ts'); - const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(target.root) : await passphraseForNewSecret(target.root); + const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(ctx.host, target.root) : await passphraseForNewSecret(ctx.host, target.root); const device = createPendingDevice(recordsDir, passphrase); const code = ownJoinCode(recordsDir, openAccountKey(recordsDir, passphrase), device); spinner.stop('Device ready'); @@ -114,7 +114,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const { importAccount } = await import('../lib/grant/account-backup.ts'); const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('../lib/passphrase.ts'); try { - const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(target.root) : await passphraseForNewSecret(target.root); + const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(ctx.host, target.root) : await passphraseForNewSecret(ctx.host, target.root); const { contractAddress } = await importAccount(recordsDir, target.network, passphrase, request.file); spinner.stop('Imported'); if (jsonMode) ctx.output.result({ subcommand: request.subcommand, network: target.network, wallet: walletName, ownerKey: 'sealed', address: contractAddress }); @@ -131,7 +131,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const owned: GrantAccount = await openGrantAccount(target.networkConfig, recordsDir, (line) => { spinner.update(line); throwIfCancelled(ctx.signal); - }, { root: target.root }); + }, { root: target.root, host: ctx.host }); // How the account's owner key and records are kept: sealed, or in plain text until `wallet protect`. const common = { subcommand: request.subcommand, network: target.network, wallet: walletName, ownerKey: owned.protection }; @@ -232,7 +232,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, if (owned.protection !== 'sealed') throw new UsageError('The account is not protected: its devices are managed once it is. Encrypt it first: midnight wallet protect'); const { openAccountKey, sealedDeviceList } = await import('../lib/grant/sealed-account.ts'); const { unlockPassphrase } = await import('../lib/passphrase.ts'); - const passphrase = await unlockPassphrase(target.root); + const passphrase = await unlockPassphrase(ctx.host, target.root); const devices = sealedDeviceList(recordsDir, openAccountKey(recordsDir, passphrase)); if (owned.ownCode === undefined) throw new Error('A sealed account names its own device code'); const own = owned.ownCode(); @@ -281,7 +281,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, case 'export': { const { exportAccount } = await import('../lib/grant/account-backup.ts'); const { unlockPassphrase } = await import('../lib/passphrase.ts'); - const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(target.root), request.file); + const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(ctx.host, target.root), request.file); spinner.stop('Written'); if (jsonMode) { ctx.output.result({ ...common, address: outcome.contractAddress, file: outcome.file }); diff --git a/src/commands/info.ts b/src/commands/info.ts index caefa90a..9c15f613 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -14,7 +14,7 @@ export default async function infoCommand(args: ParsedArgs, ctx: CallContext): P const resolvedPath = resolveWalletPath(root, getFlag(args, 'wallet')); const config = await loadWalletConfig(resolvedPath); const activeNetwork = resolveNetworkName({ args, configDir: root }); - const activeAddress = await walletAddress(resolvedPath, activeNetwork, root); + const activeAddress = await walletAddress(resolvedPath, activeNetwork, root, ctx.host); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 6cf1505d..69370f79 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -52,7 +52,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // ── Load wallet ── const root = ctx.config.paths.stateRoot; - const config = await unlockWallet(resolveWalletPath(root, getFlag(args, 'wallet')), { root }); + const config = await unlockWallet(resolveWalletPath(root, getFlag(args, 'wallet')), { root, host: ctx.host }); const seedBuffer = Buffer.from(config.seed, 'hex'); const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); @@ -101,7 +101,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // preview/preprod). dApps there can only do unshielded + dust anyway. const syncMode = shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded')) ? 'full' : 'lite'; - await (await engineFor(networkName, root)).wallet.serveWallet({ seed: seedBuffer, root, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, + await (await engineFor(networkName, root)).wallet.serveWallet({ seed: seedBuffer, root, notice: ctx.host.notice, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, onStatus: (s) => spinner.update(s), onSyncProgress: (applied, highest) => { if (highest > 0) { @@ -166,7 +166,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // Reads answer from the state the Dust wait ended on, and from every // later one that is synced by the rule the sync used. connector = served.connect({ - approvalOptions: { approveAll, approveFees, autoApproveReads }, + approvalOptions: { approveAll, approveFees, autoApproveReads, prompter: ctx.host.prompter, notice: ctx.host.notice }, feeLimits, callbacks: phaseCallbacks, }); @@ -174,6 +174,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // ── Start WebSocket server ── server = createRpcServer({ + host: ctx.host, port, handlers: connector.handlers, onConnect: (conn) => { diff --git a/src/commands/swap.definition.ts b/src/commands/swap.definition.ts index 034624c2..37884be7 100644 --- a/src/commands/swap.definition.ts +++ b/src/commands/swap.definition.ts @@ -10,7 +10,7 @@ function describeTerms(params: Readonly>): string { /** A take can run: the offer file is one, for this network, with the agreed terms, not expired. */ async function checkTake(call: ToolCheckCall) { const { prepareTake } = await import('../lib/swap/request.ts'); - return prepareTake(call.argv(), call.host.paths().stateRoot, new Date()); + return prepareTake(call.argv(), call.host.paths().stateRoot, call.host, new Date()); } export const swapDefinition: CommandDefinition = { @@ -167,7 +167,7 @@ export const swapDefinition: CommandDefinition = { }, async check(_params, call) { const { prepareMake } = await import('../lib/swap/request.ts'); - prepareMake(call.argv(), call.host.paths().stateRoot, new Date()); + prepareMake(call.argv(), call.host.paths().stateRoot, call.host, new Date()); }, }, order: 40, diff --git a/src/commands/swap.ts b/src/commands/swap.ts index 5d8e0924..b9bc91cf 100644 --- a/src/commands/swap.ts +++ b/src/commands/swap.ts @@ -34,7 +34,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P switch (args.subcommand) { case 'make': { - const { target, terms, expiresAt, out } = prepareMake(args, root, now); + const { target, terms, expiresAt, out } = prepareMake(args, root, ctx.host, now); if (out !== undefined && existsSync(out)) throw new UsageError(`${out} already exists; an offer file is never written over another`); if (!jsonMode) { ctx.output.stderr('\n' + header('Swap: make an offer') + '\n\n'); @@ -42,7 +42,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P ctx.output.stderr(keyValue('Gives', legText(terms.give)) + '\n'); ctx.output.stderr(keyValue('Wants', legText(terms.want)) + '\n\n'); } - const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root); + const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root, ctx.host); const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Making the offer (proving its half)...'); @@ -66,7 +66,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P } case 'inspect': { - const target = resolvePayingTarget(args, 'swap', 'inspect', root); + const target = resolvePayingTarget(args, 'swap', 'inspect', root, ctx.host); const offer = await readOfferArg(args, target); const spinner = spinnerFor('Asking the indexer whether it is still live...'); const { expired, spends } = await standingOf(offer, target.networkConfig, now, ctx.signal); @@ -87,7 +87,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P } case 'take': { - const { target, offer, agreed } = await prepareTake(args, root, now); + const { target, offer, agreed } = await prepareTake(args, root, ctx.host, now); if (!jsonMode) { ctx.output.stderr('\n' + header('Swap: take an offer') + '\n\n'); ctx.output.stderr(keyValue('Offer', offer.envelope.id) + '\n'); @@ -117,8 +117,8 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P case 'cancel': { const id = args.positionals[0]; if (id === undefined) throw new UsageError('swap cancel needs the offer\'s id (8 characters of it at least): midnight swap cancel '); - const target = resolvePayingTarget(args, 'swap', 'cancel', root); - const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root); + const target = resolvePayingTarget(args, 'swap', 'cancel', root, ctx.host); + const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root, ctx.host); const session = await payerFor('swap cancel', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Spending the offer\'s coins back to this wallet...'); @@ -143,8 +143,8 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P } case 'list': { - const target = resolvePayingTarget(args, 'swap', 'list', root); - const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root); + const target = resolvePayingTarget(args, 'swap', 'list', root, ctx.host); + const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root, ctx.host); const spinner = spinnerFor('Asking the indexer about each open offer...'); const listed = await listOffers(root, target.network, target.networkConfig, address, now, ctx.signal); spinner.stop(`${listed.length} offer${listed.length === 1 ? '' : 's'}`); diff --git a/src/commands/test.ts b/src/commands/test.ts index 108a87b5..6a8ef682 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -446,7 +446,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): } // Prep context for resource tracking + teardown - const prep = createPrepContext(ctx.config.paths.stateRoot, ctx.sdkWarnings, signal); + const prep = createPrepContext(ctx.config.paths.stateRoot, ctx.host, ctx.sdkWarnings, signal); const prepResults: PrepStepResult[] = []; // Register teardown on abort diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 1558fd69..2177b3c7 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -112,7 +112,7 @@ export const transferDefinition: CommandDefinition = { }, async check(_params, call) { const { resolveTransferRequest } = await import('../lib/transfer-request.ts'); - await resolveTransferRequest(call.argv(), call.host.paths().stateRoot); + await resolveTransferRequest(call.argv(), call.host.paths().stateRoot, call.host); }, }, order: 12, diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index c2a48c9c..c947ab7b 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -17,7 +17,7 @@ import { receiptText } from '../ui/receipt.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); - const request = await resolveTransferRequest(args, ctx.config.paths.stateRoot); + const request = await resolveTransferRequest(args, ctx.config.paths.stateRoot, ctx.host); return request.shielded ? shieldedTransfer(args, request, ctx) : unshieldedTransfer(args, request, ctx); } @@ -29,7 +29,7 @@ async function unshieldedTransfer( ctx: CallContext, ): Promise { const root = ctx.config.paths.stateRoot; - const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root })).seed, 'hex'); + const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root, host: ctx.host })).seed, 'hex'); const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); const address = config.addresses[networkName]; @@ -52,6 +52,7 @@ async function unshieldedTransfer( try { const result = await (await engineFor(networkName, root)).wallet.transfer({ root, + notice: ctx.host.notice, seedBuffer, networkConfig, recipientAddress, @@ -127,7 +128,7 @@ async function shieldedTransfer( ): Promise { const amount = nightToMicro(amountNight); const root = ctx.config.paths.stateRoot; - const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root })).seed, 'hex'); + const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root, host: ctx.host })).seed, 'hex'); const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); @@ -152,6 +153,7 @@ async function shieldedTransfer( const txHash = await (await engineFor(networkName, root)).wallet.shieldedTransfer({ seed: seedBuffer, root, + notice: ctx.host.notice, network: networkName, networkConfig, recipient: recipientAddress, diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index 0bf49146..37321ad3 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -83,7 +83,7 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise const secret = walletSecretFrom(seedHex !== undefined ? { seed: parseSeedHex(seedHex, '--seed') } : { mnemonic: mnemonicStr }); - const passphrase = await passphraseForNewSecret(root, { signal: ctx.signal }); + const passphrase = await passphraseForNewSecret(ctx.host, root, { signal: ctx.signal }); // Cancelled while the passphrase was asked for: no wallet is written, and no new passphrase saved. throwIfCancelled(ctx.signal); // Checked above: an existing wallet is replaced only with --force. @@ -240,7 +240,7 @@ async function walletInfo(args: ParsedArgs, ctx: CallContext): Promise { const config = await loadWalletConfig(walletPath); const isActive = name === getActiveWalletName(root); const networkName = resolveNetworkName({ args, configDir: root }); - const activeAddress = await walletAddress(walletPath, networkName, root); + const activeAddress = await walletAddress(walletPath, networkName, root, ctx.host); if (hasFlag(args, 'json')) { // Agent-slim shape: drops the per-network addresses map (3× repetition @@ -327,7 +327,7 @@ async function walletSeed(args: ParsedArgs, ctx: CallContext): Promise { const walletPath = resolveWalletPath(root, name); // The seed and mnemonic, opened with mn's passphrase. - const raw = await unlockWallet(walletPath, { root }); + const raw = await unlockWallet(walletPath, { root, host: ctx.host }); // `--entropy` adds the 32-byte BIP-39 entropy (derived from the mnemonic) // alongside the 64-byte PBKDF2 seed. They're DIFFERENT values that produce @@ -391,7 +391,7 @@ async function walletSeed(args: ParsedArgs, ctx: CallContext): Promise { /** Sets mn's passphrase where none is set, and seals every plain-text wallet under it. */ async function walletProtect(args: ParsedArgs, ctx: WalletCommandContext): Promise { const root = ctx.config.paths.stateRoot; - const passphrase = await passphraseForNewSecret(root, { signal: ctx.signal }); + const passphrase = await passphraseForNewSecret(ctx.host, root, { signal: ctx.signal }); // Cancelled, it stops between wallets and before a protector, never in the middle of a file. const report = await protectAllWallets(root, passphrase, ctx.signal); const sealed = report.filter((w) => w.sealedNow).map((w) => w.name); @@ -400,7 +400,7 @@ async function walletProtect(args: ParsedArgs, ctx: WalletCommandContext): Promi const results: Array<{ name: string; result: ProtectorResult }> = []; for (const protector of ctx.protectors ?? []) { throwIfCancelled(ctx.signal); - results.push({ name: protector.name, result: await protector.protect(root, passphrase, (wallet) => coinKeyOfWallet(root, wallet)) }); + results.push({ name: protector.name, result: await protector.protect(root, passphrase, (wallet) => coinKeyOfWallet(root, ctx.host, wallet)) }); } if (hasFlag(args, 'json')) { ctx.output.result({ sealed, alreadySealed, ...Object.fromEntries(results.map(({ name, result }) => [name, result.report])) }); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 5de35267..ae186984 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -12,9 +12,8 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; import { installSdkNoiseFilters } from './sdk-noise.ts'; -import { setNoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { setPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; @@ -33,9 +32,7 @@ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host prompter, sdkWarnings: installSdkNoiseFilters(), }); - setNoticeSink(host.notice); setSettingsSource(host.settings); - setPrompter(host.prompter); setEngineLoader(loadInstalledEngine); return host; } diff --git a/src/lib/dev/deploy.ts b/src/lib/dev/deploy.ts index 649b5bcd..ed3c8ba2 100644 --- a/src/lib/dev/deploy.ts +++ b/src/lib/dev/deploy.ts @@ -7,10 +7,11 @@ import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { deployContract, type DeployedContract } from '../contract/deploy.ts'; import { resolveContractDeployRequest } from '../contract/request.ts'; import { resolvePayingTarget, type Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -export async function deployDevContract(root: string, projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { +export async function deployDevContract(root: string, host: Host, projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { // The deploy as `mn contract deploy --path --wallet --network ` reads it. const args: ParsedArgs = { command: 'contract', @@ -20,7 +21,7 @@ export async function deployDevContract(root: string, projectRoot: string, walle }; return deployContract({ request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', root), + target: resolvePayingTarget(args, 'contract', 'deploy', root, host), wallet, payer, progress: () => progress, diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 4c8311d7..341604f3 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -4,7 +4,7 @@ // left untouched (the user can `mn wallet remove ` to force re-setup). import { existsSync } from 'node:fs'; -import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet } from '../wallet-config.ts'; +import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet, type UnlockHost } from '../wallet-config.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; import { passphraseForNewSecret } from '../passphrase.ts'; import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -45,15 +45,15 @@ interface ProvisionRun { signal?: AbortSignal; } -/** The steps to run; without them, the wallet functions, whose SDK runs keep their warnings to the provisioning call's `sdkWarnings`. */ -export type ProvisionOptions = ProvisionRun & ({ steps: ProvisionSteps } | { sdkWarnings: CallSdkWarnings }); +/** The steps to run; without them, the wallet functions, run in `host`, whose SDK runs keep their warnings to the provisioning call's `sdkWarnings`. */ +export type ProvisionOptions = ProvisionRun & ({ steps: ProvisionSteps } | { sdkWarnings: CallSdkWarnings; host: UnlockHost }); /** The steps through the wallet functions, on `network` (resolved once, for every wallet). */ -function walletSteps(root: string, network: NetworkConfig, sdkWarnings: CallSdkWarnings): ProvisionSteps { +function walletSteps(root: string, host: UnlockHost, network: NetworkConfig, sdkWarnings: CallSdkWarnings): ProvisionSteps { return { - generate: (name, signal) => generateWallet(root, name, signal), - airdrop: (name, amountNight, signal) => airdropToWallet(root, network, name, amountNight, signal, sdkWarnings), - registerDust: (name, signal) => registerWalletDust(root, network, name, signal, sdkWarnings), + generate: (name, signal) => generateWallet(root, host, name, signal), + airdrop: (name, amountNight, signal) => airdropToWallet(root, host, network, name, amountNight, signal, sdkWarnings), + registerDust: (name, signal) => registerWalletDust(root, host, network, name, signal, sdkWarnings), needsDust: (name, signal) => walletNeedsDust(root, network, name, signal), }; } @@ -70,7 +70,7 @@ function walletSteps(root: string, network: NetworkConfig, sdkWarnings: CallSdkW */ export async function provisionDevWallets(opts: ProvisionOptions): Promise { const { root } = opts; - const steps = 'steps' in opts ? opts.steps : walletSteps(root, undeployedNetwork(root), opts.sdkWarnings); + const steps = 'steps' in opts ? opts.steps : walletSteps(root, opts.host, undeployedNetwork(root), opts.sdkWarnings); const results: ProvisionedWallet[] = []; const created: string[] = []; @@ -147,17 +147,17 @@ function undeployedNetwork(root: string): NetworkConfig { }).config; } -async function generateWallet(root: string, name: string, signal?: AbortSignal): Promise { - const passphrase = await passphraseForNewSecret(root); +async function generateWallet(root: string, host: UnlockHost, name: string, signal?: AbortSignal): Promise { + const passphrase = await passphraseForNewSecret(host, root); // Cancelled while the passphrase was asked for: no wallet is written. throwIfCancelled(signal); await createWallet(root, name, walletSecretFrom(), passphrase); } -async function airdropToWallet(root: string, network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { +async function airdropToWallet(root: string, host: UnlockHost, network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { const recipientAddress = (await loadWalletConfig(resolveWalletPath(root, name))).addresses.undeployed; // dev's wallets live on the local chain. - await (await engineFor('undeployed', root)).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings, root }); + await (await engineFor('undeployed', root)).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings, root, notice: host.notice }); } async function walletNeedsDust(root: string, network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { @@ -166,7 +166,7 @@ async function walletNeedsDust(root: string, network: NetworkConfig, name: strin return registeredUtxos === 0 && unregisteredUtxos > 0; } -async function registerWalletDust(root: string, network: NetworkConfig, name: string, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { - const { seed } = await unlockWallet(resolveWalletPath(root, name), { root }); - await (await engineFor('undeployed', root)).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings, root }); +async function registerWalletDust(root: string, host: UnlockHost, network: NetworkConfig, name: string, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { + const { seed } = await unlockWallet(resolveWalletPath(root, name), { root, host }); + await (await engineFor('undeployed', root)).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings, root, notice: host.notice }); } diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 389fa5b9..76db2a0e 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -8,7 +8,6 @@ // owner key) and roster.json, with the private state in the directory's // midnight-level-db under the store name and password it was first made with. -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; import { join } from 'node:path'; import { artefactCache } from '@kuiralabs/midnight-account-chain/artefacts'; @@ -23,6 +22,7 @@ import { } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_DATABASE } from '../contract/private-state.ts'; import { type PassphraseSource, passphraseForNewSecret, unlockPassphrase } from '../passphrase.ts'; +import type { UnlockHost } from '../wallet-config.ts'; import { AccountMigrationInterruptedError, type SealedDeviceKeys, @@ -126,10 +126,12 @@ export interface GrantAccount { ownCode?: () => string; } -/** Where an account's passphrase comes from, and where a warning about a plain-text account goes. */ +/** Where an account's passphrase comes from, and where a warning about a plain-text account goes (the host's notices, unless given). */ export interface OpenAccountOptions { /** The state root holding mn's passphrase check and the proving artefacts. */ root: string; + /** The host: who is asked for the passphrase, the passphrase it has unlocked, and its notices. */ + host: UnlockHost; source?: PassphraseSource; warn?: (line: string) => void; } @@ -163,19 +165,19 @@ export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: return ownDeviceCode(recordsDir, key, device); }, }); - if (isSealedAccount(recordsDir)) return sealed(openAccountKey(recordsDir, await unlockPassphrase(root, options.source))); + if (isSealedAccount(recordsDir)) return sealed(openAccountKey(recordsDir, await unlockPassphrase(options.host, root, options.source))); // Caught half way through being sealed: its private state may be under its new password already. if (isAccountMigrating(recordsDir)) throw new AccountMigrationInterruptedError(recordsDir); const plainStore = directoryOwnerStore(recordsDir); const plainKeys = directoryDeviceKeys(recordsDir); if (plainStore.readOwner() !== undefined || plainKeys.read() !== undefined) { - (options.warn ?? notice)( - `Warning: the account in ${recordsDir} is not protected: its owner key and records are in plain text. Encrypt them with: midnight wallet protect`, - ); + const warning = `Warning: the account in ${recordsDir} is not protected: its owner key and records are in plain text. Encrypt them with: midnight wallet protect`; + if (options.warn !== undefined) options.warn(warning); + else options.host.notice(warning); return { context, store: plainStore, keys: plainKeys, location: { database, store: PRIVATE_STATE_STORE, password: () => LEGACY_STORE_PASSWORD }, protection: 'plain-text' }; } - return sealed(createAccountKey(recordsDir, await passphraseForNewSecret(root, options.source))); + return sealed(createAccountKey(recordsDir, await passphraseForNewSecret(options.host, root, options.source))); } /** The account's owner device, which its records hold. */ diff --git a/src/lib/grant/prepare.ts b/src/lib/grant/prepare.ts index b2411b7e..7ec1fcd9 100644 --- a/src/lib/grant/prepare.ts +++ b/src/lib/grant/prepare.ts @@ -6,6 +6,7 @@ import { type ParsedArgs, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type PayingTarget, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '../wallet-config.ts'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; @@ -49,10 +50,10 @@ export async function accountOnRecord(recordsDir: string): Promise { +export async function prepareGrant(args: ParsedArgs, root: string, host: Host): Promise { const request = resolveGrantRequest(args); assertNodeRunsAccount(); - const target = resolvePayingTarget(args, 'grant', request.subcommand, root); + const target = resolvePayingTarget(args, 'grant', request.subcommand, root, host); // Refuses a network the account can't reach before anything is created. assertAccountNetwork(target.networkConfig, root); const walletName = accountWalletName(getFlag(args, 'wallet'), () => getActiveWalletName(root)); diff --git a/src/lib/passphrase.ts b/src/lib/passphrase.ts index 052a145b..603e1d3a 100644 --- a/src/lib/passphrase.ts +++ b/src/lib/passphrase.ts @@ -1,7 +1,7 @@ // mn's one passphrase: where it comes from, and the keystore's check that // holds it to being one. It comes from MN_PASSPHRASE (scripts, the MCP // server, CI; kept off the process list), else it is typed through the -// prompter (at a terminal, nothing echoed), else the command is refused before it changes anything. +// prompter its host gives (at a terminal, nothing echoed), else the command is refused before it changes anything. // The check is a known value sealed under the passphrase in ~/.midnight: once // it is there, every other passphrase is refused, so no secret is ever sealed // under a second one. @@ -11,7 +11,8 @@ import * as path from 'node:path'; import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; -import { currentPrompter, type Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { defineHostSlot, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { PASSPHRASE_ENV, settings } from '@kuiralabs/midnight-cli-core/lib/settings'; /** The variable a non-interactive run sets the passphrase in (named in settings.ts). */ @@ -33,10 +34,9 @@ export class NoPassphraseError extends UsageError { } } -/** Where the passphrase is read from: the environment, and a prompter (the one set, unless given) if it can ask. */ +/** Where the passphrase is read from besides the prompter: the environment (the settings', unless given). */ export interface PassphraseSource { env?: Record; - prompter?: Prompter | null; /** Ask twice and refuse two that differ: for setting the passphrase. */ confirm?: boolean; /** The call's cancellation: a call cancelled while the passphrase was asked for saves none. */ @@ -51,11 +51,10 @@ const ask = async (prompter: Prompter, question: string): Promise => { return line; }; -/** The passphrase: from MN_PASSPHRASE, else asked for at the terminal. */ -export async function readPassphrase(source: PassphraseSource = {}): Promise { +/** The passphrase: from MN_PASSPHRASE, else asked for through `prompter` (at the terminal) when it can ask. */ +export async function readPassphrase(prompter: Prompter | null, source: PassphraseSource = {}): Promise { const fromEnv = source.env !== undefined ? source.env[PASSPHRASE_ENV] : settings().passphrase; if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv; - const prompter = source.prompter === undefined ? currentPrompter() : source.prompter; if (prompter === null || !prompter.isInteractive()) throw new NoPassphraseError(); const passphrase = await ask(prompter, source.confirm ? 'New passphrase for mn: ' : 'Passphrase for mn: '); if (source.confirm) { @@ -88,20 +87,24 @@ export function checkPassphrase(root: string, passphrase: string): void { /** The shortest passphrase mn accepts when one is set. */ export const MIN_PASSPHRASE_LENGTH = 12; -// The passphrase this process has unlocked, by state root: one prompt per run. -const unlocked = new Map(); +/** What a passphrase is had through: the host's prompter, and the host's record of the passphrases it has unlocked. */ +export type PassphraseHost = Pick; + +// The passphrase each host has unlocked, by state root: one prompt per run. +const UNLOCKED = defineHostSlot('passphrase.unlocked', () => new Map()); /** * mn's passphrase, read and checked against the one set; asked for once per - * run. One already checked is taken again only when the environment names no - * other: a changed MN_PASSPHRASE is checked afresh. + * run of `host`. One already checked is taken again only when the environment + * names no other: a changed MN_PASSPHRASE is checked afresh. */ -export async function unlockPassphrase(root: string, source: PassphraseSource = {}): Promise { +export async function unlockPassphrase(host: PassphraseHost, root: string, source: PassphraseSource = {}): Promise { + const unlocked = host.slot(UNLOCKED); const known = unlocked.get(root); const fromEnv = source.env !== undefined ? source.env[PASSPHRASE_ENV] : settings().passphrase; if (known !== undefined && (fromEnv === undefined || fromEnv === '' || fromEnv === known)) return known; if (!isPassphraseSet(root)) throw new UsageError('mn has no passphrase yet. Set one with: midnight wallet protect'); - const passphrase = await readPassphrase(source); + const passphrase = await readPassphrase(host.prompter, source); checkPassphrase(root, passphrase); unlocked.set(root, passphrase); return passphrase; @@ -111,14 +114,14 @@ export async function unlockPassphrase(root: string, source: PassphraseSource = * The passphrase to seal a new secret under: the one set, or, on a machine * with none yet, a new one (asked twice at a terminal), which is then set. */ -export async function passphraseForNewSecret(root: string, source: PassphraseSource = {}): Promise { - if (isPassphraseSet(root)) return unlockPassphrase(root, source); - const passphrase = await readPassphrase({ ...source, confirm: true }); +export async function passphraseForNewSecret(host: PassphraseHost, root: string, source: PassphraseSource = {}): Promise { + if (isPassphraseSet(root)) return unlockPassphrase(host, root, source); + const passphrase = await readPassphrase(host.prompter, { ...source, confirm: true }); if ([...passphrase].length < MIN_PASSPHRASE_LENGTH) { throw new UsageError(`mn's passphrase must be at least ${MIN_PASSPHRASE_LENGTH} characters.`); } throwIfCancelled(source.signal); establishPassphrase(root, passphrase); - unlocked.set(root, passphrase); + host.slot(UNLOCKED).set(root, passphrase); return passphrase; } diff --git a/src/lib/seed-resolver.ts b/src/lib/seed-resolver.ts index e68d3ae2..f065352f 100644 --- a/src/lib/seed-resolver.ts +++ b/src/lib/seed-resolver.ts @@ -5,7 +5,7 @@ import { getFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { resolveWalletPath, unlockWallet, type WalletConfig } from './wallet-config.ts'; +import { resolveWalletPath, unlockWallet, type UnlockHost, type WalletConfig } from './wallet-config.ts'; import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; export interface ResolvedSeed { @@ -54,7 +54,7 @@ export function parseSeedHex(input: string, label: string): Buffer { * source), so a caller that caches to the wallet file can skip that when there is none. * Wallets are the ones under the state root `root`. */ -export async function resolveSeedSource(args: ParsedArgs, root: string, opts: ResolveSeedOptions = {}): Promise { +export async function resolveSeedSource(args: ParsedArgs, root: string, host: UnlockHost, opts: ResolveSeedOptions = {}): Promise { const seedFlag = getFlag(args, 'seed'); const seedSource = seedFlag ?? settings().seed; if (seedSource) { @@ -76,11 +76,11 @@ export async function resolveSeedSource(args: ParsedArgs, root: string, opts: Re } const walletPath = resolveWalletPath(root, walletName); - const { seed, mnemonic: _mnemonic, ...config } = await unlockWallet(walletPath, { root }); + const { seed, mnemonic: _mnemonic, ...config } = await unlockWallet(walletPath, { root, host }); return { seed: Buffer.from(seed, 'hex'), walletPath, config }; } /** Just the seed — for commands that don't touch the wallet file. */ -export async function resolveSeed(args: ParsedArgs, root: string, opts?: ResolveSeedOptions): Promise { - return (await resolveSeedSource(args, root, opts)).seed; +export async function resolveSeed(args: ParsedArgs, root: string, host: UnlockHost, opts?: ResolveSeedOptions): Promise { + return (await resolveSeedSource(args, root, host, opts)).seed; } diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 1d9c9abd..571b164f 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -4,7 +4,7 @@ // Always runs in approve-all mode. import { Socket } from 'node:net'; -import { resolveWalletPath, unlockWallet, walletAddress } from './wallet-config.ts'; +import { resolveWalletPath, unlockWallet, walletAddress, type UnlockHost } from './wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -23,6 +23,8 @@ export interface ServeHandle { export interface ServeManagerOptions { /** The state root the wallets, config and caches live under. */ root: string; + /** The host: who unlocks the wallet, where the wallet's and the server's notices go, and its connection ids. */ + host: UnlockHost; port?: number; network?: string; /** Explicit endpoints; they win over the network defaults and docker auto-detection. */ @@ -197,7 +199,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise { +async function serveWallet(port: number, { network, root, host, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { const { startServeOrReuse } = await import('./serve-manager.ts'); const handle = await startServeOrReuse({ root, + host, port, network, endpoints, @@ -42,10 +43,10 @@ async function serveWallet(port: number, { network, root, endpoints }: PayingTar * server that is running already is reused. Closing it reverts what it * balanced but never submitted. */ -async function connectWallet({ network, root, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options: ConnectOptions = {}): Promise { +async function connectWallet({ network, root, host, endpoints }: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options: ConnectOptions = {}): Promise { const { openConnector } = await import('./serve-manager.ts'); const engine = await engineFor(network, root); - const open = () => openConnector({ root, network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, forceShielded: options.shielded, signal }); + const open = () => openConnector({ root, host, network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, forceShielded: options.shielded, signal }); return sessionOver(network, await open(), (tx, stage) => engine.ledger.readTransaction(tx, stage), { reopen: open, onMessage: (msg) => progress.update(msg) }); } diff --git a/src/lib/swap/request.ts b/src/lib/swap/request.ts index 7e4b7b08..97928366 100644 --- a/src/lib/swap/request.ts +++ b/src/lib/swap/request.ts @@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs'; import { type ParsedArgs, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type PayingTarget, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { checkTerms, type SwapLeg, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { assertOfferUnexpired } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; import { readOfferFile, type ReadOffer } from './offers.ts'; @@ -36,11 +37,11 @@ export interface MakeRequest { out: string | undefined; } -export function prepareMake(args: ParsedArgs, root: string, now: Date): MakeRequest { +export function prepareMake(args: ParsedArgs, root: string, host: Host, now: Date): MakeRequest { const lifetime = getFlag(args, 'expires-in') ?? String(DEFAULT_OFFER_LIFETIME_S); if (!/^[1-9][0-9]*$/.test(lifetime)) throw new UsageError(`--expires-in must be a whole number of seconds above 0, not "${lifetime}"`); return { - target: resolvePayingTarget(args, 'swap', 'make', root), + target: resolvePayingTarget(args, 'swap', 'make', root, host), terms: termsOf(args), expiresAt: new Date(now.getTime() + Number(lifetime) * 1000), out: getFlag(args, 'out'), @@ -67,8 +68,8 @@ export async function readOfferArg(args: ParsedArgs, target: PayingTarget): Prom } /** A take, checked as far as it can be without the chain: the file, its network, the agreed terms and the expiry. */ -export async function prepareTake(args: ParsedArgs, root: string, now: Date): Promise { - const target = resolvePayingTarget(args, 'swap', 'take', root); +export async function prepareTake(args: ParsedArgs, root: string, host: Host, now: Date): Promise { + const target = resolvePayingTarget(args, 'swap', 'take', root, host); const agreed = termsOf(args); const offer = await readOfferArg(args, target); checkTerms(offer.contents.terms, agreed); diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index 53bf66b4..31a09021 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -111,7 +111,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig); - const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root }); + const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root, host: ctx.host }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; @@ -122,7 +122,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont callbacks.onMessage(`SDK: ${msg}`); }); try { - const balance = await engine.wallet.prepNightBalance({ seed: seedBuffer, root: ctx.root, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }); + const balance = await engine.wallet.prepNightBalance({ seed: seedBuffer, root: ctx.root, notice: ctx.host.notice, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }); if (balance > 0n) { callbacks.onMessage(`Balance OK: ${balance}`); return; @@ -154,6 +154,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont onSyncWarning(_tag, msg) { callbacks.onMessage(`Syncing genesis... (${msg})`); }, sdkWarnings: ctx.sdkWarnings, root: ctx.root, + notice: ctx.host.notice, }); callbacks.onMessage(`Airdropped ${amount} NIGHT`); @@ -169,7 +170,7 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre }); await assertLedgerSupported(network, networkConfig); - const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root }); + const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root, host: ctx.host }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; @@ -177,7 +178,7 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre const stopListening = ctx.sdkWarnings.listen(undefined); try { const { dustAvailable } = await (await engineFor(network, ctx.root)).wallet.prepDust( - { seed: seedBuffer, root: ctx.root, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }, + { seed: seedBuffer, root: ctx.root, notice: ctx.host.notice, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }, DUST_WAIT_TIMEOUT_MS, ); // Verify dust is actually available — don't trust silent timeouts @@ -206,6 +207,7 @@ async function stepMnServe(config: DappTestConfig, ctx: PrepContext, callbacks: // before. const handle = await startServeOrReuse({ root: ctx.root, + host: ctx.host, port: undefined, // use default network: config.network, onMessage: (msg) => callbacks.onMessage(`[serve] ${msg}`), diff --git a/src/lib/test/types.ts b/src/lib/test/types.ts index 5581bc8d..d84a2bb7 100644 --- a/src/lib/test/types.ts +++ b/src/lib/test/types.ts @@ -1,6 +1,7 @@ // Test framework types — schemas for dapp.test.json, suite configs, assertions, and results. import type { ServeHandle } from '../serve-manager.ts'; +import type { UnlockHost } from '../wallet-config.ts'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; @@ -146,6 +147,8 @@ export interface BuildHandle { export interface PrepContext { /** The state root the wallets, config and caches live under. */ root: string; + /** The host the run is in: who unlocks the wallet, and where the steps' notices go. */ + host: UnlockHost; /** The SDK warnings of the call that runs the prep: the steps that run the SDK listen to them. */ sdkWarnings: CallSdkWarnings; /** The run's cancellation: no step starts after it aborts, and the waits inside a step stop. */ @@ -156,10 +159,11 @@ export interface PrepContext { addCleanup(fn: () => Promise): void; } -export function createPrepContext(root: string, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): PrepContext { +export function createPrepContext(root: string, host: UnlockHost, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): PrepContext { const cleanups: (() => Promise)[] = []; return { root, + host, sdkWarnings, signal, cleanups, diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index eb40de93..68f82818 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -4,7 +4,7 @@ import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { loadWalletConfig, resolveWalletPath, walletAddress, walletShieldedAddress, type WalletConfig } from './wallet-config.ts'; +import { loadWalletConfig, resolveWalletPath, walletAddress, walletShieldedAddress, type UnlockHost, type WalletConfig } from './wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { engineFor, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; @@ -21,8 +21,8 @@ export interface TransferRequest { shielded: boolean; } -/** `transfer [--shielded] [--wallet] [--network]`, checked without touching the chain, against the wallets and config under the state root `root`. */ -export async function resolveTransferRequest(args: ParsedArgs, root: string): Promise { +/** `transfer [--shielded] [--wallet] [--network]`, checked without touching the chain, against the wallets and config under the state root `root`; a sealed recipient wallet is unlocked through `host`. */ +export async function resolveTransferRequest(args: ParsedArgs, root: string, host: UnlockHost): Promise { const recipientInput = args.subcommand; const amountStr = args.positionals[0]; @@ -44,7 +44,7 @@ export async function resolveTransferRequest(args: ParsedArgs, root: string): Pr } const shielded = hasFlag(args, 'shielded'); - const recipientAddress = await resolveRecipient(recipientInput, args, shielded, root); + const recipientAddress = await resolveRecipient(recipientInput, args, shielded, root, host); const amountNight = parseAmount(amountStr); const walletPath = resolveWalletPath(root, getFlag(args, 'wallet')); const walletConfig = await loadWalletConfig(walletPath); @@ -75,7 +75,7 @@ function assertRecipient(keys: EngineKeys, address: string, shielded: boolean, n * An address (mn_addr_ or mn_shield-addr_ prefix) is used as given. Anything * else is a wallet name, and the address comes from that wallet's file. */ -async function resolveRecipient(input: string, args: ParsedArgs, shielded: boolean, root: string): Promise { +async function resolveRecipient(input: string, args: ParsedArgs, shielded: boolean, root: string, host: UnlockHost): Promise { if (input.startsWith('mn_addr_') || input.startsWith('mn_shield-addr_')) { return input; } @@ -84,7 +84,7 @@ async function resolveRecipient(input: string, args: ParsedArgs, shielded: boole const networkName = resolveNetworkName({ args, configDir: root }); if (shielded) { - const shieldedAddr = await walletShieldedAddress(recipientPath, networkName, root); + const shieldedAddr = await walletShieldedAddress(recipientPath, networkName, root, host); if (!shieldedAddr) { throw new Error( `Wallet "${input}" has no shielded address for network "${networkName}".\n` + @@ -94,7 +94,7 @@ async function resolveRecipient(input: string, args: ParsedArgs, shielded: boole return shieldedAddr; } - const address = await walletAddress(recipientPath, networkName, root); + const address = await walletAddress(recipientPath, networkName, root, host); if (!address) { throw new Error(`Wallet "${input}" has no address for network "${networkName}". Regenerate the wallet to derive one.`); } diff --git a/src/lib/wallet-can-pay.ts b/src/lib/wallet-can-pay.ts index 1abe9252..821f6605 100644 --- a/src/lib/wallet-can-pay.ts +++ b/src/lib/wallet-can-pay.ts @@ -16,9 +16,9 @@ import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; * active wallet is checked, the one the command's server will use. Returns * what it found, the Dust in Specks. */ -export async function assertWalletCanPay({ network, root, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner, signal?: AbortSignal): Promise<{ nightBalance: bigint; dustBalance: bigint }> { +export async function assertWalletCanPay({ network, root, host, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner, signal?: AbortSignal): Promise<{ nightBalance: bigint; dustBalance: bigint }> { throwIfCancelled(signal); - const walletConfig = await unlockWallet(resolveWalletPath(root, wallet), { root }); + const walletConfig = await unlockWallet(resolveWalletPath(root, wallet), { root, host }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; const { engineFor } = await import('@kuiralabs/midnight-cli-core/lib/engine'); @@ -43,7 +43,7 @@ export async function assertWalletCanPay({ network, root, networkConfig }: Payin ); } - const dustView = await repo.dustBalance(seedBuffer, networkConfig, { root, signal, onStatus: (s) => progress.update(s) }); + const dustView = await repo.dustBalance(seedBuffer, networkConfig, { root, notice: host.notice, signal, onStatus: (s) => progress.update(s) }); if (dustView.balance === 0n && dustView.availableCoins === 0) { progress.fail('No dust available'); throw new Error( diff --git a/src/lib/wallet-config.ts b/src/lib/wallet-config.ts index a13b7a7a..2f61afa2 100644 --- a/src/lib/wallet-config.ts +++ b/src/lib/wallet-config.ts @@ -1,5 +1,4 @@ import * as fs from 'fs'; -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; import * as path from 'path'; import { DEFAULT_WALLET_FILENAME, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, FILE_MODE, isValidWalletName } from '@kuiralabs/midnight-cli-core/lib/constants'; import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; @@ -8,7 +7,8 @@ import { getWalletsDir } from './wallet-paths.ts'; import { anyEngine, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; import { isSealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { FileExistsError, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; -import { type PassphraseSource, unlockPassphrase } from './passphrase.ts'; +import { type PassphraseHost, type PassphraseSource, unlockPassphrase } from './passphrase.ts'; +import { defineHostSlot, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** What anyone may read of a wallet: its addresses, and whether its secrets are sealed. No secret. */ @@ -80,16 +80,16 @@ export function getAddress(config: WalletConfig, network: NetworkName): string { * that network existed has none saved yet: it is unlocked, which derives and * saves it. */ -export async function walletAddress(walletPath: string, network: NetworkName, root: string): Promise { +export async function walletAddress(walletPath: string, network: NetworkName, root: string, host: UnlockHost): Promise { const config = await loadWalletConfig(walletPath); - return config.addresses[network] ?? (await unlockWallet(walletPath, { root })).addresses[network]; + return config.addresses[network] ?? (await unlockWallet(walletPath, { root, host })).addresses[network]; } /** A wallet's shielded address on `network`, unlocking a sealed wallet that has none saved yet (see walletAddress); undefined when the wallet keeps no shielded addresses. */ -export async function walletShieldedAddress(walletPath: string, network: NetworkName, root: string): Promise { +export async function walletShieldedAddress(walletPath: string, network: NetworkName, root: string, host: UnlockHost): Promise { const config = await loadWalletConfig(walletPath); if (config.shieldedAddresses === undefined || config.shieldedAddresses[network] !== undefined) return config.shieldedAddresses?.[network]; - return (await unlockWallet(walletPath, { root })).shieldedAddresses?.[network]; + return (await unlockWallet(walletPath, { root, host })).shieldedAddresses?.[network]; } /** The networks an address map has no address for: a wallet written before they existed. */ @@ -553,15 +553,19 @@ export async function protectAllWallets(root: string, passphrase: string, signal return report; } -/** How a wallet is unlocked: the state root holding mn's passphrase check, where the passphrase comes from, and where a warning goes. */ +/** What a wallet is unlocked through: the host's prompter and its record of the passphrase unlocked, its notices, and its record of the plain-text wallets warned about. */ +export type UnlockHost = PassphraseHost & Pick; + +/** How a wallet is unlocked: the state root holding mn's passphrase check, the host, where the passphrase comes from, and where a warning goes (the host's notices, unless given). */ export interface UnlockOptions { root: string; + host: UnlockHost; source?: PassphraseSource; warn?: (line: string) => void; } -// Each plain-text wallet is warned about once per run. -const warnedPlain = new Set(); +// Each plain-text wallet is warned about once per run of a host. +const WARNED_PLAIN = defineHostSlot('wallet-config.warnedPlain', () => new Set()); /** A wallet with its secrets: opened with mn's passphrase, or read as it is from a plain-text file an earlier mn wrote. */ export async function unlockWallet(walletPath: string, options: UnlockOptions): Promise { @@ -569,15 +573,16 @@ export async function unlockWallet(walletPath: string, options: UnlockOptions): const config = await loadWalletConfig(resolvedPath); const raw = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8')); if (!config.isSealed) { + const warnedPlain = options.host.slot(WARNED_PLAIN); if (!warnedPlain.has(resolvedPath) || options.warn !== undefined) { warnedPlain.add(resolvedPath); - (options.warn ?? notice)( - `Warning: wallet ${resolvedPath} is not protected: its seed is in plain text. Encrypt it with: midnight wallet protect`, - ); + const warning = `Warning: wallet ${resolvedPath} is not protected: its seed is in plain text. Encrypt it with: midnight wallet protect`; + if (options.warn !== undefined) options.warn(warning); + else options.host.notice(warning); } return typeof raw.mnemonic === 'string' ? { ...config, seed: raw.seed, mnemonic: raw.mnemonic } : { ...config, seed: raw.seed }; } - const passphrase = await unlockPassphrase(options.root, options.source); + const passphrase = await unlockPassphrase(options.host, options.root, options.source); const secrets = JSON.parse(openSecret(raw.sealed, passphrase, 'wallet').toString('utf8')) as WalletSecrets; // A network added since the wallet was written: now that its seed is open, // derive that network's addresses and save them beside the sealed secrets. diff --git a/src/lib/wallet-protector.ts b/src/lib/wallet-protector.ts index 50fbd16b..1d1545b5 100644 --- a/src/lib/wallet-protector.ts +++ b/src/lib/wallet-protector.ts @@ -3,7 +3,7 @@ // caller passes it in the call context: wallet never imports that domain. import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { resolveWalletPath, unlockWallet } from './wallet-config.ts'; +import { resolveWalletPath, unlockWallet, type UnlockHost } from './wallet-config.ts'; /** What protecting one item did: sealed now, already sealed, or why it could not be. */ export type ProtectedItem = @@ -30,9 +30,9 @@ export interface WalletProtector { /** The wallet command's call context: a command's, with the protectors `wallet protect` runs. */ export type WalletCommandContext = CallContext; -/** The shielded coin public key of the wallet `name` under the state root `root`, unlocked with mn's passphrase. */ -export async function coinKeyOfWallet(root: string, name: string): Promise { +/** The shielded coin public key of the wallet `name` under the state root `root`, unlocked with mn's passphrase through `host`. */ +export async function coinKeyOfWallet(root: string, host: UnlockHost, name: string): Promise { // The engine loads the SDK, which the other wallet subcommands don't need: loaded here, not up front. const { anyEngine } = await import('@kuiralabs/midnight-cli-core/lib/engine'); - return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(root, name), { root })).seed, 'hex')); + return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(root, name), { root, host })).seed, 'hex')); } diff --git a/src/lib/ws-rpc.ts b/src/lib/ws-rpc.ts index 1fa90e1d..be7611f0 100644 --- a/src/lib/ws-rpc.ts +++ b/src/lib/ws-rpc.ts @@ -2,7 +2,7 @@ // Transport layer for the DApp Connector — dispatches RPC calls to handler functions import { WebSocketServer, WebSocket } from 'ws'; -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { defineHostSlot, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import type { APIError, RpcHandler, RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; // The wire types the connector's handlers use, from where every package can reach them. @@ -131,6 +131,8 @@ export interface RpcConnection { // ── Server options ── export interface RpcServerOptions { + /** The host the server runs in: its notices, and the count its connection ids come from. */ + host: Pick; port: number; handlers: Record; /** @@ -196,10 +198,11 @@ function parseRequest(data: string): JsonRpcRequest { // ── Create server ── -let connectionCounter = 0; +// The connections a host's servers have accepted: ids are unique across its servers. +const CONNECTIONS = defineHostSlot('ws-rpc.connections', () => ({ count: 0 })); export function createRpcServer(options: RpcServerOptions): RpcServer { - const { port, handlers, onConnect, onDisconnect, onRequest, onResponse, refuseBrowsers = false } = options; + const { host, port, handlers, onConnect, onDisconnect, onRequest, onResponse, refuseBrowsers = false } = options; const connections = new Map(); // Bind to loopback only — prevents remote machines on the network from connecting. @@ -220,11 +223,11 @@ export function createRpcServer(options: RpcServerOptions): RpcServer { wss.on('error', (err: Error) => { // Callers handle this via the close() method or process-level error handling // We just need to prevent the uncaught exception - notice(`WebSocket server error: ${err.message}`); + host.notice(`WebSocket server error: ${err.message}`); }); wss.on('connection', (ws: WebSocket) => { - const id = `conn_${++connectionCounter}`; + const id = `conn_${++host.slot(CONNECTIONS).count}`; const connection: RpcConnection = { ws, id, diff --git a/src/ui/dev-keys.ts b/src/ui/dev-keys.ts index aae0aa43..e1ccb4b4 100644 --- a/src/ui/dev-keys.ts +++ b/src/ui/dev-keys.ts @@ -1,4 +1,4 @@ -import { notice } from '@kuiralabs/midnight-cli-core/lib/notices'; +import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; // Raw-mode single-keystroke dispatcher for `mn dev`. // Registers {key → handler} pairs; reads one char at a time from stdin. // Always restores the terminal's cooked mode on stop() so a crash or Ctrl+C @@ -13,8 +13,10 @@ export interface KeyDispatcherOptions { onInterrupt: () => void; /** Called on an unbound key. Defaults to a silent no-op. */ onUnknown?: (key: string) => void; - /** Called when any action handler throws. Defaults to printing to stderr. */ + /** Called when any action handler throws. Defaults to saying it through `notice`. */ onError?: (key: string, err: Error) => void; + /** Where a failed action is said when there is no `onError` (the host's notices). */ + notice: NoticeSink; } export interface KeyDispatcher { @@ -59,7 +61,7 @@ export function startKeyDispatcher(opts: KeyDispatcherOptions): KeyDispatcher { .catch((err) => { const error = err instanceof Error ? err : new Error(String(err)); if (opts.onError) opts.onError(key, error); - else notice(`key handler error (${key}): ${error.message}`); + else opts.notice(`key handler error (${key}): ${error.message}`); }); }; From 60dd240da230aca4984cb084090c8f437b858e93 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 04:14:18 -0800 Subject: [PATCH 59/88] Each host loads its own engine (3B, 5 of 7) The engine packages export createRcEngine(host) and createBetaEngine(host) instead of ready constants: each engine instance owns its wallet repository and, in beta, its once-said WASM Dust notice, and reads its own host's settings. A host loads its engine through its engine loader and keeps it, with the set it prefers; one guard stays process-wide (approved, Y51): a process that loaded one SDK set refuses the other. Until slice 6 moves the callers, a bridge points the module-level engineFor and anyEngine at the CLI host's engines, so the CLI still holds one engine. The fresh-install check's probe, broken since slice 3 (it imported the removed paths setter), builds a host with createHost now. Module state allowed: 4 (the chain-id memo, the SDK-set guard, the bridge, settings). Behaviour snapshot unchanged; suite 2573, beta 171; fresh install loads both engines; scratch chain swap 30/30, MCP swap 12/12, tx 25/25; stagenet (beta) balance and Dust status read. --- packages/cli-core/api-report.md | 17 ++- packages/cli-core/src/lib/call-context.ts | 4 +- packages/cli-core/src/lib/engine.ts | 85 ++++++----- packages/cli-core/src/lib/host.ts | 40 ++++- packages/engine-beta/api-report.md | 47 +++--- packages/engine-beta/src/airdrop.ts | 7 +- packages/engine-beta/src/dust-direct.ts | 5 +- packages/engine-beta/src/dust-export.ts | 8 +- packages/engine-beta/src/dust-register.ts | 8 +- packages/engine-beta/src/dust-sync-native.ts | 30 ++-- packages/engine-beta/src/index.ts | 24 ++- packages/engine-beta/src/transfer.ts | 10 +- .../engine-beta/src/wallet-data-repository.ts | 75 ++++----- packages/engine-beta/src/wallet.ts | 52 ++++--- packages/engine-rc/api-report.md | 46 +++--- packages/engine-rc/src/airdrop.ts | 7 +- packages/engine-rc/src/dust-direct.ts | 5 +- packages/engine-rc/src/dust-export.ts | 8 +- packages/engine-rc/src/dust-register.ts | 8 +- packages/engine-rc/src/dust-sync-native.ts | 30 ++-- packages/engine-rc/src/index.ts | 24 ++- packages/engine-rc/src/transfer.ts | 10 +- .../engine-rc/src/wallet-data-repository.ts | 55 +++---- packages/engine-rc/src/wallet.ts | 52 ++++--- scripts/check-process-safety.mjs | 10 +- scripts/fresh-install-check.mjs | 11 +- src/__tests__/account-backup.test.ts | 5 +- src/__tests__/contract-runtime-check.test.ts | 6 +- .../contract-script-packages.test.ts | 6 +- src/__tests__/dust-export.test.ts | 3 +- src/__tests__/dust-sync-native.test.ts | 28 ++-- src/__tests__/engine-beta-host.test.ts | 73 +++++++++ src/__tests__/engine-beta.test.ts | 6 +- src/__tests__/engine.test.ts | 143 +++++++++++++----- src/__tests__/fixtures/record-swap-offer.ts | 6 +- src/__tests__/helpers/shell-settings.ts | 14 +- src/__tests__/helpers/test-host.ts | 7 +- src/__tests__/read-cancellation.test.ts | 5 +- src/__tests__/sealed-account.test.ts | 6 +- src/__tests__/verbose-per-call.test.ts | 2 +- src/__tests__/wallet-data-repository.test.ts | 45 +++--- .../wallet-state-to-restore.live.test.ts | 4 +- src/lib/cli-host.ts | 8 +- src/lib/installed-engines.ts | 11 +- 44 files changed, 647 insertions(+), 409 deletions(-) create mode 100644 src/__tests__/engine-beta-host.test.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 7704afa2..eaba383f 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -648,6 +648,7 @@ import type { NoticeSink } from "./notices.ts"; import type { FeeLimits } from "./fee-limits.ts"; import type { RpcHandler } from "./connector-api.ts"; import type { Spinner } from "../ui/spinner.ts"; +import type { Host } from "./host.ts"; export type SdkSet = "rc" | "beta"; export interface EngineKeys { unshieldedAddress(seed: Buffer, network: NetworkName, keyIndex?: number): string; @@ -949,16 +950,23 @@ export interface Engine { readonly wallet: EngineWallet; } export declare function sdkSetOf(network: NetworkName, root: string): SdkSet; -export type EngineLoader = (set: SdkSet) => Promise; +export type EngineHost = Pick; +export type EngineLoader = (set: SdkSet, host: Host) => Promise; +export interface HostEngines { + load(set: SdkSet): Promise; + for(network: NetworkName): Promise; + any(): Promise; + prefer(network: NetworkName): void; +} export declare class OtherSdkSetError extends Error { readonly code = "OTHER_SDK_SET"; readonly loadedSet: SdkSet; readonly wantedSet: SdkSet; constructor(loadedSet: SdkSet, wantedSet: SdkSet, message?: string); } -export declare function setEngineLoader(next: EngineLoader): void; +export declare function claimSdkSet(set: SdkSet): void; +export declare function bridgeEngines(engines: HostEngines): void; export declare function engineFor(network: NetworkName, root: string): Promise; -export declare function preferEngineOf(network: NetworkName, root: string): void; export declare function anyEngine(): Promise; ``` @@ -1095,6 +1103,7 @@ import type { HostPaths } from "./state-root.ts"; import { type Settings } from "./settings.ts"; import type { Prompter } from "./prompter.ts"; import { type SdkWarningCalls } from "./sdk-warnings.ts"; +import { type EngineLoader, type HostEngines } from "./engine.ts"; export interface HostSlot { readonly name: string; readonly init: () => T; @@ -1106,6 +1115,7 @@ export interface Host { notice(line: string): void; readonly prompter: Prompter | null; readonly sdkWarnings: SdkWarningCalls; + readonly engines: HostEngines; slot(key: HostSlot): T; } export type Supplied = T | (() => T); @@ -1115,6 +1125,7 @@ export interface HostOptions { readonly notice?: (line: string) => void; readonly prompter?: Prompter | null; readonly sdkWarnings?: SdkWarningCalls; + readonly engineLoader?: EngineLoader; } export declare function createHost(options?: HostOptions): Host; ``` diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index 0a92f429..36aa3b74 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -13,7 +13,6 @@ import { isVerbose, type ParsedArgs } from './argv.ts'; import { CancelledError } from './errors.ts'; -import { preferEngineOf } from './engine.ts'; import { resolveNetworkName } from './resolve-network.ts'; import type { Payer } from './payer.ts'; import type { Settings } from './settings.ts'; @@ -150,8 +149,7 @@ export function createCallContext(parts: CallParts(handler: CommandHandler, args: ParsedArgs, ctx: CallContext): Promise { if (ctx.signal.aborted) throw new CancelledError(); try { - const root = ctx.config.paths.stateRoot; - preferEngineOf(resolveNetworkName({ args, configDir: root }), root); + ctx.host.engines.prefer(resolveNetworkName({ args, configDir: ctx.config.paths.stateRoot })); } catch { /* an invalid --network: the command says so */ } return handler(args, ctx); } diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 297cbec2..c0d0a3de 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -1,9 +1,9 @@ // The Midnight SDK, behind one interface. Everything that touches an SDK set // is an engine's; the rest of mn reaches it through the engine for its -// network, and names no SDK type. One engine today, for the SDK's release -// candidates (rc). Which engines there are is the host's: it installs a -// loader at start (the shell, the engines it ships), as it does the settings. -// Loading an engine loads its SDK, so the loader imports it only when asked. +// network, and names no SDK type. Which engines there are is the host's: its +// engine loader makes each host an engine of its own (the shell's loader, the +// engines it ships). Loading an engine loads its SDK, so the loader imports it +// only when asked. What stays process-wide is which SDK set the process runs. import type { OfferContents } from './swap-offer.ts'; import type { OpenOffer } from './open-offers.ts'; @@ -15,6 +15,7 @@ import type { NoticeSink } from './notices.ts'; import type { FeeLimits } from './fee-limits.ts'; import type { RpcHandler } from './connector-api.ts'; import type { Spinner } from '../ui/spinner.ts'; +import type { Host } from './host.ts'; /** An SDK set mn runs on: the SDK's release candidates, or the beta set stagenet runs. */ export type SdkSet = 'rc' | 'beta'; @@ -472,18 +473,27 @@ export function sdkSetOf(network: NetworkName, root: string): SdkSet { return sdkSetOfNetwork(network, root); } -/** Loads the engine for an SDK set: the host's, which knows the engines it ships. */ -export type EngineLoader = (set: SdkSet) => Promise; +/** What an engine takes from the host that loads it: its settings, and where its notices go. */ +export type EngineHost = Pick; -let loader: EngineLoader | undefined; +/** Makes the engine for an SDK set, for the host that asks: the program's, which knows the engines it ships. */ +export type EngineLoader = (set: SdkSet, host: Host) => Promise; -// The engine this process has loaded: one per process, since two SDK sets' -// WASM ledgers can't share one. -let loaded: Promise | undefined; - -// The set work every set does alike loads while nothing is loaded: the set of -// the network the call is for, so it doesn't commit the process to another. -let preferred: SdkSet | undefined; +/** A host's engines: one engine of the host's own, loaded on first use. */ +export interface HostEngines { + /** The engine for an SDK set. Rejects with OtherSdkSetError when this host or this process has the other set. */ + load(set: SdkSet): Promise; + /** The engine for a network's SDK set, by the network table and the config under the host's state root. */ + for(network: NetworkName): Promise; + /** + * An engine for work every set does alike, such as deriving addresses: the + * one the host has loaded, else the set of the network the call is for (the + * rc set's when none was said). + */ + any(): Promise; + /** The network a call is for, whose set any() loads while the host has loaded none. */ + prefer(network: NetworkName): void; +} /** A call on a network whose SDK set isn't the one this process has loaded. */ export class OtherSdkSetError extends Error { @@ -502,36 +512,37 @@ export class OtherSdkSetError extends Error { } } -/** The host's loader of engines, set once at start; a new loader forgets the engine an old one loaded. */ -export function setEngineLoader(next: EngineLoader): void { - loader = next; - loaded = undefined; +// The SDK set this process loads, whichever host loaded it first: two sets' +// WASM ledgers can't share a process, so it is the process's, not a host's. +let loadedSet: SdkSet | undefined; + +/** Records that this process loads `set`; throws OtherSdkSetError when it has loaded the other. */ +export function claimSdkSet(set: SdkSet): void { + if (loadedSet !== undefined && loadedSet !== set) throw new OtherSdkSetError(loadedSet, set); + loadedSet = set; } -function loadEngine(set: SdkSet): Promise { - if (loader === undefined) throw new Error('No SDK engine is installed: the host sets an engine loader at start (setEngineLoader)'); - loaded ??= loader(set); - return loaded.then((engine) => { - if (engine.set !== set) throw new OtherSdkSetError(engine.set, set); - return engine; - }); +// A temporary bridge, gone once every library takes its host's engines: the +// engines of the host the shell bridges to, for the libraries that don't yet. +// The shell sets it once at start, so the CLI process has one engine. +let bridged: HostEngines | undefined; + +/** Gives engineFor and anyEngine the engines of the host they serve: the shell's, set once at start. */ +export function bridgeEngines(engines: HostEngines): void { + bridged = engines; } -/** The engine for a network's SDK set (by the config under the state root `root`), loaded on first use. */ -export function engineFor(network: NetworkName, root: string): Promise { - return loadEngine(sdkSetOf(network, root)); +function bridgedEngines(): HostEngines { + if (bridged === undefined) throw new Error('No SDK engine is installed: the shell bridges its host\'s engines at start (bridgeEngines)'); + return bridged; } -/** The network a call is for, whose set work every set does alike loads while no engine is loaded. */ -export function preferEngineOf(network: NetworkName, root: string): void { - preferred = sdkSetOf(network, root); +/** The bridged host's engine for a network's SDK set (by the config under the state root `root`), loaded on first use. */ +export function engineFor(network: NetworkName, root: string): Promise { + return bridgedEngines().load(sdkSetOf(network, root)); } -/** - * An engine for work every set does alike, such as deriving addresses: the - * one this process has loaded, else the set of the network the call is for - * (the rc set's when none was said). - */ +/** The bridged host's engine for work every set does alike (see HostEngines.any). */ export function anyEngine(): Promise { - return loaded ?? loadEngine(preferred ?? 'rc'); + return bridgedEngines().any(); } diff --git a/packages/cli-core/src/lib/host.ts b/packages/cli-core/src/lib/host.ts index b99cfe76..4e2b9c73 100644 --- a/packages/cli-core/src/lib/host.ts +++ b/packages/cli-core/src/lib/host.ts @@ -1,8 +1,9 @@ // The host: what a program gives the libraries it runs. Its settings, its // paths (the state root and the user's home), where its notices go, who -// answers its questions, where the SDK's warnings go, and the state the -// libraries keep for it (the slots). A program creates one and passes it in; -// two hosts in one process share nothing of it. +// answers its questions, its SDK engine, where the SDK's warnings go, and the +// state the libraries keep for it (the slots). A program creates one and +// passes it in; two hosts in one process share nothing of it but the SDK set +// the process runs (two sets' ledgers can't share a process). // // mn's shell builds one at start, its MCP server one for all its calls. @@ -11,6 +12,8 @@ import { NoStateRootError } from './state-root.ts'; import { settingsFromEnvironment, type Settings } from './settings.ts'; import type { Prompter } from './prompter.ts'; import { createSdkWarningRouter, sdkWarningCallsOn, type SdkWarningCalls } from './sdk-warnings.ts'; +import { claimSdkSet, OtherSdkSetError, sdkSetOf, type Engine, type EngineLoader, type HostEngines, type SdkSet } from './engine.ts'; +import type { NetworkName } from './network.ts'; /** A piece of state a library keeps per host, named by the library that owns it. */ export interface HostSlot { @@ -34,6 +37,8 @@ export interface Host { readonly prompter: Prompter | null; /** Where the SDK's warnings go, per call. */ readonly sdkWarnings: SdkWarningCalls; + /** This host's SDK engine, made by its engine loader on first use. */ + readonly engines: HostEngines; /** This host's value of a library's state, made on first use. */ slot(key: HostSlot): T; } @@ -52,6 +57,8 @@ export interface HostOptions { readonly prompter?: Prompter | null; /** Where the SDK's warnings go; a router of the host's own when not given. */ readonly sdkWarnings?: SdkWarningCalls; + /** Makes this host's engine for an SDK set; without one, asking for an engine refuses. */ + readonly engineLoader?: EngineLoader; } const UNSET: Settings = settingsFromEnvironment({}); @@ -62,7 +69,7 @@ export function createHost(options: HostOptions = {}): Host { const slots = new Map, unknown>(); const { paths, settings, notice, prompter = null } = options; const sdkWarnings = options.sdkWarnings ?? sdkWarningCallsOn(createSdkWarningRouter()); - return { + const host: Host = { settings: () => (settings === undefined ? UNSET : read(settings)), paths: () => { if (paths === undefined) throw new NoStateRootError(); @@ -71,9 +78,34 @@ export function createHost(options: HostOptions = {}): Host { notice: (line) => notice?.(line), prompter, sdkWarnings, + engines: hostEngines(() => host, options.engineLoader), slot(key: HostSlot): T { if (!slots.has(key)) slots.set(key, key.init()); return slots.get(key) as T; }, }; + return host; +} + +/** A host's engines: the one engine its loader makes it, and the set work every set does alike prefers. */ +function hostEngines(host: () => Host, loader: EngineLoader | undefined): HostEngines { + let loaded: Promise | undefined; + let preferred: SdkSet | undefined; + const root = () => host().paths().stateRoot; + const load = async (set: SdkSet): Promise => { + if (loaded === undefined) { + if (loader === undefined) throw new Error('No SDK engine is installed: the host is given an engine loader (createHost\'s engineLoader)'); + claimSdkSet(set); + loaded = loader(set, host()); + } + const engine = await loaded; + if (engine.set !== set) throw new OtherSdkSetError(engine.set, set); + return engine; + }; + return { + load, + for: async (network: NetworkName) => load(sdkSetOf(network, root())), + any: () => loaded ?? load(preferred ?? 'rc'), + prefer: (network: NetworkName) => { preferred = sdkSetOf(network, root()); }, + }; } diff --git a/packages/engine-beta/api-report.md b/packages/engine-beta/api-report.md index 9ee762a8..a6a7d087 100644 --- a/packages/engine-beta/api-report.md +++ b/packages/engine-beta/api-report.md @@ -5,8 +5,12 @@ Generated by `node scripts/api-report.mjs write` from the code: every module the ## `@kuiralabs/midnight-engine-beta` ```ts -import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare const betaEngine: Engine; +import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; +import { type RepoDeps } from "./wallet-data-repository.ts"; +export interface BetaEngineOptions { + readonly repository?: RepoDeps; +} +export declare function createBetaEngine(host: EngineHost, options?: BetaEngineOptions): Engine; ``` ## `@kuiralabs/midnight-engine-beta/addresses` @@ -24,8 +28,9 @@ export declare function assertAddress(address: string, kind: "shielded" | "unshi ```ts import { type TransferResult } from "./transfer.ts"; import type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; export type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function airdropNight(params: AirdropParams): Promise; +export declare function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise; ``` ## `@kuiralabs/midnight-engine-beta/contract-providers` @@ -199,7 +204,7 @@ export declare function validateDustCacheChainId(network: string, currentChainId ```ts import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type WalletDataRepository } from "./wallet-data-repository.ts"; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; @@ -209,7 +214,7 @@ export interface DustExportOptions { notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; - repository?: WalletDataRepository; + repository: WalletDataRepository; buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; log?: VerboseLog; } @@ -219,10 +224,11 @@ export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, ## `@kuiralabs/midnight-engine-beta/dust-register` ```ts +import type { WalletDataRepository } from "./wallet-data-repository.ts"; import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; +export declare function registerDust(repo: WalletDataRepository, seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; ``` ## `@kuiralabs/midnight-engine-beta/dust-sync-native` @@ -231,6 +237,7 @@ export declare function registerDust(seed: Buffer, networkConfig: NetworkConfig, import * as ledger from "@midnightntwrk/ledger-v9"; import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; +import type { Settings } from "@kuiralabs/midnight-cli-core/lib/settings"; export interface SidecarCheckpoint { dust_state: string; last_applied_event_id: number; @@ -248,13 +255,14 @@ interface NativeFetchOptions { signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; root: string; + settings: Settings; } -export declare function resolveSidecarBinary(): string | null; +export declare function resolveSidecarBinary(settings: Pick): string | null; export declare function platformPackageBinary(fromUrl: string): string | null; -export declare function nativeDustSyncAvailable(): boolean; +export declare function nativeDustSyncAvailable(settings: Pick): boolean; export declare function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): "existing" | "seed" | "fresh"; export declare function runDustSyncNative(seed: Buffer, network: NetworkConfig, opts: NativeFetchOptions): Promise; -export declare function adaptResult(cp: SidecarCheckpoint): DustDirectResult; +export declare function adaptResult(cp: SidecarCheckpoint, settings: Pick): DustDirectResult; ``` ## `@kuiralabs/midnight-engine-beta/dust-wallet` @@ -363,8 +371,12 @@ export declare function feeOnlyRefusals(tx: FeeCheckTransaction, walletKey: Sign ## `@kuiralabs/midnight-engine-beta/index` ```ts -import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare const betaEngine: Engine; +import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; +import { type RepoDeps } from "./wallet-data-repository.ts"; +export interface BetaEngineOptions { + readonly repository?: RepoDeps; +} +export declare function createBetaEngine(host: EngineHost, options?: BetaEngineOptions): Engine; ``` ## `@kuiralabs/midnight-engine-beta/ledger-parameters` @@ -474,13 +486,14 @@ import { UnshieldedAddress, type DustAddress } from "@midnightntwrk/wallet-sdk-a import { type FacadeState, type UtxoWithMeta } from "@midnightntwrk/wallet-sdk-facade"; import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import { type FacadeBundle } from "./facade.ts"; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; export declare function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress; export { isDustRelatedError, isSdkInsufficientFundsError } from "@kuiralabs/midnight-cli-core/lib/sdk-errors"; import type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export declare function registerNightUtxos(bundle: FacadeBundle, nightUtxos: readonly UtxoWithMeta[], dustReceiverAddress: DustAddress, onStatus?: (status: string) => void): Promise; export declare function ensureDust(bundle: FacadeBundle, onStatus?: (status: string) => void, syncedState?: FacadeState): Promise; -export declare function executeTransfer(params: TransferParams): Promise; +export declare function executeTransfer(repo: WalletDataRepository, params: TransferParams): Promise; ``` ## `@kuiralabs/midnight-engine-beta/tx-inspect` @@ -494,7 +507,8 @@ export declare function inspectTxHex(txHex: string, stage: "unsealed" | "sealed" ```ts import type { EngineWallet } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare const betaWallet: EngineWallet; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; +export declare function createBetaWallet(repo: WalletDataRepository): EngineWallet; ``` ## `@kuiralabs/midnight-engine-beta/wallet-data-repository` @@ -511,7 +525,7 @@ import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subsc import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; -import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustView extends DustBalance { state: ledger.DustLocalState; @@ -551,7 +565,6 @@ export interface RepoDeps { onProgress?: (applied: number, max: number) => void; onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; root: string; - notice: NoticeSink; log?: VerboseLog; }) => Promise; fetchChainId?: (nodeWsUrl: string) => Promise; @@ -569,7 +582,7 @@ export declare class WalletDataRepository { private readonly dustMemo; private readonly unshieldedMemo; private readonly tipMemo; - constructor(deps?: RepoDeps); + constructor(host: EngineHost, deps?: RepoDeps); private keepCachesOfThisIndexer; walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise; private freshWalletOnDustCheckpoint; @@ -583,6 +596,4 @@ export declare class WalletDataRepository { private getTip; private deleteByPrefix; } -export declare function defaultRepository(): WalletDataRepository; -export declare function setDefaultRepository(repo: WalletDataRepository | null): void; ``` diff --git a/packages/engine-beta/src/airdrop.ts b/packages/engine-beta/src/airdrop.ts index f31eb5aa..bbf732cd 100644 --- a/packages/engine-beta/src/airdrop.ts +++ b/packages/engine-beta/src/airdrop.ts @@ -5,13 +5,14 @@ import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; -/** Sends `amountNight` NIGHT from genesis to `recipientAddress`. */ -export async function airdropNight(params: AirdropParams): Promise { +/** Sends `amountNight` NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ +export async function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise { try { - return await executeTransfer({ ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); + return await executeTransfer(repo, { ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); } catch (err) { if (err instanceof Error && err.message.toLowerCase().includes('dust')) { throw new Error( diff --git a/packages/engine-beta/src/dust-direct.ts b/packages/engine-beta/src/dust-direct.ts index d462fdc1..3d901581 100644 --- a/packages/engine-beta/src/dust-direct.ts +++ b/packages/engine-beta/src/dust-direct.ts @@ -18,9 +18,8 @@ import { INITIAL_DUST_GRACE_PERIOD_SECONDS, } from '@kuiralabs/midnight-cli-core/lib/constants'; import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; -import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; -// MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): settings().isDustCollapseOff. +// MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): the repository then passes `collapse: false`, read from its host's settings. /** * Data the collapse needs to keep working correctly across restarts: which @@ -151,7 +150,7 @@ export function readDustBalanceDirect( collapse, } = options; - const collapseEnabled = collapse !== false && !settings().isDustCollapseOff; + const collapseEnabled = collapse !== false; // Apply events in chunks as they arrive so the final step is cheap and // progress updates stay responsive. Replaying 100k events in a single diff --git a/packages/engine-beta/src/dust-export.ts b/packages/engine-beta/src/dust-export.ts index 80699521..8524107e 100644 --- a/packages/engine-beta/src/dust-export.ts +++ b/packages/engine-beta/src/dust-export.ts @@ -20,7 +20,7 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -34,8 +34,8 @@ export interface DustExportOptions { notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; - /** Injectable for tests; defaults to the process-wide repository. */ - repository?: WalletDataRepository; + /** The engine's repository the sync runs through. */ + repository: WalletDataRepository; /** * Produce the base (empty) dust snapshot to overlay onto. Injectable for tests; * defaults to building a fresh facade from keys and reading its dust snapshot. @@ -77,7 +77,7 @@ export async function exportDustSnapshot( options: DustExportOptions, ): Promise { const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); - const repo = options.repository ?? defaultRepository(); + const repo = options.repository; const view = await repo.dust(seedBuffer, networkConfig, { root: options.root, diff --git a/packages/engine-beta/src/dust-register.ts b/packages/engine-beta/src/dust-register.ts index d19182d0..ce6cc699 100644 --- a/packages/engine-beta/src/dust-register.ts +++ b/packages/engine-beta/src/dust-register.ts @@ -4,7 +4,7 @@ import { waitForLiteSyncedState } from './facade.ts'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { ensureDust } from './transfer.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; @@ -12,12 +12,12 @@ import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight- export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; - -export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { +/** Registers a seed's NIGHT for Dust on the engine's repository `repo`, unless it has Dust already. */ +export async function registerDust(repo: WalletDataRepository, seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root, notice } = options; const stopListening = sdkWarnings.listen(onSyncWarning); try { - const { result, dustBalance } = await defaultRepository().withFacade( + const { result, dustBalance } = await repo.withFacade( seed, networkConfig, async ({ bundle, state }) => { diff --git a/packages/engine-beta/src/dust-sync-native.ts b/packages/engine-beta/src/dust-sync-native.ts index 8779b2f9..8434bf70 100644 --- a/packages/engine-beta/src/dust-sync-native.ts +++ b/packages/engine-beta/src/dust-sync-native.ts @@ -19,7 +19,7 @@ import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import type { Settings } from '@kuiralabs/midnight-cli-core/lib/settings'; import { cacheRootDir, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; @@ -43,15 +43,17 @@ interface NativeFetchOptions { onProgress?: (applied: number, max: number) => void; /** The state root: the checkpoint lives beside the other Dust caches under it. */ root: string; + /** The engine's host's settings: the sidecar to run, and whether to collapse its state. */ + settings: Settings; } /** - * Locate the sidecar binary. Order: explicit env override → the (Phase 3) - * optional platform package → the dev build under sidecar/dust-sync. Returns - * null when none resolve (→ WASM fallback). + * Locate the sidecar binary. Order: the settings' override (MN_DUST_SYNC_BIN) → + * the (Phase 3) optional platform package → the dev build under + * sidecar/dust-sync. Returns null when none resolve (→ WASM fallback). */ -export function resolveSidecarBinary(): string | null { - const fromEnv = settings().dustSyncBin; +export function resolveSidecarBinary(settings: Pick): string | null { + const fromEnv = settings.dustSyncBin; if (fromEnv && existsSync(fromEnv)) return fromEnv; const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; @@ -94,10 +96,10 @@ const SIDECAR_LEDGER: number = 8; /** The ledger this build of mn targets. */ const MN_LEDGER: number = 9; -export function nativeDustSyncAvailable(): boolean { +export function nativeDustSyncAvailable(settings: Pick): boolean { if (SIDECAR_LEDGER !== MN_LEDGER) return false; - if (settings().isNativeDustOff) return false; - return resolveSidecarBinary() !== null; + if (settings.isNativeDustOff) return false; + return resolveSidecarBinary(settings) !== null; } /** @@ -144,7 +146,7 @@ export function runDustSyncNative( opts: NativeFetchOptions, ): Promise { return new Promise((resolve, reject) => { - const bin = resolveSidecarBinary(); + const bin = resolveSidecarBinary(opts.settings); if (!bin) { reject(new Error('dust-sync sidecar not found')); return; } assertEndpointUsable(network.indexerWS); @@ -214,7 +216,7 @@ export function runDustSyncNative( const cp: SidecarCheckpoint = lastLine ? JSON.parse(lastLine) : JSON.parse(readFileSync(out, 'utf-8')); - resolve(adaptResult(cp)); + resolve(adaptResult(cp, opts.settings)); } catch (err) { reject(new Error(`dust-sync output parse failed: ${(err as Error).message}`)); } @@ -222,8 +224,8 @@ export function runDustSyncNative( }); } -/** Map the sidecar's checkpoint JSON to a `DustDirectResult`. Exported for tests. */ -export function adaptResult(cp: SidecarCheckpoint): DustDirectResult { +/** Map the sidecar's checkpoint JSON to a `DustDirectResult`, collapsed unless the settings say not to. Exported for tests. */ +export function adaptResult(cp: SidecarCheckpoint, settings: Pick): DustDirectResult { const now = new Date(); let state = ledger.DustLocalState.deserialize(new Uint8Array(Buffer.from(cp.dust_state, 'hex'))); // The Rust sidecar doesn't collapse the generation tree, so a native sync would @@ -231,7 +233,7 @@ export function adaptResult(cp: SidecarCheckpoint): DustDirectResult { // vs ~23 KB collapsed). Apply the same TS collapse the WASM reader uses, reusing // the owned-indices + frontier the checkpoint already carries. Idempotent, and it // fails safe to the uncollapsed state via the balance+root guard. - if (!settings().isDustCollapseOff) { + if (!settings.isDustCollapseOff) { const owned = new Set(cp.owned_generation_indices.map((i) => BigInt(i))); state = collapseForeignGenerations(state, owned, BigInt(cp.generation_frontier)).state; } diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts index 8dbbb6cf..63dc0d5d 100644 --- a/packages/engine-beta/src/index.ts +++ b/packages/engine-beta/src/index.ts @@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; import * as ledger from '@midnightntwrk/ledger-v9'; import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; @@ -15,7 +15,8 @@ import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; import { inspectTxHex } from './tx-inspect.ts'; import { readOffer, spentNullifiers } from './offer-reader.ts'; -import { betaWallet } from './wallet.ts'; +import { createBetaWallet } from './wallet.ts'; +import { WalletDataRepository, type RepoDeps } from './wallet-data-repository.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; @@ -28,7 +29,23 @@ const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, ' .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name)); assertOneSdkCopy("mn's beta engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); -export const betaEngine: Engine = { +/** What an beta engine is made with besides its host. */ +export interface BetaEngineOptions { + /** Its wallet repository's seams (the clock, the chain's and the indexer's reads), for a test standing in for the network. */ + readonly repository?: RepoDeps; +} + +/** + * The beta engine for a host: its own wallet repository (the in-memory caches), + * reading the host's settings and telling the host's notices. Each host gets + * one of its own; the work every engine does alike is shared. + */ +export function createBetaEngine(host: EngineHost, options: BetaEngineOptions = {}): Engine { + return { ...SHARED, wallet: createBetaWallet(new WalletDataRepository(host, options.repository)) }; +} + +// The parts that keep no state: the same for every host's engine. +const SHARED: Omit = { set: 'beta', keys: { unshieldedAddress: deriveUnshieldedAddress, @@ -78,5 +95,4 @@ export const betaEngine: Engine = { readers: { shieldedBalance: readShieldedBalanceCached, }, - wallet: betaWallet, }; diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index 86d665d8..f678e2ba 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -10,7 +10,7 @@ import * as rx from 'rxjs'; import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; import { @@ -412,15 +412,15 @@ async function buildAndSubmitTransfer( // ── Main transfer flow ─────────────────────────────────────────────── /** - * Execute a full transfer flow. The lifecycle and recovery loops live in - * `repo.withFacade(...)`: pre-prime dust, sync-retry on stale-cache / + * Execute a full transfer flow on the engine's repository `repo`. The + * lifecycle and recovery loops live in `repo.withFacade(...)`: pre-prime dust, sync-retry on stale-cache / * timeout, cold-start race retry on SDK InsufficientFunds, save+invalidate * on success, stopFacade in finally. This function only owns the * transfer-specific work: pre-flight checks (balance, dust threshold), * `ensureDust` orchestration, and the build/sign/prove/submit retry loop * (handled inside `buildAndSubmitTransfer` for stale-UTXO + dust errors). */ -export async function executeTransfer(params: TransferParams): Promise { +export async function executeTransfer(repo: WalletDataRepository, params: TransferParams): Promise { const { seedBuffer, networkConfig, @@ -448,7 +448,7 @@ export async function executeTransfer(params: TransferParams): Promise { diff --git a/packages/engine-beta/src/wallet-data-repository.ts b/packages/engine-beta/src/wallet-data-repository.ts index 397d8866..489f1119 100644 --- a/packages/engine-beta/src/wallet-data-repository.ts +++ b/packages/engine-beta/src/wallet-data-repository.ts @@ -1,7 +1,7 @@ // Wallet data repository — single owner of cache + tip-aware invalidation. // // What this hides from callers: -// • In-memory layer (per-process; matters for the long-lived MCP server) +// • In-memory layer (the engine's, so one per host; matters for the long-lived MCP server) // • On-disk layer (shared across `mn` shell invocations) // • Tip-aware invalidation (cache valid iff chain tip unchanged) // • Force-fresh override @@ -55,7 +55,7 @@ import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; import { deriveDustSeed } from './derivation.ts'; import { deriveUnshieldedAddress } from './derive-address.ts'; import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain/lib/event-tip'; -import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; // ── Public types ────────────────────────────────────────── @@ -136,8 +136,6 @@ export interface RepoDeps { onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; /** The state root of the caches; the native sidecar keeps its checkpoint beside them. */ root: string; - /** Where the read's lines for the person go (the host's notices). */ - notice: NoticeSink; /** The call's verbose lines. */ log?: VerboseLog; }, @@ -198,11 +196,12 @@ export class WalletDataRepository { private readonly unshieldedMemo = new Map>(); private readonly tipMemo = new Map(); - constructor(deps: RepoDeps = {}) { + /** A repository for an engine: its host's settings choose how Dust is read, and its notices go to the host. */ + constructor(host: EngineHost, deps: RepoDeps = {}) { this.now = deps.now ?? Date.now; this.fetchTip = deps.fetchTip ?? defaultTipFetcher; this.fetchUnshielded = deps.fetchUnshielded ?? defaultUnshieldedFetcher; - this.fetchDust = deps.fetchDust ?? nativeOrWasmDustFetcher; + this.fetchDust = deps.fetchDust ?? nativeOrWasmDustFetcher(host); this.fetchChainId = deps.fetchChainId ?? getChainGenesisHash; this.fetchEventTip = deps.fetchEventTip ?? fetchEventTip; this.fetchProtocolVersion = deps.fetchProtocolVersion ?? fetchProtocolVersion; @@ -304,7 +303,6 @@ export class WalletDataRepository { result = await this.fetchDust(seed, network, { root: opts.root, - notice: opts.notice, startFromId, initialState: cached?.state, initialRetention: cached?.retention, @@ -683,39 +681,40 @@ function defaultDustFetcher( root: string; log?: VerboseLog; }, + collapse: boolean, ): Promise { const dustSeed = deriveDustSeed(seed); const dustSecretKey = ledger.DustSecretKey.fromSeed(dustSeed); - return readDustBalanceDirect(dustSecretKey, network.indexerWS, opts); + return readDustBalanceDirect(dustSecretKey, network.indexerWS, { ...opts, collapse }); } -// Said once per process: the first sync from the start of a chain's Dust history. -let saidWasmDust = false; - /** * Prefer the native sidecar (~5x faster cold dust sync) when it's available; * fall back to the WASM reader on a missing binary or any failure. The sidecar * is an optional accelerator, so a fallback is a slowdown, never a break. - * No sidecar replays ledger 9 yet, so this engine reads Dust in WASM, and says - * so before a sync from the start of the chain's history. + * Each sync reads the host's settings: the sidecar to run, whether to run it, + * and whether to collapse the generation tree. + * No sidecar replays ledger 9 yet, so this engine reads Dust in WASM, and tells + * its host so once, before its first sync from the start of a chain's history. */ -async function nativeOrWasmDustFetcher( - seed: Buffer, - network: NetworkConfig, - opts: Parameters>[2], -): Promise { - if (!nativeDustSyncAvailable() && opts.startFromId === 0 && !saidWasmDust) { - saidWasmDust = true; - opts.notice(` Reading ${network.networkId}'s Dust history in WASM: no native sidecar runs ledger 9 yet, so a first sync takes a few minutes (about 2.5 on stagenet), then it is cached.`); - } - if (nativeDustSyncAvailable()) { - try { - return await runDustSyncNative(seed, network, opts); - } catch (err) { - opts.log?.('dust', `native sidecar failed, using WASM: ${(err as Error).message}`); +function nativeOrWasmDustFetcher(host: EngineHost): NonNullable { + let saidWasmDust = false; + return async (seed, network, opts) => { + const settings = host.settings(); + const native = nativeDustSyncAvailable(settings); + if (!native && opts.startFromId === 0 && !saidWasmDust) { + saidWasmDust = true; + host.notice(` Reading ${network.networkId}'s Dust history in WASM: no native sidecar runs ledger 9 yet, so a first sync takes a few minutes (about 2.5 on stagenet), then it is cached.`); } - } - return defaultDustFetcher(seed, network, opts); + if (native) { + try { + return await runDustSyncNative(seed, network, { ...opts, settings }); + } catch (err) { + opts.log?.('dust', `native sidecar failed, using WASM: ${(err as Error).message}`); + } + } + return defaultDustFetcher(seed, network, opts, !settings.isDustCollapseOff); + }; } // ── Helpers ─────────────────────────────────────────────── @@ -725,21 +724,3 @@ function networkNameOf(network: NetworkConfig): NetworkName { if (isValidNetworkName(lower)) return lower; throw new Error(`Unsupported network: ${network.networkId}`); } - -// ── Process-wide singleton ──────────────────────────────── - -let defaultRepo: WalletDataRepository | null = null; - -/** - * Process-wide repository instance. Long-lived MCP sessions share this so - * the in-memory cache layer is meaningful across tool calls. - */ -export function defaultRepository(): WalletDataRepository { - if (!defaultRepo) defaultRepo = new WalletDataRepository(); - return defaultRepo; -} - -/** Test/diagnostic: replace the process singleton (e.g. with different fetchers). */ -export function setDefaultRepository(repo: WalletDataRepository | null): void { - defaultRepo = repo; -} diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index cc8ee2b2..09d8d506 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -29,18 +29,18 @@ import { ensureDust, executeTransfer } from './transfer.ts'; import { airdropNight } from './airdrop.ts'; import { registerDust } from './dust-register.ts'; import { exportDustSnapshot } from './dust-export.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import { createDAppConnector } from './dapp-connector.ts'; const HOUR_MS = 60 * 60 * 1000; -async function shieldedTransfer(params: ShieldedTransferParams): Promise { +async function shieldedTransfer(repo: WalletDataRepository, params: ShieldedTransferParams): Promise { const { seed, root, notice, network, networkConfig, amount, progress, signal } = params; const networkId = getNetworkId(networkConfig.networkId); const nightToken = ledger.unshieldedToken().raw; const receiverAddress = decodeShieldedAddress(params.recipient, network); - return defaultRepository().withFacade( + return repo.withFacade( seed, networkConfig, async ({ bundle, state }) => { @@ -178,7 +178,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv } } -const openConnector: EngineWallet['openConnector'] = async (options): Promise => { +async function openConnector(repo: WalletDataRepository, options: Parameters[0]): Promise { const { seed, root, notice, network, networkConfig, address, syncMode, signal, onMessage } = options; // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig, undefined, signal); @@ -194,7 +194,6 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise { +function serveWallet(repo: WalletDataRepository, options: Parameters[0], serve: (session: ServedWalletSession) => Promise): Promise { const { seed, root, notice, networkConfig, network, address, syncMode } = options; // The repository owns validating the caches, priming Dust, building the // facade, syncing (with retries) and stopping it. Its save is skipped: mn // serve saves only when no transaction is pending, since the SDK drops // pending Dust on serialization and would persist dust=0. - return defaultRepository().withFacade(seed, networkConfig, async ({ bundle }) => { + return repo.withFacade(seed, networkConfig, async ({ bundle }) => { let lastState: Awaited> | undefined; const session: ServedWalletSession = { async waitForDust() { @@ -306,21 +305,24 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { onSyncProgress: options.onSyncProgress, onSyncDetail: options.onSyncDetail, }); -}; +} -export const betaWallet: EngineWallet = { - unshieldedBalance: (address, networkConfig, options) => defaultRepository().unshielded(address, networkConfig, options), - async dustBalance(seed, networkConfig, options) { - const { state: _state, ...balance } = await defaultRepository().dust(seed, networkConfig, options); - return balance; - }, - transfer: executeTransfer, - airdrop: airdropNight, - shieldedTransfer, - registerDust, - exportDust: (seed, network, networkConfig, options) => exportDustSnapshot(seed, network, networkConfig, options), - prepNightBalance, - prepDust, - openConnector, - serveWallet, -}; +/** The wallet of an engine whose repository (its caches) is `repo`. */ +export function createBetaWallet(repo: WalletDataRepository): EngineWallet { + return { + unshieldedBalance: (address, networkConfig, options) => repo.unshielded(address, networkConfig, options), + async dustBalance(seed, networkConfig, options) { + const { state: _state, ...balance } = await repo.dust(seed, networkConfig, options); + return balance; + }, + transfer: (params) => executeTransfer(repo, params), + airdrop: (params) => airdropNight(repo, params), + shieldedTransfer: (params) => shieldedTransfer(repo, params), + registerDust: (seed, networkConfig, options) => registerDust(repo, seed, networkConfig, options), + exportDust: (seed, network, networkConfig, options) => exportDustSnapshot(seed, network, networkConfig, { ...options, repository: repo }), + prepNightBalance, + prepDust, + openConnector: (options) => openConnector(repo, options), + serveWallet: (options, serve) => serveWallet(repo, options, serve), + }; +} diff --git a/packages/engine-rc/api-report.md b/packages/engine-rc/api-report.md index c78b63b0..4906b483 100644 --- a/packages/engine-rc/api-report.md +++ b/packages/engine-rc/api-report.md @@ -5,8 +5,12 @@ Generated by `node scripts/api-report.mjs write` from the code: every module the ## `@kuiralabs/midnight-engine-rc` ```ts -import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare const rcEngine: Engine; +import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; +import { type RepoDeps } from "./wallet-data-repository.ts"; +export interface RcEngineOptions { + readonly repository?: RepoDeps; +} +export declare function createRcEngine(host: EngineHost, options?: RcEngineOptions): Engine; ``` ## `@kuiralabs/midnight-engine-rc/addresses` @@ -24,8 +28,9 @@ export declare function assertAddress(address: string, kind: "shielded" | "unshi ```ts import { type TransferResult } from "./transfer.ts"; import type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; export type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function airdropNight(params: AirdropParams): Promise; +export declare function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise; ``` ## `@kuiralabs/midnight-engine-rc/contract-providers` @@ -199,7 +204,7 @@ export declare function validateDustCacheChainId(network: string, currentChainId ```ts import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type WalletDataRepository } from "./wallet-data-repository.ts"; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; @@ -209,7 +214,7 @@ export interface DustExportOptions { notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; - repository?: WalletDataRepository; + repository: WalletDataRepository; buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; log?: VerboseLog; } @@ -219,10 +224,11 @@ export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, ## `@kuiralabs/midnight-engine-rc/dust-register` ```ts +import type { WalletDataRepository } from "./wallet-data-repository.ts"; import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; +export declare function registerDust(repo: WalletDataRepository, seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; ``` ## `@kuiralabs/midnight-engine-rc/dust-sync-native` @@ -231,6 +237,7 @@ export declare function registerDust(seed: Buffer, networkConfig: NetworkConfig, import * as ledger from "@midnightntwrk/ledger-v9"; import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; +import type { Settings } from "@kuiralabs/midnight-cli-core/lib/settings"; export interface SidecarCheckpoint { dust_state: string; last_applied_event_id: number; @@ -248,13 +255,14 @@ interface NativeFetchOptions { signal?: AbortSignal; onProgress?: (applied: number, max: number) => void; root: string; + settings: Settings; } -export declare function resolveSidecarBinary(): string | null; +export declare function resolveSidecarBinary(settings: Pick): string | null; export declare function platformPackageBinary(fromUrl: string): string | null; -export declare function nativeDustSyncAvailable(): boolean; +export declare function nativeDustSyncAvailable(settings: Pick): boolean; export declare function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): "existing" | "seed" | "fresh"; export declare function runDustSyncNative(seed: Buffer, network: NetworkConfig, opts: NativeFetchOptions): Promise; -export declare function adaptResult(cp: SidecarCheckpoint): DustDirectResult; +export declare function adaptResult(cp: SidecarCheckpoint, settings: Pick): DustDirectResult; ``` ## `@kuiralabs/midnight-engine-rc/dust-wallet` @@ -373,8 +381,12 @@ export declare const FORK_SCHEDULE: ProtocolVersion.ForkSchedule; ## `@kuiralabs/midnight-engine-rc/index` ```ts -import type { Engine } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare const rcEngine: Engine; +import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; +import { type RepoDeps } from "./wallet-data-repository.ts"; +export interface RcEngineOptions { + readonly repository?: RepoDeps; +} +export declare function createRcEngine(host: EngineHost, options?: RcEngineOptions): Engine; ``` ## `@kuiralabs/midnight-engine-rc/ledger-parameters` @@ -484,13 +496,14 @@ import { UnshieldedAddress, type DustAddress } from "@midnightntwrk/wallet-sdk/a import { type FacadeState, type UtxoWithMeta } from "@midnightntwrk/wallet-sdk/facade"; import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; import { type FacadeBundle } from "./facade.ts"; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; export declare function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress; export { isDustRelatedError, isSdkInsufficientFundsError } from "@kuiralabs/midnight-cli-core/lib/sdk-errors"; import type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; export declare function registerNightUtxos(bundle: FacadeBundle, nightUtxos: readonly UtxoWithMeta[], dustReceiverAddress: DustAddress, onStatus?: (status: string) => void): Promise; export declare function ensureDust(bundle: FacadeBundle, onStatus?: (status: string) => void, syncedState?: FacadeState): Promise; -export declare function executeTransfer(params: TransferParams): Promise; +export declare function executeTransfer(repo: WalletDataRepository, params: TransferParams): Promise; ``` ## `@kuiralabs/midnight-engine-rc/tx-inspect` @@ -504,7 +517,8 @@ export declare function inspectTxHex(txHex: string, stage: "unsealed" | "sealed" ```ts import type { EngineWallet } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare const rcWallet: EngineWallet; +import type { WalletDataRepository } from "./wallet-data-repository.ts"; +export declare function createRcWallet(repo: WalletDataRepository): EngineWallet; ``` ## `@kuiralabs/midnight-engine-rc/wallet-data-repository` @@ -521,7 +535,7 @@ import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; -import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; +import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; export interface DustView extends DustBalance { state: ledger.DustLocalState; @@ -578,7 +592,7 @@ export declare class WalletDataRepository { private readonly dustMemo; private readonly unshieldedMemo; private readonly tipMemo; - constructor(deps?: RepoDeps); + constructor(host: EngineHost, deps?: RepoDeps); private keepCachesOfThisIndexer; walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise; private freshWalletOnDustCheckpoint; @@ -592,6 +606,4 @@ export declare class WalletDataRepository { private getTip; private deleteByPrefix; } -export declare function defaultRepository(): WalletDataRepository; -export declare function setDefaultRepository(repo: WalletDataRepository | null): void; ``` diff --git a/packages/engine-rc/src/airdrop.ts b/packages/engine-rc/src/airdrop.ts index f31eb5aa..bbf732cd 100644 --- a/packages/engine-rc/src/airdrop.ts +++ b/packages/engine-rc/src/airdrop.ts @@ -5,13 +5,14 @@ import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; -/** Sends `amountNight` NIGHT from genesis to `recipientAddress`. */ -export async function airdropNight(params: AirdropParams): Promise { +/** Sends `amountNight` NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ +export async function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise { try { - return await executeTransfer({ ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); + return await executeTransfer(repo, { ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); } catch (err) { if (err instanceof Error && err.message.toLowerCase().includes('dust')) { throw new Error( diff --git a/packages/engine-rc/src/dust-direct.ts b/packages/engine-rc/src/dust-direct.ts index d462fdc1..3d901581 100644 --- a/packages/engine-rc/src/dust-direct.ts +++ b/packages/engine-rc/src/dust-direct.ts @@ -18,9 +18,8 @@ import { INITIAL_DUST_GRACE_PERIOD_SECONDS, } from '@kuiralabs/midnight-cli-core/lib/constants'; import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; -import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; -// MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): settings().isDustCollapseOff. +// MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): the repository then passes `collapse: false`, read from its host's settings. /** * Data the collapse needs to keep working correctly across restarts: which @@ -151,7 +150,7 @@ export function readDustBalanceDirect( collapse, } = options; - const collapseEnabled = collapse !== false && !settings().isDustCollapseOff; + const collapseEnabled = collapse !== false; // Apply events in chunks as they arrive so the final step is cheap and // progress updates stay responsive. Replaying 100k events in a single diff --git a/packages/engine-rc/src/dust-export.ts b/packages/engine-rc/src/dust-export.ts index 80699521..8524107e 100644 --- a/packages/engine-rc/src/dust-export.ts +++ b/packages/engine-rc/src/dust-export.ts @@ -20,7 +20,7 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { defaultRepository, type WalletDataRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -34,8 +34,8 @@ export interface DustExportOptions { notice: NoticeSink; onProgress?: (eventsApplied: number, maxIdSeen: number) => void; signal?: AbortSignal; - /** Injectable for tests; defaults to the process-wide repository. */ - repository?: WalletDataRepository; + /** The engine's repository the sync runs through. */ + repository: WalletDataRepository; /** * Produce the base (empty) dust snapshot to overlay onto. Injectable for tests; * defaults to building a fresh facade from keys and reading its dust snapshot. @@ -77,7 +77,7 @@ export async function exportDustSnapshot( options: DustExportOptions, ): Promise { const pubkeyHex = dustPublicKeyHexFromSeed(seedBuffer); - const repo = options.repository ?? defaultRepository(); + const repo = options.repository; const view = await repo.dust(seedBuffer, networkConfig, { root: options.root, diff --git a/packages/engine-rc/src/dust-register.ts b/packages/engine-rc/src/dust-register.ts index d19182d0..ce6cc699 100644 --- a/packages/engine-rc/src/dust-register.ts +++ b/packages/engine-rc/src/dust-register.ts @@ -4,7 +4,7 @@ import { waitForLiteSyncedState } from './facade.ts'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { ensureDust } from './transfer.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; @@ -12,12 +12,12 @@ import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight- export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; - -export async function registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { +/** Registers a seed's NIGHT for Dust on the engine's repository `repo`, unless it has Dust already. */ +export async function registerDust(repo: WalletDataRepository, seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise { const { signal, onStatus, onSyncProgress, onSyncDetail, onSyncWarning, sdkWarnings, log, root, notice } = options; const stopListening = sdkWarnings.listen(onSyncWarning); try { - const { result, dustBalance } = await defaultRepository().withFacade( + const { result, dustBalance } = await repo.withFacade( seed, networkConfig, async ({ bundle, state }) => { diff --git a/packages/engine-rc/src/dust-sync-native.ts b/packages/engine-rc/src/dust-sync-native.ts index 8779b2f9..8434bf70 100644 --- a/packages/engine-rc/src/dust-sync-native.ts +++ b/packages/engine-rc/src/dust-sync-native.ts @@ -19,7 +19,7 @@ import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import type { Settings } from '@kuiralabs/midnight-cli-core/lib/settings'; import { cacheRootDir, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; @@ -43,15 +43,17 @@ interface NativeFetchOptions { onProgress?: (applied: number, max: number) => void; /** The state root: the checkpoint lives beside the other Dust caches under it. */ root: string; + /** The engine's host's settings: the sidecar to run, and whether to collapse its state. */ + settings: Settings; } /** - * Locate the sidecar binary. Order: explicit env override → the (Phase 3) - * optional platform package → the dev build under sidecar/dust-sync. Returns - * null when none resolve (→ WASM fallback). + * Locate the sidecar binary. Order: the settings' override (MN_DUST_SYNC_BIN) → + * the (Phase 3) optional platform package → the dev build under + * sidecar/dust-sync. Returns null when none resolve (→ WASM fallback). */ -export function resolveSidecarBinary(): string | null { - const fromEnv = settings().dustSyncBin; +export function resolveSidecarBinary(settings: Pick): string | null { + const fromEnv = settings.dustSyncBin; if (fromEnv && existsSync(fromEnv)) return fromEnv; const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; @@ -94,10 +96,10 @@ const SIDECAR_LEDGER: number = 8; /** The ledger this build of mn targets. */ const MN_LEDGER: number = 9; -export function nativeDustSyncAvailable(): boolean { +export function nativeDustSyncAvailable(settings: Pick): boolean { if (SIDECAR_LEDGER !== MN_LEDGER) return false; - if (settings().isNativeDustOff) return false; - return resolveSidecarBinary() !== null; + if (settings.isNativeDustOff) return false; + return resolveSidecarBinary(settings) !== null; } /** @@ -144,7 +146,7 @@ export function runDustSyncNative( opts: NativeFetchOptions, ): Promise { return new Promise((resolve, reject) => { - const bin = resolveSidecarBinary(); + const bin = resolveSidecarBinary(opts.settings); if (!bin) { reject(new Error('dust-sync sidecar not found')); return; } assertEndpointUsable(network.indexerWS); @@ -214,7 +216,7 @@ export function runDustSyncNative( const cp: SidecarCheckpoint = lastLine ? JSON.parse(lastLine) : JSON.parse(readFileSync(out, 'utf-8')); - resolve(adaptResult(cp)); + resolve(adaptResult(cp, opts.settings)); } catch (err) { reject(new Error(`dust-sync output parse failed: ${(err as Error).message}`)); } @@ -222,8 +224,8 @@ export function runDustSyncNative( }); } -/** Map the sidecar's checkpoint JSON to a `DustDirectResult`. Exported for tests. */ -export function adaptResult(cp: SidecarCheckpoint): DustDirectResult { +/** Map the sidecar's checkpoint JSON to a `DustDirectResult`, collapsed unless the settings say not to. Exported for tests. */ +export function adaptResult(cp: SidecarCheckpoint, settings: Pick): DustDirectResult { const now = new Date(); let state = ledger.DustLocalState.deserialize(new Uint8Array(Buffer.from(cp.dust_state, 'hex'))); // The Rust sidecar doesn't collapse the generation tree, so a native sync would @@ -231,7 +233,7 @@ export function adaptResult(cp: SidecarCheckpoint): DustDirectResult { // vs ~23 KB collapsed). Apply the same TS collapse the WASM reader uses, reusing // the owned-indices + frontier the checkpoint already carries. Idempotent, and it // fails safe to the uncollapsed state via the balance+root guard. - if (!settings().isDustCollapseOff) { + if (!settings.isDustCollapseOff) { const owned = new Set(cp.owned_generation_indices.map((i) => BigInt(i))); state = collapseForeignGenerations(state, owned, BigInt(cp.generation_frontier)).state; } diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index 489403e7..22e01ff4 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; import * as ledger from '@midnightntwrk/ledger-v9'; import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; @@ -14,7 +14,8 @@ import { rawContractState } from './contract-providers.ts'; import { assertAddress } from './addresses.ts'; import { inspectTxHex } from './tx-inspect.ts'; import { readOffer, spentNullifiers } from './offer-reader.ts'; -import { rcWallet } from './wallet.ts'; +import { createRcWallet } from './wallet.ts'; +import { WalletDataRepository, type RepoDeps } from './wallet-data-repository.ts'; import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; @@ -27,7 +28,23 @@ const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, ' .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name)); assertOneSdkCopy("mn's rc engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); -export const rcEngine: Engine = { +/** What an rc engine is made with besides its host. */ +export interface RcEngineOptions { + /** Its wallet repository's seams (the clock, the chain's and the indexer's reads), for a test standing in for the network. */ + readonly repository?: RepoDeps; +} + +/** + * The rc engine for a host: its own wallet repository (the in-memory caches), + * reading the host's settings and telling the host's notices. Each host gets + * one of its own; the work every engine does alike is shared. + */ +export function createRcEngine(host: EngineHost, options: RcEngineOptions = {}): Engine { + return { ...SHARED, wallet: createRcWallet(new WalletDataRepository(host, options.repository)) }; +} + +// The parts that keep no state: the same for every host's engine. +const SHARED: Omit = { set: 'rc', keys: { unshieldedAddress: deriveUnshieldedAddress, @@ -77,5 +94,4 @@ export const rcEngine: Engine = { readers: { shieldedBalance: readShieldedBalanceCached, }, - wallet: rcWallet, }; diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index f0d64504..f4d75d65 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -10,7 +10,7 @@ import * as rx from 'rxjs'; import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; import { @@ -411,15 +411,15 @@ async function buildAndSubmitTransfer( // ── Main transfer flow ─────────────────────────────────────────────── /** - * Execute a full transfer flow. The lifecycle and recovery loops live in - * `repo.withFacade(...)`: pre-prime dust, sync-retry on stale-cache / + * Execute a full transfer flow on the engine's repository `repo`. The + * lifecycle and recovery loops live in `repo.withFacade(...)`: pre-prime dust, sync-retry on stale-cache / * timeout, cold-start race retry on SDK InsufficientFunds, save+invalidate * on success, stopFacade in finally. This function only owns the * transfer-specific work: pre-flight checks (balance, dust threshold), * `ensureDust` orchestration, and the build/sign/prove/submit retry loop * (handled inside `buildAndSubmitTransfer` for stale-UTXO + dust errors). */ -export async function executeTransfer(params: TransferParams): Promise { +export async function executeTransfer(repo: WalletDataRepository, params: TransferParams): Promise { const { seedBuffer, networkConfig, @@ -447,7 +447,7 @@ export async function executeTransfer(params: TransferParams): Promise { diff --git a/packages/engine-rc/src/wallet-data-repository.ts b/packages/engine-rc/src/wallet-data-repository.ts index 9c0ec934..ee1cb7a9 100644 --- a/packages/engine-rc/src/wallet-data-repository.ts +++ b/packages/engine-rc/src/wallet-data-repository.ts @@ -1,7 +1,7 @@ // Wallet data repository — single owner of cache + tip-aware invalidation. // // What this hides from callers: -// • In-memory layer (per-process; matters for the long-lived MCP server) +// • In-memory layer (the engine's, so one per host; matters for the long-lived MCP server) // • On-disk layer (shared across `mn` shell invocations) // • Tip-aware invalidation (cache valid iff chain tip unchanged) // • Force-fresh override @@ -55,7 +55,7 @@ import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; import { deriveDustSeed } from './derivation.ts'; import { deriveUnshieldedAddress } from './derive-address.ts'; import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain/lib/event-tip'; -import type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; // ── Public types ────────────────────────────────────────── @@ -196,11 +196,12 @@ export class WalletDataRepository { private readonly unshieldedMemo = new Map>(); private readonly tipMemo = new Map(); - constructor(deps: RepoDeps = {}) { + /** A repository for an engine: its host's settings choose how Dust is read, and its notices go to the host. */ + constructor(host: EngineHost, deps: RepoDeps = {}) { this.now = deps.now ?? Date.now; this.fetchTip = deps.fetchTip ?? defaultTipFetcher; this.fetchUnshielded = deps.fetchUnshielded ?? defaultUnshieldedFetcher; - this.fetchDust = deps.fetchDust ?? nativeOrWasmDustFetcher; + this.fetchDust = deps.fetchDust ?? nativeOrWasmDustFetcher(host); this.fetchChainId = deps.fetchChainId ?? getChainGenesisHash; this.fetchEventTip = deps.fetchEventTip ?? fetchEventTip; this.fetchProtocolVersion = deps.fetchProtocolVersion ?? fetchProtocolVersion; @@ -680,30 +681,32 @@ function defaultDustFetcher( root: string; log?: VerboseLog; }, + collapse: boolean, ): Promise { const dustSeed = deriveDustSeed(seed); const dustSecretKey = ledger.DustSecretKey.fromSeed(dustSeed); - return readDustBalanceDirect(dustSecretKey, network.indexerWS, opts); + return readDustBalanceDirect(dustSecretKey, network.indexerWS, { ...opts, collapse }); } /** * Prefer the native sidecar (~5x faster cold dust sync) when it's available; * fall back to the WASM reader on a missing binary or any failure. The sidecar * is an optional accelerator, so a fallback is a slowdown, never a break. + * Each sync reads the host's settings: the sidecar to run, whether to run it, + * and whether to collapse the generation tree. */ -async function nativeOrWasmDustFetcher( - seed: Buffer, - network: NetworkConfig, - opts: Parameters[2], -): Promise { - if (nativeDustSyncAvailable()) { - try { - return await runDustSyncNative(seed, network, opts); - } catch (err) { - opts.log?.('dust', `native sidecar failed, using WASM: ${(err as Error).message}`); +function nativeOrWasmDustFetcher(host: EngineHost): NonNullable { + return async (seed, network, opts) => { + const settings = host.settings(); + if (nativeDustSyncAvailable(settings)) { + try { + return await runDustSyncNative(seed, network, { ...opts, settings }); + } catch (err) { + opts.log?.('dust', `native sidecar failed, using WASM: ${(err as Error).message}`); + } } - } - return defaultDustFetcher(seed, network, opts); + return defaultDustFetcher(seed, network, opts, !settings.isDustCollapseOff); + }; } // ── Helpers ─────────────────────────────────────────────── @@ -713,21 +716,3 @@ function networkNameOf(network: NetworkConfig): NetworkName { if (isValidNetworkName(lower)) return lower; throw new Error(`Unsupported network: ${network.networkId}`); } - -// ── Process-wide singleton ──────────────────────────────── - -let defaultRepo: WalletDataRepository | null = null; - -/** - * Process-wide repository instance. Long-lived MCP sessions share this so - * the in-memory cache layer is meaningful across tool calls. - */ -export function defaultRepository(): WalletDataRepository { - if (!defaultRepo) defaultRepo = new WalletDataRepository(); - return defaultRepo; -} - -/** Test/diagnostic: replace the process singleton (e.g. with different fetchers). */ -export function setDefaultRepository(repo: WalletDataRepository | null): void { - defaultRepo = repo; -} diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index 70f689f3..356c2547 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -29,18 +29,18 @@ import { ensureDust, executeTransfer } from './transfer.ts'; import { airdropNight } from './airdrop.ts'; import { registerDust } from './dust-register.ts'; import { exportDustSnapshot } from './dust-export.ts'; -import { defaultRepository } from './wallet-data-repository.ts'; +import type { WalletDataRepository } from './wallet-data-repository.ts'; import { createDAppConnector } from './dapp-connector.ts'; const HOUR_MS = 60 * 60 * 1000; -async function shieldedTransfer(params: ShieldedTransferParams): Promise { +async function shieldedTransfer(repo: WalletDataRepository, params: ShieldedTransferParams): Promise { const { seed, root, notice, network, networkConfig, amount, progress, signal } = params; const networkId = getNetworkId(networkConfig.networkId); const nightToken = ledger.unshieldedToken().raw; const receiverAddress = decodeShieldedAddress(params.recipient, network); - return defaultRepository().withFacade( + return repo.withFacade( seed, networkConfig, async ({ bundle, state }) => { @@ -177,7 +177,7 @@ async function prepDust(wallet: PrepWallet, waitMs: number): Promise<{ alreadyAv } } -const openConnector: EngineWallet['openConnector'] = async (options): Promise => { +async function openConnector(repo: WalletDataRepository, options: Parameters[0]): Promise { const { seed, root, notice, network, networkConfig, address, syncMode, signal, onMessage } = options; // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig, undefined, signal); @@ -193,7 +193,6 @@ const openConnector: EngineWallet['openConnector'] = async (options): Promise { +function serveWallet(repo: WalletDataRepository, options: Parameters[0], serve: (session: ServedWalletSession) => Promise): Promise { const { seed, root, notice, networkConfig, network, address, syncMode } = options; // The repository owns validating the caches, priming Dust, building the // facade, syncing (with retries) and stopping it. Its save is skipped: mn // serve saves only when no transaction is pending, since the SDK drops // pending Dust on serialization and would persist dust=0. - return defaultRepository().withFacade(seed, networkConfig, async ({ bundle }) => { + return repo.withFacade(seed, networkConfig, async ({ bundle }) => { let lastState: Awaited> | undefined; const session: ServedWalletSession = { async waitForDust() { @@ -305,21 +304,24 @@ const serveWallet: EngineWallet['serveWallet'] = (options, serve) => { onSyncProgress: options.onSyncProgress, onSyncDetail: options.onSyncDetail, }); -}; +} -export const rcWallet: EngineWallet = { - unshieldedBalance: (address, networkConfig, options) => defaultRepository().unshielded(address, networkConfig, options), - async dustBalance(seed, networkConfig, options) { - const { state: _state, ...balance } = await defaultRepository().dust(seed, networkConfig, options); - return balance; - }, - transfer: executeTransfer, - airdrop: airdropNight, - shieldedTransfer, - registerDust, - exportDust: (seed, network, networkConfig, options) => exportDustSnapshot(seed, network, networkConfig, options), - prepNightBalance, - prepDust, - openConnector, - serveWallet, -}; +/** The wallet of an engine whose repository (its caches) is `repo`. */ +export function createRcWallet(repo: WalletDataRepository): EngineWallet { + return { + unshieldedBalance: (address, networkConfig, options) => repo.unshielded(address, networkConfig, options), + async dustBalance(seed, networkConfig, options) { + const { state: _state, ...balance } = await repo.dust(seed, networkConfig, options); + return balance; + }, + transfer: (params) => executeTransfer(repo, params), + airdrop: (params) => airdropNight(repo, params), + shieldedTransfer: (params) => shieldedTransfer(repo, params), + registerDust: (seed, networkConfig, options) => registerDust(repo, seed, networkConfig, options), + exportDust: (seed, network, networkConfig, options) => exportDustSnapshot(seed, network, networkConfig, { ...options, repository: repo }), + prepNightBalance, + prepDust, + openConnector: (options) => openConnector(repo, options), + serveWallet: (options, serve) => serveWallet(repo, options, serve), + }; +} diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index cc2a7384..546a3737 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -83,16 +83,10 @@ export const ALLOWED = { // why. A call's state is allowed only until it moves into the call's context; what is shared on purpose holds no call's state. export const ALLOWED_STATE = { // Shared on purpose: none holds a call's state. - 'engine/rc/wallet-data-repository.ts': { defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls' }, - 'engine/beta/wallet-data-repository.ts': { - defaultRepo: 'shared on purpose: the wallet repository, whose cache long-lived MCP sessions share across calls', - saidWasmDust: 'shared on purpose: the WASM Dust notice is said once per process', - }, 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/engine.ts': { - loaded: 'shared on purpose: the one SDK engine this process loads (two WASM ledgers cannot share a process)', - loader: 'shared on purpose: the host sets the engine loader once', - preferred: 'shared on purpose: the set work every set does alike loads while no engine is loaded, the set of the call it runs for', + loadedSet: 'shared on purpose: the SDK set this process loads, whichever host loads it (two WASM ledgers cannot share a process)', + bridged: "temporary until slice 6: the shell's host's engines, for the libraries that don't take their host's engines yet", }, // The host source, set once by the host at start (handlers see it through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 0c6afcbe..31a228d6 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -236,11 +236,12 @@ try { } } writeFileSync(join(outside, 'load.mjs'), ` - import { engineFor, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; - import { setHostPathsSource } from '@kuiralabs/midnight-cli-core/lib/state-root'; - setHostPathsSource(() => ({ stateRoot: ${JSON.stringify(join(outside, 'state'))}, home: ${JSON.stringify(outside)} })); - setEngineLoader(async (set) => set === 'beta' ? (await import('@kuiralabs/midnight-engine-beta')).betaEngine : (await import('@kuiralabs/midnight-engine-rc')).rcEngine); - try { console.log((await engineFor(process.argv[2])).set); } catch (error) { console.log(error.code ?? error.message); } + import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + const host = createHost({ + paths: { stateRoot: ${JSON.stringify(join(outside, 'state'))}, home: ${JSON.stringify(outside)} }, + engineLoader: async (set, host) => set === 'beta' ? (await import('@kuiralabs/midnight-engine-beta')).createBetaEngine(host) : (await import('@kuiralabs/midnight-engine-rc')).createRcEngine(host), + }); + try { console.log((await host.engines.for(process.argv[2])).set); } catch (error) { console.log(error.code ?? error.message); } `); for (const [network, set] of [['undeployed', 'rc'], ['stagenet', 'beta']]) { const loaded = run(process.execPath, ['load.mjs', network], outside).trim(); diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index e2be42e7..53e5f5e4 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -7,7 +7,7 @@ // passphrase it was made with. import * as fs from 'node:fs'; -import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -24,6 +24,9 @@ import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStat import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +// An rc engine, for what every host's has alike: its keys, ledger and contracts. +const rcEngine = createRcEngine(createHost()); + // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/contract-runtime-check.test.ts b/src/__tests__/contract-runtime-check.test.ts index 1205f485..5af7698e 100644 --- a/src/__tests__/contract-runtime-check.test.ts +++ b/src/__tests__/contract-runtime-check.test.ts @@ -7,10 +7,14 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { runDeploy } from '../lib/contract/runner.ts'; +// An rc engine, for what every host's has alike: its keys, ledger and contracts. +const rcEngine = createRcEngine(createHost()); + const contract = (runtimeVersion: string, compilerVersion = '0.30.0') => ({ name: 'counter', compilerVersion, runtimeVersion }); // A state root with no config: undeployed on the set the table names. const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-runtime-check-root-')); diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index 38229a9a..4b1fefd7 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -22,9 +22,13 @@ import { } from '../lib/contract/runner.ts'; import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; import { SCRIPT_PACKAGES, packageFolder } from '@kuiralabs/midnight-engine-rc/contract-scripts'; -import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; +// An rc engine, for what every host's has alike: its keys, ledger and contracts. +const rcEngine = createRcEngine(createHost()); + // The rc engine's scripts, with the parts the runner gives every engine. const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); diff --git a/src/__tests__/dust-export.test.ts b/src/__tests__/dust-export.test.ts index 69d7b78e..410ab832 100644 --- a/src/__tests__/dust-export.test.ts +++ b/src/__tests__/dust-export.test.ts @@ -98,6 +98,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { exportDustSnapshot } from '@kuiralabs/midnight-engine-rc/dust-export'; import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; +import { testHost } from './helpers/test-host.ts'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { DustDirectResult } from '@kuiralabs/midnight-engine-rc/dust-direct'; @@ -123,7 +124,7 @@ function fakeDust(state: ledger.DustLocalState, over: Partial } function fakeRepo(result: DustDirectResult): WalletDataRepository { - return new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + return new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchChainId: async () => null, // skip the node RPC (offline) diff --git a/src/__tests__/dust-sync-native.test.ts b/src/__tests__/dust-sync-native.test.ts index c2d68df4..443c043e 100644 --- a/src/__tests__/dust-sync-native.test.ts +++ b/src/__tests__/dust-sync-native.test.ts @@ -12,6 +12,10 @@ import { type SidecarCheckpoint, } from '@kuiralabs/midnight-engine-rc/dust-sync-native'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; + +// The settings a host reading the environment gives its engine: what each test sets there. +const envSettings = () => settingsFromEnvironment(process.env); describe('resumeDecision (kill-safe resume)', () => { it('resumes from an existing checkpoint that already reaches the cursor', () => { @@ -54,7 +58,7 @@ describe('adaptResult (sidecar checkpoint → DustDirectResult)', () => { // depends on time; read it at the state's own sync time. vi.useFakeTimers({ now: new Date('2026-10-05T06:14:30.000Z') }); let r: ReturnType; - try { r = adaptResult(cpFor(DUST_STATE_OWNED_HEX)); } finally { vi.useRealTimers(); } + try { r = adaptResult(cpFor(DUST_STATE_OWNED_HEX), envSettings()); } finally { vi.useRealTimers(); } expect(r.balance).toBe(1_436_566_695_496_744n); expect(r.availableCoins).toBe(1); expect(r.ownedUtxoCount).toBe(1); @@ -72,7 +76,7 @@ describe('adaptResult (sidecar checkpoint → DustDirectResult)', () => { it('maps an empty state to a zero balance', () => { const empty = new ledger.DustLocalState(new ledger.DustParameters(5_000_000_000n, 8_267n, 10_800n)); const hex = Buffer.from(empty.serialize()).toString('hex'); - const r = adaptResult(cpFor(hex, { partial: true, last_applied_event_id: -1 })); + const r = adaptResult(cpFor(hex, { partial: true, last_applied_event_id: -1 }), envSettings()); expect(r.balance).toBe(0n); expect(r.availableCoins).toBe(0); expect(r.partial).toBe(true); @@ -95,14 +99,14 @@ describe('binary resolution + gating', () => { const bin = join(dir, 'dust-sync'); writeFileSync(bin, '#!/bin/sh\n'); process.env.MN_DUST_SYNC_BIN = bin; - expect(resolveSidecarBinary()).toBe(bin); + expect(resolveSidecarBinary(envSettings())).toBe(bin); } finally { rmSync(dir, { recursive: true, force: true }); } }); it('ignores a non-existent override path', () => { process.env.MN_DUST_SYNC_BIN = '/no/such/dust-sync-binary'; // Falls through to the dev build or null — never returns the bad override. - expect(resolveSidecarBinary()).not.toBe('/no/such/dust-sync-binary'); + expect(resolveSidecarBinary(envSettings())).not.toBe('/no/such/dust-sync-binary'); }); it('never selects the ledger-8 sidecar on this ledger-9 build, even with a resolvable binary', () => { @@ -112,8 +116,8 @@ describe('binary resolution + gating', () => { writeFileSync(bin, '#!/bin/sh\n'); process.env.MN_DUST_SYNC_BIN = bin; delete process.env.MN_DISABLE_NATIVE_DUST; - expect(resolveSidecarBinary()).toBe(bin); - expect(nativeDustSyncAvailable()).toBe(false); + expect(resolveSidecarBinary(envSettings())).toBe(bin); + expect(nativeDustSyncAvailable(envSettings())).toBe(false); } finally { rmSync(dir, { recursive: true, force: true }); } }); @@ -124,7 +128,7 @@ describe('binary resolution + gating', () => { writeFileSync(bin, '#!/bin/sh\n'); process.env.MN_DUST_SYNC_BIN = bin; process.env.MN_DISABLE_NATIVE_DUST = '1'; - expect(nativeDustSyncAvailable()).toBe(false); // gated off despite a resolvable binary + expect(nativeDustSyncAvailable(envSettings())).toBe(false); // gated off despite a resolvable binary } finally { rmSync(dir, { recursive: true, force: true }); } }); }); @@ -164,7 +168,7 @@ describe('runDustSyncNative exit handling (fake sidecar binary)', () => { it('accepts the checkpoint from a clean exit (control: the fake binary works)', async () => { fakeSidecar(0); - const r = await runDustSyncNative(seed, network, { root: join(dir, '.midnight'), startFromId: 0 }); + const r = await runDustSyncNative(seed, network, { root: join(dir, '.midnight'), startFromId: 0, settings: envSettings() }); expect(r.lastAppliedEventId).toBe(7); }); @@ -172,7 +176,7 @@ describe('runDustSyncNative exit handling (fake sidecar binary)', () => { // A ledger-8 sidecar on a ledger-9 chain dies like this (exit 2) after a // checkpoint already sits at --out; parsing it as success froze dust. fakeSidecar(2); - await expect(runDustSyncNative(seed, network, { root: join(dir, '.midnight'), startFromId: 0 })).rejects.toThrow('dust-sync exited 2'); + await expect(runDustSyncNative(seed, network, { root: join(dir, '.midnight'), startFromId: 0, settings: envSettings() })).rejects.toThrow('dust-sync exited 2'); }); }); @@ -209,10 +213,8 @@ describe('adaptResult — native-path generation-tree collapse', () => { const hex = Buffer.from(stateWithForeignLeaves(8, 3).serialize()).toString('hex'); const cp = cpFor(hex, { owned_generation_indices: [3], generation_frontier: 8 }); - const on = adaptResult(cp); - process.env.MN_DISABLE_DUST_COLLAPSE = '1'; - let off: ReturnType; - try { off = adaptResult(cp); } finally { delete process.env.MN_DISABLE_DUST_COLLAPSE; } + const on = adaptResult(cp, { isDustCollapseOff: false }); + const off = adaptResult(cp, { isDustCollapseOff: true }); expect(on.balance).toBe(off.balance); // collapse never moves the balance expect(on.retention.ownedGenerationIndices).toEqual([3]); // owned indices pass through diff --git a/src/__tests__/engine-beta-host.test.ts b/src/__tests__/engine-beta-host.test.ts new file mode 100644 index 00000000..f9a86511 --- /dev/null +++ b/src/__tests__/engine-beta-host.test.ts @@ -0,0 +1,73 @@ +// Hosts on the beta set, in a process of its own: the set a call's network +// runs loads first, each host's beta engine tells its own host that it reads +// Dust in WASM (once per engine), and the process then refuses the rc set to +// any host. + +import { afterAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { OtherSdkSetError, type SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; +import type { RepoDeps } from '@kuiralabs/midnight-engine-beta/wallet-data-repository'; +import { startRefusingEndpoint } from './helpers/stand-in-indexer.ts'; + +// A state root with no config: stagenet runs the beta set, the rest the rc set. +const ROOT = mkdtempSync(join(tmpdir(), 'mn-engine-beta-host-')); +afterAll(() => rmSync(ROOT, { recursive: true, force: true })); + +// The chain answers as a ledger-9 one with no genesis hash; the indexer refuses every connection. +const deps: RepoDeps = { fetchProtocolVersion: async () => 2001000n, fetchChainId: async () => null }; +const asked: SdkSet[] = []; +const loader = async (set: SdkSet, host: Host) => { asked.push(set); return createBetaEngine(host, { repository: deps }); }; +const hostWith = (notices: string[]) => createHost({ paths: { stateRoot: ROOT, home: ROOT }, notice: (line) => notices.push(line), engineLoader: loader }); + +describe('hosts on the beta set', () => { + // First in this file: nothing in the process has loaded a set yet. + it('load the set of the call\'s network for work every set does alike', async () => { + const host = hostWith([]); + host.engines.prefer('stagenet'); + expect((await host.engines.any()).set).toBe('beta'); + expect(asked).toStrictEqual(['beta']); + }); + + it('each tell their own host, once per engine, that the engine reads Dust in WASM', async () => { + const indexer = await startRefusingEndpoint(); + const root = mkdtempSync(join(tmpdir(), 'mn-engine-beta-dust-')); + try { + const network: NetworkConfig = { + indexer: 'http://test/indexer', + indexerWS: `ws://127.0.0.1:${indexer.port}/api/v4/graphql/ws`, + node: 'ws://test/node', + proofServer: 'http://test/proof', + networkId: 'StageNet', + }; + const toA: string[] = []; + const toB: string[] = []; + const toCalls: string[] = []; + const a = await hostWith(toA).engines.for('stagenet'); + const b = await hostWith(toB).engines.for('stagenet'); + const read = (engine: typeof a, seed: number) => engine.wallet.dustBalance(Buffer.alloc(32, seed), network, { root, notice: (line) => toCalls.push(line) }); + + await expect(read(a, 1)).rejects.toThrow(); + await expect(read(a, 2)).rejects.toThrow(); + expect(toA).toStrictEqual([" Reading StageNet's Dust history in WASM: no native sidecar runs ledger 9 yet, so a first sync takes a few minutes (about 2.5 on stagenet), then it is cached."]); + expect(toB).toStrictEqual([]); + + await expect(read(b, 1)).rejects.toThrow(); + expect(toB).toStrictEqual(toA); + expect(toCalls).toStrictEqual([]); + } finally { + rmSync(root, { recursive: true, force: true }); + await indexer.close(); + } + }); + + it('leave the process refusing the rc set to a new host', async () => { + const refusal = await hostWith([]).engines.for('undeployed').catch((err: unknown) => err); + expect(refusal).toBeInstanceOf(OtherSdkSetError); + expect(refusal).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'beta', wantedSet: 'rc' }); + }); +}); diff --git a/src/__tests__/engine-beta.test.ts b/src/__tests__/engine-beta.test.ts index 7be86fb8..ea22b153 100644 --- a/src/__tests__/engine-beta.test.ts +++ b/src/__tests__/engine-beta.test.ts @@ -5,7 +5,8 @@ import { describe, it, expect, vi } from 'vitest'; import * as rx from 'rxjs'; -import { betaEngine } from '@kuiralabs/midnight-engine-beta'; +import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { createDAppConnector } from '@kuiralabs/midnight-engine-beta/dapp-connector'; import type { FacadeBundle } from '@kuiralabs/midnight-engine-beta/facade'; import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-beta/derive-address'; @@ -13,6 +14,9 @@ import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; import { NO_TERMINAL } from './helpers/connector-stub.ts'; +// A beta engine, for what every host's has alike: its keys, ledger and contracts. +const betaEngine = createBetaEngine(createHost()); + // The beta set's own address classes, as the engine resolves them: the // repository's root holds the rc set's. const { DustAddress, UnshieldedAddress } = await import(new URL('../../packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-address-format/dist/index.js', import.meta.url).href) as typeof import('@midnightntwrk/wallet-sdk-address-format'); diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index ecc27b08..b7b40b81 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -1,43 +1,69 @@ -// The engine for a network: one per process, loaded on first use, and the -// same for work every set does alike. +// A host's engine for a network: one per host, loaded on first use, and the +// same for work every set does alike. Each host's engine keeps its own +// repository and reads its own host's settings; the process runs one SDK set, +// whichever host loaded it. import { afterAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { OtherSdkSetError, anyEngine, engineFor, preferEngineOf, sdkSetOf, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { OtherSdkSetError, sdkSetOf, type Engine, type SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { getValidNetworkNames, sdkSetOfNetwork, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import type { RepoDeps } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import { getValidNetworkNames, sdkSetOfNetwork, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +import { startRefusingEndpoint } from './helpers/stand-in-indexer.ts'; // A state root with no config: every network on the set the table names. const ROOT = mkdtempSync(join(tmpdir(), 'mn-engine-test-')); afterAll(() => rmSync(ROOT, { recursive: true, force: true })); -describe('the engine for a network', () => { +/** A host on ROOT whose engines come from `engineLoader` (the engines the CLI ships by default). */ +const hostOn = (engineLoader: (set: SdkSet, host: Host) => Promise = loadInstalledEngine, notice?: (line: string) => void) => + createHost({ paths: { stateRoot: ROOT, home: ROOT }, engineLoader, ...(notice ? { notice } : {}) }); + +describe('a host\'s engine for a network', () => { it('is the rc engine for every network but stagenet, which runs the beta set', async () => { + const host = hostOn(); + const engine = await host.engines.for('undeployed'); + expect(engine.set).toBe('rc'); for (const network of getValidNetworkNames() as NetworkName[]) { if (network === 'stagenet') continue; expect(sdkSetOf(network, ROOT)).toBe('rc'); - expect(await engineFor(network, ROOT)).toBe(rcEngine); + expect(await host.engines.for(network)).toBe(engine); } expect(sdkSetOf('stagenet', ROOT)).toBe('beta'); }); - it('refuses stagenet in a process that has loaded the rc engine, naming both sets', async () => { - await engineFor('undeployed', ROOT); - const refusal = await engineFor('stagenet', ROOT).catch((err: unknown) => err); + it('refuses stagenet in a host that has loaded the rc engine, naming both sets', async () => { + const host = hostOn(); + await host.engines.for('undeployed'); + const refusal = await host.engines.for('stagenet').catch((err: unknown) => err); + expect(refusal).toBeInstanceOf(OtherSdkSetError); + expect(refusal).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'rc', wantedSet: 'beta' }); + }); + + it('refuses the other set to a new host once the process has loaded one, without asking its loader', async () => { + await hostOn().engines.for('undeployed'); + const asked: SdkSet[] = []; + const fresh = hostOn(async (set, host) => { asked.push(set); return createRcEngine(host); }); + const refusal = await fresh.engines.for('stagenet').catch((err: unknown) => err); expect(refusal).toBeInstanceOf(OtherSdkSetError); expect(refusal).toMatchObject({ code: 'OTHER_SDK_SET', loadedSet: 'rc', wantedSet: 'beta' }); + expect(asked).toStrictEqual([]); }); - it('is the one loaded in this process for work every set does alike', async () => { - expect(await anyEngine()).toBe(await engineFor('undeployed', ROOT)); + it('is the one the host has loaded for work every set does alike', async () => { + const host = hostOn(); + expect(await host.engines.any()).toBe(await host.engines.for('undeployed')); }); it('derives a wallet\'s addresses on every network, matching one network at a time', async () => { const seed = Buffer.from('ab'.repeat(32), 'hex'); - const { keys } = await anyEngine(); + const { keys } = await hostOn().engines.any(); const unshielded = keys.unshieldedAddresses(seed); const shielded = keys.shieldedAddresses(seed); for (const network of getValidNetworkNames() as NetworkName[]) { @@ -47,44 +73,77 @@ describe('the engine for a network', () => { expect(shielded[network]).toMatch(new RegExp(`^mn_shield-addr_${network}1`)); } }); + + it('refuses without an engine loader, naming the option', async () => { + const host = createHost({ paths: { stateRoot: ROOT, home: ROOT } }); + await expect(host.engines.for('undeployed')).rejects.toThrow("createHost's engineLoader"); + }); }); describe('the network picks the engine', () => { - it('asks the host\'s loader for the set the network table names, once a process', async () => { - const asked: string[] = []; - setEngineLoader(async (set) => { asked.push(set); return rcEngine; }); - try { - expect(await engineFor('preview', ROOT)).toBe(rcEngine); - expect(await engineFor('undeployed', ROOT)).toBe(rcEngine); - expect(asked).toStrictEqual(['rc']); - for (const network of getValidNetworkNames() as NetworkName[]) expect(sdkSetOf(network, ROOT)).toBe(sdkSetOfNetwork(network, ROOT)); - } finally { - setEngineLoader(loadInstalledEngine); - } + it('asks the host\'s loader for the set the network table names, once a host', async () => { + const asked: SdkSet[] = []; + const host = hostOn(async (set, h) => { asked.push(set); return createRcEngine(h); }); + const engine = await host.engines.for('preview'); + expect(await host.engines.for('undeployed')).toBe(engine); + expect(asked).toStrictEqual(['rc']); + for (const network of getValidNetworkNames() as NetworkName[]) expect(sdkSetOf(network, ROOT)).toBe(sdkSetOfNetwork(network, ROOT)); }); - it('loads the set of the call\'s network for work every set does alike, before any engine is loaded', async () => { - const asked: string[] = []; - const beta = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; - setEngineLoader(async (set) => { asked.push(set); return set === 'beta' ? beta : rcEngine; }); - try { - preferEngineOf('stagenet', ROOT); - expect(await anyEngine()).toBe(beta); - expect(asked).toStrictEqual(['beta']); - } finally { - preferEngineOf('undeployed', ROOT); - setEngineLoader(loadInstalledEngine); - } + it('refuses an engine of a set other than the one asked for', async () => { + const host = hostOn(async (_set, h) => ({ ...createRcEngine(h), set: 'beta' })); + await expect(host.engines.for('undeployed')).rejects.toThrow("This process runs the beta SDK set and can't load the rc one"); + }); +}); + +// The chain and the indexer stand in at the repository's seams; the rest is the engine's own. +const NETWORK: NetworkConfig = { + indexer: 'http://test/indexer', + indexerWS: 'ws://test/indexer/ws', + node: 'ws://test/node', + proofServer: 'http://test/proof', + networkId: 'Undeployed', +}; +const ADDRESS = 'mn_addr_undeployed1ugtvumxjrspvh598y6agtw3sdk06qf8sl0x0pfu6lf2080wrnprsdj8xxx'; +const summary = (): BalanceSummary => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }); + +describe('each host\'s engine', () => { + it('is an instance of its own, with a repository of its own: a read cached in one host is fetched again in the other', async () => { + const fetched: string[] = []; + const deps: RepoDeps = { + fetchTip: async () => 'tip-1', + fetchUnshielded: async (address) => { fetched.push(address); return summary(); }, + }; + const loader = async (_set: SdkSet, h: Host) => createRcEngine(h, { repository: deps }); + const a = await hostOn(loader).engines.for('undeployed'); + const b = await hostOn(loader).engines.for('undeployed'); + expect(a).not.toBe(b); + expect(a.wallet).not.toBe(b.wallet); + + expect((await a.wallet.unshieldedBalance(ADDRESS, NETWORK)).fromCache).toBe(false); + expect((await a.wallet.unshieldedBalance(ADDRESS, NETWORK)).fromCache).toBe(true); + expect((await b.wallet.unshieldedBalance(ADDRESS, NETWORK)).fromCache).toBe(false); + expect(fetched).toStrictEqual([ADDRESS, ADDRESS]); }); - it('refuses a second set in a process that has loaded one', async () => { - const other = { ...rcEngine, set: 'beta' } as unknown as typeof rcEngine; - setEngineLoader(async () => other); + it('reads its own host\'s settings when it reads Dust, never another host\'s', async () => { + const indexer = await startRefusingEndpoint(); + const root = mkdtempSync(join(tmpdir(), 'mn-engine-dust-')); try { - await expect(engineFor('undeployed', ROOT)).rejects.toThrow("This process runs the beta SDK set and can't load the rc one"); + const reads: string[] = []; + const settingsOf = (name: string) => () => { reads.push(name); return settingsFromEnvironment({ MN_DISABLE_DUST_COLLAPSE: '1' }); }; + const deps: RepoDeps = { fetchProtocolVersion: async () => 2001000n, fetchChainId: async () => null }; + const loader = async (_set: SdkSet, h: Host) => createRcEngine(h, { repository: deps }); + const a = await createHost({ paths: { stateRoot: ROOT, home: ROOT }, settings: settingsOf('A'), engineLoader: loader }).engines.for('undeployed'); + await createHost({ paths: { stateRoot: ROOT, home: ROOT }, settings: settingsOf('B'), engineLoader: loader }).engines.for('undeployed'); + + const network = { ...NETWORK, indexerWS: `ws://127.0.0.1:${indexer.port}/api/v4/graphql/ws` }; + await expect(a.wallet.dustBalance(Buffer.alloc(32, 3), network, { root, notice: () => {} })).rejects.toThrow(); + expect(reads.length).toBeGreaterThan(0); + expect(new Set(reads)).toStrictEqual(new Set(['A'])); } finally { - setEngineLoader(loadInstalledEngine); + rmSync(root, { recursive: true, force: true }); + await indexer.close(); } }); - }); diff --git a/src/__tests__/fixtures/record-swap-offer.ts b/src/__tests__/fixtures/record-swap-offer.ts index 07fe2641..618a46ad 100644 --- a/src/__tests__/fixtures/record-swap-offer.ts +++ b/src/__tests__/fixtures/record-swap-offer.ts @@ -14,7 +14,7 @@ import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { engineFor, setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { loadInstalledEngine } from '../../lib/installed-engines.ts'; @@ -35,9 +35,9 @@ const networkConfig: NetworkConfig = { const home = mkdtempSync(join(tmpdir(), 'mn-record-offer-')); const root = join(home, '.midnight'); setSettingsSource(() => settingsFromEnvironment(process.env)); -setEngineLoader(loadInstalledEngine); +const host = createHost({ settings: () => settingsFromEnvironment(process.env), paths: { stateRoot: root, home }, engineLoader: loadInstalledEngine }); -const engine = await engineFor('undeployed', root); +const engine = await host.engines.for('undeployed'); const ctx = { notify: () => {}, connectionId: 'record', requestId: 1, metadata: {} }; const open = (seed: Buffer) => engine.wallet.openConnector({ seed, root, notice: () => {}, network: 'undeployed', networkConfig, address: engine.keys.unshieldedAddress(seed, 'undeployed'), syncMode: 'full', diff --git a/src/__tests__/helpers/shell-settings.ts b/src/__tests__/helpers/shell-settings.ts index f063cb7e..a8fa43da 100644 --- a/src/__tests__/helpers/shell-settings.ts +++ b/src/__tests__/helpers/shell-settings.ts @@ -1,12 +1,12 @@ // The test run stands in for the shell: libraries read the environment the -// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, and load the engines the -// CLI ships, as the CLI gives them. Where state is kept, each test says: its -// host's paths (test-host.ts), or the root it passes a library. +// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, and the libraries that +// don't take their host's engines yet reach the engines of a host made with +// the engines the CLI ships, as the CLI bridges them. Where state is kept, each +// test says: its host's paths (test-host.ts), or the root it passes a library. import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { loadInstalledEngine } from '../../lib/installed-engines.ts'; +import { bridgeEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { testHost } from './test-host.ts'; setSettingsSource(() => settingsFromEnvironment(process.env)); -// And the engines this build ships, as the CLI gives them. -setEngineLoader(loadInstalledEngine); +bridgeEngines(testHost().engines); diff --git a/src/__tests__/helpers/test-host.ts b/src/__tests__/helpers/test-host.ts index 6301cf51..5af6b6b4 100644 --- a/src/__tests__/helpers/test-host.ts +++ b/src/__tests__/helpers/test-host.ts @@ -1,18 +1,21 @@ // The host a test's calls run with: settings from the environment and the // state root under the home directory, each read when used (tests change HOME -// and the environment as they go), notices dropped, nobody to ask, and SDK -// warnings of its own (no host's filters report to it). +// and the environment as they go), notices dropped, nobody to ask, SDK +// warnings of its own (no host's filters report to it), and an engine of its +// own from the engines the CLI ships. import { homedir } from 'node:os'; import { join } from 'node:path'; import { createHost, type Host, type HostOptions } from '@kuiralabs/midnight-cli-core/lib/host'; import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { loadInstalledEngine } from '../../lib/installed-engines.ts'; export function testHost(overrides: HostOptions = {}): Host { return createHost({ settings: () => settingsFromEnvironment(process.env), paths: () => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() }), + engineLoader: loadInstalledEngine, ...overrides, }); } diff --git a/src/__tests__/read-cancellation.test.ts b/src/__tests__/read-cancellation.test.ts index a1b2f1d6..cc48cb86 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/src/__tests__/read-cancellation.test.ts @@ -18,6 +18,7 @@ import { waitForAddressFunded } from '@kuiralabs/midnight-chain/lib/indexer-read import { waitForProofServerReady } from '@kuiralabs/midnight-chain/lib/proof-server-ready'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; +import { testHost } from './helpers/test-host.ts'; import { getNetworkConfig, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; @@ -119,7 +120,7 @@ describe('the wallet data repository, cancelled while it checks a memoized read' const summary: BalanceSummary = { balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }; const call = new AbortController(); let tipChecks = 0; - const repo = new WalletDataRepository({ + const repo = new WalletDataRepository(testHost(), { now: () => clock, // The first check answers; the second waits until its call is cancelled, as a node that doesn't answer. fetchTip: (_network, signal) => { @@ -142,7 +143,7 @@ describe('the wallet data repository, cancelled while it checks a memoized read' it('passes the call\'s signal on to its unshielded fetch', async () => { const seen: Array = []; - const repo = new WalletDataRepository({ + const repo = new WalletDataRepository(testHost(), { fetchTip: async () => 'tip', fetchUnshielded: async (_address, _network, _onProgress, signal) => { seen.push(signal); diff --git a/src/__tests__/sealed-account.test.ts b/src/__tests__/sealed-account.test.ts index 7dd8d087..2d3f494a 100644 --- a/src/__tests__/sealed-account.test.ts +++ b/src/__tests__/sealed-account.test.ts @@ -7,7 +7,8 @@ // node:test as that suite is written. import { execFileSync } from 'node:child_process'; -import { rcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -26,6 +27,9 @@ import { sealedPrivateStatePassword, } from '../lib/grant/sealed-account.ts'; +// An rc engine, for what every host's has alike: its keys, ledger and contracts. +const rcEngine = createRcEngine(createHost()); + const PASSPHRASE = 'correct horse battery staple'; const RECORD = { contractAddress: 'ab'.repeat(32), bootSalt: 'ef'.repeat(32), encryptionSecret: '12'.repeat(32) }; const CONFORMANCE = fileURLToPath(new URL('./sealed-account.conformance.ts', import.meta.url)); diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 8baff4f0..d74e1ccb 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -73,7 +73,7 @@ describe('verbose, per call', () => { it("a library writes its diagnostics to the log of the call that reached it, and only a verbose call's shows them", async () => { const network: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', node: 'ws://test/node', proofServer: 'http://test/proof', networkId: 'Undeployed' }; // The chain's tip can't be read, which the repository notes as a diagnostic. - const repo = new WalletDataRepository({ + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: async () => 2001000n, fetchTip: async () => { throw new Error('node unreachable'); }, fetchUnshielded: async () => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }), diff --git a/src/__tests__/wallet-data-repository.test.ts b/src/__tests__/wallet-data-repository.test.ts index 1c9acfa1..160274d0 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/src/__tests__/wallet-data-repository.test.ts @@ -11,6 +11,7 @@ import { Buffer } from 'node:buffer'; import * as ledger from '@midnightntwrk/ledger-v9'; import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; +import { testHost } from './helpers/test-host.ts'; import { UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; @@ -73,7 +74,7 @@ afterEach(() => { rmSync(TMP, { recursive: true, force: true }); }); describe('WalletDataRepository — ledger guard', () => { it('refuses a ledger-8 chain before starting any dust sync', async () => { const fetchDust = vi.fn(async () => fakeDustResult()); - const repo = new WalletDataRepository({ + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: async () => 1000300n, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -88,7 +89,7 @@ describe('WalletDataRepository — ledger guard', () => { describe('WalletDataRepository — unshielded reads', () => { it('serves a memo hit when the chain tip has not changed', async () => { let tipCalls = 0, fetchCalls = 0; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => { tipCalls++; return 'tip-A'; }, fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary({ utxoCount: 3 }); }, @@ -108,7 +109,7 @@ describe('WalletDataRepository — unshielded reads', () => { it('refetches when the chain tip changes between calls', async () => { let tip = 'tip-A', fetchCalls = 0; let nowMs = 1_000_000; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => nowMs, fetchTip: async () => tip, fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary({ utxoCount: fetchCalls }); }, @@ -127,7 +128,7 @@ describe('WalletDataRepository — unshielded reads', () => { it('forceFresh bypasses the memo even when the tip is unchanged', async () => { let fetchCalls = 0; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => { fetchCalls++; return fakeBalanceSummary(); }, @@ -143,7 +144,7 @@ describe('WalletDataRepository — unshielded reads', () => { it('serves cached value when the tip-check itself fails (network down)', async () => { let fetchCalls = 0; let tipShouldFail = false; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => { if (tipShouldFail) throw new Error('ECONNREFUSED'); @@ -167,7 +168,7 @@ describe('WalletDataRepository — unshielded reads', () => { describe('WalletDataRepository — dust reads', () => { it('hits the in-memory memo on the second call within the same tip', async () => { let fetchCalls = 0; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -193,11 +194,11 @@ describe('WalletDataRepository — dust reads', () => { }, }); // Before the reset: the cache reaches event 500. - await new WalletDataRepository(deps(null, [], 500)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); + await new WalletDataRepository(testHost(), deps(null, [], 500)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); // After it: the chain's latest event is 106, so the cache can't be from this chain. const startIds: number[] = []; - const view = await new WalletDataRepository(deps(106, startIds, 106)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); + const view = await new WalletDataRepository(testHost(), deps(106, startIds, 106)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startIds).toEqual([0]); expect(view.fromCache).toBe(false); @@ -216,8 +217,8 @@ describe('WalletDataRepository — dust reads', () => { fetchEventTip: async () => eventTip, fetchDust: async (_seed, _net, opts) => { startIds.push(opts.startFromId); return fakeDustResult({ lastAppliedEventId: lastId }); }, }); - await new WalletDataRepository(deps(null, 100)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); - await new WalletDataRepository(deps(150, 150)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); + await new WalletDataRepository(testHost(), deps(null, 100)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); + await new WalletDataRepository(testHost(), deps(150, 150)).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(startIds).toEqual([0, 101]); }); @@ -227,7 +228,7 @@ describe('WalletDataRepository — dust reads', () => { // fakeDustResult with lastAppliedEventId advancing by 250 each time. const startIds: number[] = []; let nextLastEventId = 249; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -257,7 +258,7 @@ describe('WalletDataRepository — dust reads', () => { it('resumes through as many short windows as the sync needs, while each one moves', async () => { let calls = 0; let clock = 1_000_000; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => clock, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -278,7 +279,7 @@ describe('WalletDataRepository — dust reads', () => { it('gives up after three windows in a row that apply nothing, and says the state is short', async () => { let calls = 0; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -301,7 +302,7 @@ describe('WalletDataRepository — dust reads', () => { it('keeps a completed sync when the tip fetch fails at memo time', async () => { // The tip probe is an optimization. A cold dust sync is minutes of work that // is already on disk by this point; a node blip must not turn it into a throw. - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => { throw new Error('node unreachable'); }, fetchUnshielded: async () => fakeBalanceSummary(), @@ -314,7 +315,7 @@ describe('WalletDataRepository — dust reads', () => { }); it('reports partial: false and the synced offset once the resume loop reaches the tip', async () => { - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -335,7 +336,7 @@ describe('WalletDataRepository — dust reads', () => { let nextLastEventId = 249; // Each window takes ten minutes: the loop's hour is used up after six. let clock = 1_000_000; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => clock, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -372,12 +373,12 @@ describe('WalletDataRepository — dust reads', () => { fetchDust, }); - const cold = await new WalletDataRepository( + const cold = await new WalletDataRepository(testHost(), deps(async () => fakeDustResult({ lastAppliedEventId: 900, eventCount: 901 })), ).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(cold.lastAppliedEventId).toBe(900); - const warm = await new WalletDataRepository( + const warm = await new WalletDataRepository(testHost(), deps(async () => fakeDustResult({ lastAppliedEventId: -1, eventCount: 0 })), ).dust(SEED, NETWORK, { root: TMP, notice: dropNotice }); expect(warm.lastAppliedEventId).toBe(900); @@ -387,7 +388,7 @@ describe('WalletDataRepository — dust reads', () => { it('forceFresh on dust bypasses both memos and disk cache', async () => { let fetchCalls = 0; let lastStartFromId = -999; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), @@ -409,7 +410,7 @@ describe('WalletDataRepository — dust reads', () => { describe('WalletDataRepository — invalidation', () => { it('invalidate() drops the dust + unshielded memo entries for the given seed/network', async () => { let dustCalls = 0, unshieldedCalls = 0; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => { unshieldedCalls++; return fakeBalanceSummary(); }, @@ -431,7 +432,7 @@ describe('WalletDataRepository — invalidation', () => { it('invalidate() with kinds: ["dust"] leaves the unshielded memo intact', async () => { let dustCalls = 0, unshieldedCalls = 0; - const repo = new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + const repo = new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, now: () => 1_000_000, fetchTip: async () => 'tip-A', fetchUnshielded: async () => { unshieldedCalls++; return fakeBalanceSummary(); }, @@ -475,7 +476,7 @@ function readDustCacheFile(): { chainId?: string; lastAppliedEventId?: number } describe('WalletDataRepository — dust cache chain-reset guard', () => { const mkRepo = (chainId: string, fetchDust: NonNullable) => - new WalletDataRepository({ fetchProtocolVersion: LEDGER9_PROTOCOL, + new WalletDataRepository(testHost(), { fetchProtocolVersion: LEDGER9_PROTOCOL, fetchTip: async () => 'tip-A', fetchUnshielded: async () => fakeBalanceSummary(), fetchDust, diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index 5c35ea50..2a506bbf 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -39,7 +39,7 @@ describe('walletStateToRestore', () => { const checkpoint = ledger.DustLocalState.deserialize(Buffer.from(DUST_STATE_OWNED_HEX, 'hex')); saveDustCache('undeployed', dustPublicKeyHexFromSeed(SEED), checkpoint, 395_185, root); - const state = await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root, () => {}); + const state = await new WalletDataRepository(testHost()).walletStateToRestore(SEED, NETWORK, 'undeployed', root, () => {}); expect(state, 'a wallet to restore, not one built from its keys').not.toBeNull(); const dust = JSON.parse(state!.dust) as { offset: string; state: string }; @@ -48,6 +48,6 @@ describe('walletStateToRestore', () => { }, 30_000); it('with no saved wallet and no checkpoint, is null: the wallet is built from its keys', async () => { - expect(await new WalletDataRepository().walletStateToRestore(SEED, NETWORK, 'undeployed', root, () => {})).toBeNull(); + expect(await new WalletDataRepository(testHost()).walletStateToRestore(SEED, NETWORK, 'undeployed', root, () => {})).toBeNull(); }); }); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index ae186984..d0e8e1c0 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -6,7 +6,7 @@ // - a notice sink: stderr; // - settings, read from the environment as each is needed; // - the state root, ~/.midnight, read as each path is built; -// - the SDK engines this build ships. +// - the SDK engines this build ships, as its engine loader. // The prompter is the CLI's alone: the MCP server has no terminal to ask at. import { homedir } from 'node:os'; @@ -15,7 +15,7 @@ import { installSdkNoiseFilters } from './sdk-noise.ts'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { setEngineLoader } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { bridgeEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from './installed-engines.ts'; @@ -31,8 +31,10 @@ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host notice: (line) => process.stderr.write(line + '\n'), prompter, sdkWarnings: installSdkNoiseFilters(), + engineLoader: loadInstalledEngine, }); setSettingsSource(host.settings); - setEngineLoader(loadInstalledEngine); + // The libraries that don't take the host's engines yet reach these, so the process has one engine. + bridgeEngines(host.engines); return host; } diff --git a/src/lib/installed-engines.ts b/src/lib/installed-engines.ts index d3644d7b..5cf43812 100644 --- a/src/lib/installed-engines.ts +++ b/src/lib/installed-engines.ts @@ -1,15 +1,16 @@ // A shell concern: the SDK engines this build of mn ships, which the host -// gives the libraries as their engine loader. Each loads its SDK, so each is +// makes its engine with (its engine loader). Each loads its SDK, so each is // imported only when a call needs it. import type { Engine, SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -/** The engine for an SDK set, as this build ships it. */ -export async function loadInstalledEngine(set: SdkSet): Promise { +/** The engine for an SDK set, as this build ships it, made for `host`. */ +export async function loadInstalledEngine(set: SdkSet, host: Host): Promise { switch (set) { case 'rc': - return (await import('@kuiralabs/midnight-engine-rc')).rcEngine; + return (await import('@kuiralabs/midnight-engine-rc')).createRcEngine(host); case 'beta': - return (await import('@kuiralabs/midnight-engine-beta')).betaEngine; + return (await import('@kuiralabs/midnight-engine-beta')).createBetaEngine(host); } } From c26e1df46661b6bd32374a6770aa36224b1c24ac Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 04:43:12 -0800 Subject: [PATCH 60/88] Every caller gets its engine from its host (3B, 6 of 7) Commands load their engine through ctx.host.engines; libraries take a resolved engine where they always use one, and the host's engines where they use one only sometimes, so the SDK loads no earlier than before (wallet list still loads none for sealed wallets). The temporary bridge and its module state go; 3 module states are left (the chain-id memo, the SDK-set guard, settings). A new test runs two hosts on one state root: a wallet check and a wallet listing through host B use B's engine and repository only. Behaviour snapshot unchanged; suite 2575, beta 171; fresh install loads both engines; scratch chain swap 30/30, MCP swap 12/12, tx 25/25; stagenet (beta) balance and Dust status read. --- packages/cli-core/api-report.md | 6 +- packages/cli-core/src/lib/engine.ts | 25 ----- packages/cli-core/src/lib/wallet-session.ts | 12 ++- scripts/check-process-safety.mjs | 1 - src/__tests__/account-backup.test.ts | 19 ++-- src/__tests__/command-cancellation.test.ts | 6 +- src/__tests__/contract-runner.test.ts | 3 +- src/__tests__/contract-runtime-check.test.ts | 11 ++- src/__tests__/grant-account.test.ts | 5 +- src/__tests__/helpers/shell-settings.ts | 10 +- src/__tests__/host-engines.test.ts | 98 ++++++++++++++++++++ src/__tests__/host-paths.test.ts | 11 ++- src/__tests__/host-slots.test.ts | 5 +- src/__tests__/multi-wallet.test.ts | 11 ++- src/__tests__/network-cancellation.test.ts | 6 +- src/__tests__/notices.test.ts | 5 +- src/__tests__/protect-account.test.ts | 21 +++-- src/__tests__/sealed-wallet.test.ts | 19 ++-- src/__tests__/seed-resolver.test.ts | 5 +- src/__tests__/serve-manager.test.ts | 5 +- src/__tests__/state-root.test.ts | 4 +- src/__tests__/swap-request.test.ts | 5 +- src/__tests__/transfer-request.test.ts | 5 +- src/__tests__/wallet-config.test.ts | 31 ++++--- src/__tests__/wallet-create.test.ts | 17 ++-- src/__tests__/wallet-protect.test.ts | 5 +- src/commands/address.ts | 3 +- src/commands/airdrop.ts | 14 +-- src/commands/balance.ts | 9 +- src/commands/cache.ts | 3 +- src/commands/contract.definition.ts | 15 +-- src/commands/contract.ts | 9 +- src/commands/dust.ts | 7 +- src/commands/generate.ts | 3 +- src/commands/genesis-address.ts | 3 +- src/commands/grant.definition.ts | 2 +- src/commands/grant.ts | 4 +- src/commands/info.ts | 2 +- src/commands/inspect-cost.ts | 3 +- src/commands/localnet.ts | 3 +- src/commands/serve.ts | 4 +- src/commands/swap.ts | 2 +- src/commands/test.ts | 1 + src/commands/transfer.ts | 5 +- src/commands/wallet.ts | 10 +- src/lib/cli-host.ts | 7 +- src/lib/contract/call.ts | 1 + src/lib/contract/deploy.ts | 1 + src/lib/contract/runner.ts | 18 ++-- src/lib/contract/runtime-check.ts | 10 +- src/lib/dev/provision-wallets.ts | 16 ++-- src/lib/grant/account-backup.ts | 9 +- src/lib/grant/account-protector.ts | 4 +- src/lib/grant/account.ts | 5 +- src/lib/grant/protect-account.ts | 22 +++-- src/lib/serve-manager.ts | 4 +- src/lib/serve-payer.ts | 4 +- src/lib/swap/offers.ts | 16 ++-- src/lib/swap/request.ts | 2 +- src/lib/test/actions-runner.ts | 12 ++- src/lib/test/prep-runner.ts | 6 +- src/lib/transfer-request.ts | 8 +- src/lib/wallet-can-pay.ts | 4 +- src/lib/wallet-config.ts | 59 ++++++------ src/lib/wallet-create.ts | 10 +- src/lib/wallet-protector.ts | 10 +- 66 files changed, 396 insertions(+), 285 deletions(-) create mode 100644 src/__tests__/host-engines.test.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index eaba383f..915d1127 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -965,9 +965,6 @@ export declare class OtherSdkSetError extends Error { constructor(loadedSet: SdkSet, wantedSet: SdkSet, message?: string); } export declare function claimSdkSet(set: SdkSet): void; -export declare function bridgeEngines(engines: HostEngines): void; -export declare function engineFor(network: NetworkName, root: string): Promise; -export declare function anyEngine(): Promise; ``` ## `@kuiralabs/midnight-cli-core/lib/error-trim` @@ -1599,7 +1596,7 @@ export declare function clearWalletCache(address: string | undefined, network: s ## `@kuiralabs/midnight-cli-core/lib/wallet-session` ```ts -import { type OpenedConnector, type TransactionDetail } from "./engine.ts"; +import { type HostEngines, type OpenedConnector, type TransactionDetail } from "./engine.ts"; import type { NetworkConfig, NetworkName } from "./network.ts"; import type { NoticeSink } from "./notices.ts"; import type { SwapLeg } from "./swap-offer.ts"; @@ -1655,6 +1652,7 @@ export interface OpenWalletSessionOptions { network: NetworkName; root: string; notice: NoticeSink; + engines: HostEngines; networkConfig?: NetworkConfig; forceShielded?: boolean; dustWaitMs?: number; diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index c0d0a3de..1e68b394 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -521,28 +521,3 @@ export function claimSdkSet(set: SdkSet): void { if (loadedSet !== undefined && loadedSet !== set) throw new OtherSdkSetError(loadedSet, set); loadedSet = set; } - -// A temporary bridge, gone once every library takes its host's engines: the -// engines of the host the shell bridges to, for the libraries that don't yet. -// The shell sets it once at start, so the CLI process has one engine. -let bridged: HostEngines | undefined; - -/** Gives engineFor and anyEngine the engines of the host they serve: the shell's, set once at start. */ -export function bridgeEngines(engines: HostEngines): void { - bridged = engines; -} - -function bridgedEngines(): HostEngines { - if (bridged === undefined) throw new Error('No SDK engine is installed: the shell bridges its host\'s engines at start (bridgeEngines)'); - return bridged; -} - -/** The bridged host's engine for a network's SDK set (by the config under the state root `root`), loaded on first use. */ -export function engineFor(network: NetworkName, root: string): Promise { - return bridgedEngines().load(sdkSetOf(network, root)); -} - -/** The bridged host's engine for work every set does alike (see HostEngines.any). */ -export function anyEngine(): Promise { - return bridgedEngines().any(); -} diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index f2ab061d..70e44a9a 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -11,7 +11,7 @@ // writes retry). Until the session has built its first transaction, it meets // that by reopening the wallet and asking again, a few times. -import { engineFor, type DAppConnector, type OpenedConnector, type TransactionDetail } from './engine.ts'; +import { sdkSetOf, type DAppConnector, type HostEngines, type OpenedConnector, type TransactionDetail } from './engine.ts'; import type { NetworkConfig, NetworkName } from './network.ts'; import type { NoticeSink } from './notices.ts'; import { resolveNetwork } from './resolve-network.ts'; @@ -226,6 +226,8 @@ export interface OpenWalletSessionOptions { root: string; /** Where the wallet's lines for the person go (a cache it can't restore from, the connector's waits for Dust). */ notice: NoticeSink; + /** The engines of the host the session opens in: the network's SDK set is loaded from them. */ + engines: HostEngines; /** The network's endpoints; when absent, as a command without endpoint flags resolves them (the saved config, then the defaults). */ networkConfig?: NetworkConfig; /** Whether to sync the shielded wallet; off where the network has no shielded faucet, unless forced. */ @@ -239,16 +241,16 @@ export interface OpenWalletSessionOptions { } /** - * Opens a seed's wallet on a network: synced, its Dust ready. The host must - * have installed its engine loader and settings first, as the CLI does at - * start. + * Opens a seed's wallet on a network: synced, its Dust ready, with the + * network's engine from `options.engines`. The host must have installed its + * settings first, as the CLI does at start. */ export async function openWalletSession(options: OpenWalletSessionOptions): Promise { const { seed, network, root, signal } = options; throwIfCancelled(signal); const networkConfig = options.networkConfig ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } }, configDir: root }).config; - const engine = await engineFor(network, root); + const engine = await options.engines.load(sdkSetOf(network, root)); const open = () => engine.wallet.openConnector({ seed, root, diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index 546a3737..bab26b3e 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -86,7 +86,6 @@ export const ALLOWED_STATE = { 'lib/chain-id.ts': { CHAIN_ID_MEMO: 'shared on purpose: the chain-id memo, by endpoint' }, 'lib/engine.ts': { loadedSet: 'shared on purpose: the SDK set this process loads, whichever host loads it (two WASM ledgers cannot share a process)', - bridged: "temporary until slice 6: the shell's host's engines, for the libraries that don't take their host's engines yet", }, // The host source, set once by the host at start (handlers see it through the context). 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index 53e5f5e4..5df5a629 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -23,12 +23,13 @@ import { parseDeviceCode } from '../lib/grant/device-code.ts'; import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStatePassword } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -77,7 +78,7 @@ afterEach(() => { describe("an account's backup", () => { it('holds nothing in the clear but the network and the address', async () => { - await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup); + await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); const text = fs.readFileSync(backup, 'utf8'); expect(JSON.parse(text)).toMatchObject({ network: 'undeployed', contractAddress: ACCOUNT }); for (const secret of [RECORD.encryptionSecret, RECORD.bootSalt, 'bb'.repeat(32)]) expect(text).not.toContain(secret); @@ -86,11 +87,11 @@ describe("an account's backup", () => { it('is never written over a file that exists', async () => { fs.writeFileSync(backup, 'something'); - await expect(exportAccount(fromDir, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/already exists/); + await expect(exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines)).rejects.toThrow(/already exists/); }); it('imports for a wallet with no account, which then acts as the same owner, its private state with it', async () => { - await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup); + await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); establishPassphrase(stateRootIn(there), PASSPHRASE); expect(await importAccount(toDir, 'undeployed', PASSPHRASE, backup)).toEqual({ contractAddress: ACCOUNT }); const { account, privateState } = await privateStateIn(there, toDir); @@ -102,13 +103,13 @@ describe("an account's backup", () => { }); it('is never imported over an account, nor for another network', async () => { - await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup); + await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); await expect(importAccount(fromDir, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/already has an account/); await expect(importAccount(toDir, 'preview', PASSPHRASE, backup)).rejects.toThrow(/undeployed/); }); it('opens only with the passphrase it was made with', async () => { - await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup); + await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); await expect(importAccount(toDir, 'undeployed', 'not the passphrase it was made with', backup)).rejects.toThrow(WrongPassphraseError); expect(fs.existsSync(toDir)).toBe(false); }); @@ -121,7 +122,7 @@ describe("a backup made for another device", () => { const pending = createPendingDevice(toDir, PASSPHRASE); expect(pending.arm).toBe('v1'); const pendingCode = ownDeviceCode(toDir, openAccountKey(toDir, PASSPHRASE), pending); - await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, { forDevice: parseDeviceCode(pendingCode) }); + await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines, { forDevice: parseDeviceCode(pendingCode) }); await importAccount(toDir, 'undeployed', PASSPHRASE, backup); const { account, privateState } = await privateStateIn(there, toDir); const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), host, source: source() }); @@ -143,7 +144,7 @@ describe("a backup made for another device", () => { establishPassphrase(stateRootIn(other), PASSPHRASE); fs.mkdirSync(otherDir, { recursive: true }); const stranger = createPendingDevice(otherDir, PASSPHRASE); - await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, { forDevice: parseDeviceCode(ownDeviceCode(otherDir, openAccountKey(otherDir, PASSPHRASE), stranger)) }); + await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines, { forDevice: parseDeviceCode(ownDeviceCode(otherDir, openAccountKey(otherDir, PASSPHRASE), stranger)) }); await expect(importAccount(toDir, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/made for another device/); const empty = accountsOf(path.join(root, 'empty')); await expect(importAccount(empty, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/device new/); diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 48416372..b003a9ba 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -262,7 +262,7 @@ describe('commands that write check the call before each whole write', () => { createdAt: '2026-10-31T00:00:00.000Z', }, path.join(stateRootIn(home), 'wallets', `${name}.json`)); }; - const isSealed = async (file: string): Promise => (await loadWalletConfig(file)).isSealed === true; + const isSealed = async (file: string): Promise => (await loadWalletConfig(file, testHost().engines)).isSealed === true; it('cancelled while the passphrase is asked for: no wallet is sealed', async () => { const files = [plainWallet('alice', 'a1'), plainWallet('bob', 'b2')]; @@ -279,7 +279,7 @@ describe('commands that write check the call before each whole write', () => { const files = [plainWallet('alice', 'a1'), plainWallet('bob', 'b2'), plainWallet('carol', 'c3')]; const call = new AbortController(); - const protecting = protectAllWallets(stateRootIn(home), PASSPHRASE, call.signal); + const protecting = protectAllWallets(stateRootIn(home), PASSPHRASE, testHost().engines, call.signal); // Lands while the first wallet is being sealed: after the first turn of the event loop, before the second. setImmediate(() => call.abort()); @@ -313,7 +313,7 @@ describe('commands that write check the call before each whole write', () => { it('cache clear --wallet: cancelled while the wallet is unlocked, it clears no cache', async () => { establishPassphrase(stateRootIn(home), PASSPHRASE); - const created = await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE); + const created = await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE, await testHost().engines.any()); const cache = getCachePath(created.addresses.undeployed, 'undeployed', stateRootIn(home)); fs.mkdirSync(path.dirname(cache), { recursive: true }); fs.writeFileSync(cache, '{}'); diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index ea771edd..c95c7f77 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -43,6 +43,7 @@ const generateStateScript = (opts: StateScript & { dappDir?: string }): string = const providerSetupCode = (networkConfig: Parameters[0], key: string): string => rcScripts.providerSetupCode(networkConfig, key, SCRIPT_PARTS); import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { testHost } from './helpers/test-host.ts'; const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new ( ...params: string[] @@ -265,7 +266,7 @@ describe('a cancelled run', () => { const dappDir = mkdtempSync(join(tmpdir(), 'mn-cancelled-run-')); const root = mkdtempSync(join(tmpdir(), 'mn-cancelled-run-root-')); try { - const common = { dappDir, network: 'undeployed' as const, root, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; + const common = { dappDir, network: 'undeployed' as const, root, engines: testHost().engines, networkConfig: NETWORK, managedDir: join(dappDir, 'managed', 'counter'), contractName: 'counter', signal: AbortSignal.abort() }; await expect(runDeploy({ ...common, servePort: 9932 })).rejects.toBeInstanceOf(CancelledError); await expect(runCall({ ...common, servePort: 9932, contractAddress: 'ab'.repeat(32), circuit: 'increment' })).rejects.toBeInstanceOf(CancelledError); await expect(runState({ ...common, contractAddress: 'ab'.repeat(32) })).rejects.toBeInstanceOf(CancelledError); diff --git a/src/__tests__/contract-runtime-check.test.ts b/src/__tests__/contract-runtime-check.test.ts index 5af7698e..cf06cc0a 100644 --- a/src/__tests__/contract-runtime-check.test.ts +++ b/src/__tests__/contract-runtime-check.test.ts @@ -9,11 +9,14 @@ import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { runDeploy } from '../lib/contract/runner.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); +// The engines the checks load the network's engine from: a host's of the engines the CLI ships. +const { engines } = createHost({ engineLoader: loadInstalledEngine }); const contract = (runtimeVersion: string, compilerVersion = '0.30.0') => ({ name: 'counter', compilerVersion, runtimeVersion }); // A state root with no config: undeployed on the set the table names. @@ -34,7 +37,7 @@ describe('the rc engine\'s compact runtime', () => { describe('a contract for another compact runtime', () => { it('is refused as a usage mistake, naming both runtimes and the compiler to use', async () => { - const refused = await assertContractRunsOn(contract('0.16.0'), 'undeployed', ROOT).then(() => undefined, (err: unknown) => err); + const refused = await assertContractRunsOn(contract('0.16.0'), 'undeployed', ROOT, engines).then(() => undefined, (err: unknown) => err); expect(refused).toBeInstanceOf(UsageError); expect((refused as Error).message).toBe( 'counter was compiled by compactc 0.30.0 for compact-runtime 0.16.0, but undeployed runs contracts on compact-runtime 0.20.0.\nRecompile it with compactc 0.35.', @@ -43,8 +46,8 @@ describe('a contract for another compact runtime', () => { }); it('lets through one compiled for the engine\'s runtime, and one whose compiler recorded none', async () => { - await expect(assertContractRunsOn(contract('0.20.0', '0.35.0'), 'undeployed', ROOT)).resolves.toBeUndefined(); - await expect(assertContractRunsOn(contract('unknown', 'unknown'), 'undeployed', ROOT)).resolves.toBeUndefined(); + await expect(assertContractRunsOn(contract('0.20.0', '0.35.0'), 'undeployed', ROOT, engines)).resolves.toBeUndefined(); + await expect(assertContractRunsOn(contract('unknown', 'unknown'), 'undeployed', ROOT, engines)).resolves.toBeUndefined(); }); it('is refused by the runner too, before any script runs', async () => { @@ -54,7 +57,7 @@ describe('a contract for another compact runtime', () => { fs.mkdirSync(path.join(managedDir, 'compiler'), { recursive: true }); fs.writeFileSync(path.join(managedDir, 'compiler', 'contract-info.json'), JSON.stringify({ 'compiler-version': '0.30.0', 'language-version': '0.22.0', 'runtime-version': '0.16.0', circuits: [], witnesses: [] })); const networkConfig = { indexer: 'http://127.0.0.1:1', indexerWS: 'ws://127.0.0.1:1', node: 'ws://127.0.0.1:1', proofServer: 'http://127.0.0.1:1', networkId: 'Undeployed' }; - await expect(runDeploy({ dappDir, network: 'undeployed', root: ROOT, networkConfig, managedDir, contractName: 'counter', servePort: 1 })) + await expect(runDeploy({ dappDir, network: 'undeployed', root: ROOT, engines, networkConfig, managedDir, contractName: 'counter', servePort: 1 })) .rejects.toThrow('Recompile it with compactc 0.35.'); // No script was written into the dApp. expect(fs.readdirSync(dappDir).filter((f) => f.endsWith('.mjs'))).toEqual([]); diff --git a/src/__tests__/grant-account.test.ts b/src/__tests__/grant-account.test.ts index 1c5de166..f7e59209 100644 --- a/src/__tests__/grant-account.test.ts +++ b/src/__tests__/grant-account.test.ts @@ -15,9 +15,10 @@ import { openGrantAccount } from '../lib/grant/account.ts'; import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const PASSPHRASE = 'correct horse battery staple'; const RECORD = { contractAddress: '5e'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }; diff --git a/src/__tests__/helpers/shell-settings.ts b/src/__tests__/helpers/shell-settings.ts index a8fa43da..221942d1 100644 --- a/src/__tests__/helpers/shell-settings.ts +++ b/src/__tests__/helpers/shell-settings.ts @@ -1,12 +1,8 @@ // The test run stands in for the shell: libraries read the environment the -// tests set (MN_PASSPHRASE, MN_SEED, …) as settings, and the libraries that -// don't take their host's engines yet reach the engines of a host made with -// the engines the CLI ships, as the CLI bridges them. Where state is kept, each -// test says: its host's paths (test-host.ts), or the root it passes a library. +// tests set (MN_PASSPHRASE, MN_SEED, …) as settings. Where state is kept and +// which engine runs, each test says: its host's paths and engines +// (test-host.ts), or the root and engines it passes a library. import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { bridgeEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { testHost } from './test-host.ts'; setSettingsSource(() => settingsFromEnvironment(process.env)); -bridgeEngines(testHost().engines); diff --git a/src/__tests__/host-engines.test.ts b/src/__tests__/host-engines.test.ts new file mode 100644 index 00000000..f80e027c --- /dev/null +++ b/src/__tests__/host-engines.test.ts @@ -0,0 +1,98 @@ +// The libraries use the engine of the host they are given, never another +// host's: two hosts on the rc set in one process, each with an engine of its +// own, and a library function given one host's engines loads and reads only +// that host's engine. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; +import { listWallets } from '../lib/wallet-config.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; + +// The chain and the indexer stand in at the repository's seams; the rest is each engine's own. +const NETWORK: NetworkConfig = { + indexer: 'http://test/indexer', + indexerWS: 'ws://test/indexer/ws', + node: 'ws://test/node', + proofServer: 'http://test/proof', + networkId: 'Undeployed', +}; +const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; +const ADDRESSES = deriveAllAddresses(Buffer.from(SEED, 'hex')); +const empty = (): BalanceSummary => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }); + +let root: string; +// Which host's loader made an engine, and which host's repository fetched a balance. +let loaded: string[]; +let fetched: string[]; + +/** A host on `root` named `name`, whose engine is an rc engine of its own, its repository's fetches recorded under its name. */ +const hostNamed = (name: string): Host => + createHost({ + paths: { stateRoot: root, home: root }, + engineLoader: async (_set: SdkSet, host: Host) => { + loaded.push(name); + return createRcEngine(host, { + repository: { + fetchTip: async () => 'tip-1', + fetchUnshielded: async (address) => { fetched.push(`${name} ${address}`); return empty(); }, + }, + }); + }, + }); + +beforeEach(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-host-engines-'))); + loaded = []; + fetched = []; +}); + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); + +describe('a library given one host', () => { + it("checks a paying wallet through that host's engine: only its repository fetches, and keeps what it read", async () => { + saveWalletConfig({ seed: SEED, addresses: ADDRESSES, createdAt: '2026-11-03T00:00:00.000Z' }, path.join(root, 'wallets', 'alice.json')); + const hostA = hostNamed('A'); + const hostB = hostNamed('B'); + const target = (host: Host): PayingTarget => ({ network: 'undeployed', root, host, networkConfig: NETWORK, endpoints: {} }); + + await expect(assertWalletCanPay(target(hostB), 'alice', silentSpinner(), undefined)).rejects.toThrow('Wallet has 0 NIGHT on undeployed'); + expect(loaded).toStrictEqual(['B']); + expect(fetched).toStrictEqual([`B ${ADDRESSES.undeployed}`]); + + await expect(assertWalletCanPay(target(hostA), 'alice', silentSpinner(), undefined)).rejects.toThrow('Wallet has 0 NIGHT on undeployed'); + expect(loaded).toStrictEqual(['B', 'A']); + expect(fetched).toStrictEqual([`B ${ADDRESSES.undeployed}`, `A ${ADDRESSES.undeployed}`]); + + // Host B's repository has the balance at this tip; host A's read never filled it. + await expect(assertWalletCanPay(target(hostB), 'alice', silentSpinner(), undefined)).rejects.toThrow('Wallet has 0 NIGHT on undeployed'); + expect(fetched).toHaveLength(2); + expect(loaded).toStrictEqual(['B', 'A']); + }); + + it("derives an old wallet's addresses with an engine of the engines it is given, loading no other host's", async () => { + // A wallet from before the addresses map: its addresses are derived from its seed when listed. + saveWalletConfig({ seed: SEED, address: ADDRESSES.undeployed, createdAt: '2026-11-03T00:00:00.000Z' } as never, path.join(root, 'wallets', 'old.json')); + const hostA = hostNamed('A'); + const hostB = hostNamed('B'); + + const [old] = await listWallets(root, hostB.engines); + expect(old.addresses).toStrictEqual(ADDRESSES); + expect(loaded).toStrictEqual(['B']); + + await listWallets(root, hostA.engines); + expect(loaded).toStrictEqual(['B', 'A']); + }); +}); diff --git a/src/__tests__/host-paths.test.ts b/src/__tests__/host-paths.test.ts index 3eab648e..585cfce1 100644 --- a/src/__tests__/host-paths.test.ts +++ b/src/__tests__/host-paths.test.ts @@ -21,6 +21,7 @@ import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import { getActiveWalletName, listWallets } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { clearChainCaches } from '../lib/chain-caches.ts'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; const PASSPHRASE = 'correct horse battery staple'; const MAKER = 'mn_addr_undeployed1maker'; @@ -39,16 +40,16 @@ let rootB: string; let hostA: Host; let hostB: Host; -/** A host whose state root is `/.midnight`, and a home of its own. */ +/** A host whose state root is `/.midnight`, a home of its own, and an engine of its own from the engines the CLI ships. */ function hostAt(home: string): Host { - return createHost({ paths: { stateRoot: path.join(home, MIDNIGHT_DIR), home } }); + return createHost({ paths: { stateRoot: path.join(home, MIDNIGHT_DIR), home }, engineLoader: loadInstalledEngine }); } /** A wallet created under `host`'s state root, sealed under the passphrase set there. */ async function walletIn(host: Host, name: string): Promise { const root = host.paths().stateRoot; const passphrase = await passphraseForNewSecret(host, root, { env: { [PASSPHRASE_ENV]: PASSPHRASE } }); - await createWallet(root, name, walletSecretFrom({ seed: Buffer.alloc(32, name.length) }), passphrase); + await createWallet(root, name, walletSecretFrom({ seed: Buffer.alloc(32, name.length) }), passphrase, await host.engines.any()); } beforeEach(() => { @@ -84,8 +85,8 @@ describe('two hosts with different state roots', () => { await walletIn(hostA, 'alice'); await walletIn(hostB, 'bob'); - expect((await listWallets(rootA)).map((w) => w.name)).toEqual(['alice']); - expect((await listWallets(rootB)).map((w) => w.name)).toEqual(['bob']); + expect((await listWallets(rootA, hostA.engines)).map((w) => w.name)).toEqual(['alice']); + expect((await listWallets(rootB, hostB.engines)).map((w) => w.name)).toEqual(['bob']); expect(getActiveWalletName(rootA)).toBe('alice'); expect(getActiveWalletName(rootB)).toBe('bob'); // As the MCP server runs it. diff --git a/src/__tests__/host-slots.test.ts b/src/__tests__/host-slots.test.ts index 1cbf1664..2c8988e8 100644 --- a/src/__tests__/host-slots.test.ts +++ b/src/__tests__/host-slots.test.ts @@ -10,6 +10,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { WebSocket } from 'ws'; import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; import { NoPassphraseError, PASSPHRASE_ENV, establishPassphrase, unlockPassphrase } from '../lib/passphrase.ts'; @@ -33,9 +34,9 @@ function answering(answer: string): Prompter & { questions: string[] } { }; } -/** A host whose notices land in `lines`, asking through `prompter`. */ +/** A host whose notices land in `lines`, asking through `prompter`, with an engine of its own from the engines the CLI ships. */ const hostSaying = (lines: string[], prompter: Prompter | null = null): Host => - createHost({ notice: (line) => lines.push(line), prompter }); + createHost({ notice: (line) => lines.push(line), prompter, engineLoader: loadInstalledEngine }); let home: string; diff --git a/src/__tests__/multi-wallet.test.ts b/src/__tests__/multi-wallet.test.ts index ec705060..35879103 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/src/__tests__/multi-wallet.test.ts @@ -27,6 +27,11 @@ import { isValidWalletName, } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; + +// The engines the wallet functions derive a wallet's missing addresses with: a host's of the engines the CLI ships. +const { engines } = createHost({ engineLoader: loadInstalledEngine }); // Use a temp dir that simulates ~/.midnight const TEST_HOME = path.join(os.tmpdir(), `midnight-multi-wallet-test-${process.pid}`); @@ -107,7 +112,7 @@ describe('resolveWalletPath', () => { describe('listWallets', () => { it('returns empty array when wallets dir does not exist', async () => { - const wallets = await listWallets(TEST_MIDNIGHT_DIR); + const wallets = await listWallets(TEST_MIDNIGHT_DIR, engines); expect(wallets).toEqual([]); }); @@ -174,7 +179,7 @@ describe('migrateOldWallet', () => { describe('loadWalletConfig error messages', () => { it('suggests "midnight wallet generate" in missing file error', async () => { const filePath = path.join(TEST_HOME, 'nonexistent.json'); - await expect(loadWalletConfig(filePath)).rejects.toThrow('midnight wallet generate'); + await expect(loadWalletConfig(filePath, engines)).rejects.toThrow('midnight wallet generate'); }); }); @@ -248,7 +253,7 @@ describe('wallet config round-trip with named wallets', () => { it('saves and loads from wallets directory path', async () => { const walletPath = path.join(TEST_WALLETS_DIR, 'test.json'); saveWalletConfig(VALID_WALLET, walletPath); - const loaded = await loadWalletConfig(walletPath); + const loaded = await loadWalletConfig(walletPath, engines); expect(loaded).not.toHaveProperty('seed'); expect(loaded.isSealed).toBe(false); expect(loaded.addresses).toEqual(VALID_WALLET.addresses); diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index 80fe799f..95124ab9 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -20,6 +20,7 @@ import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-conte import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +import { testHost } from './helpers/test-host.ts'; const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -39,8 +40,9 @@ beforeEach(async () => { process.env.HOME = home; process.env.MN_PASSPHRASE = PASSPHRASE; establishPassphrase(stateRootIn(home), PASSPHRASE); - await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE); - await createWallet(stateRootIn(home), 'bob', walletSecretFrom(), PASSPHRASE); + const { engines } = testHost(); + await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE, await engines.any()); + await createWallet(stateRootIn(home), 'bob', walletSecretFrom(), PASSPHRASE, await engines.any()); io = captureOutput(); // Every endpoint: takes HTTP requests and WebSocket upgrades, and answers none. requests = 0; diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index 07588c04..d51ecd8b 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -8,6 +8,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { unlockWallet } from '../lib/wallet-config.ts'; import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; @@ -34,8 +35,8 @@ describe('notices', () => { it("carry a library's warning to its host's notices when its caller gives no warn of its own, and nowhere when the host takes none", async () => { const lines: string[] = []; const wallet = plainWallet('notice-alice'); - await unlockWallet(wallet, { root: path.join(home, '.midnight'), host: createHost() }); - await unlockWallet(wallet, { root: path.join(home, '.midnight'), host: createHost({ notice: (line) => lines.push(line) }) }); + await unlockWallet(wallet, { root: path.join(home, '.midnight'), host: createHost({ engineLoader: loadInstalledEngine }) }); + await unlockWallet(wallet, { root: path.join(home, '.midnight'), host: createHost({ notice: (line) => lines.push(line), engineLoader: loadInstalledEngine }) }); expect(lines).toHaveLength(1); expect(lines[0]).toMatch(/not protected: its seed is in plain text/); }); diff --git a/src/__tests__/protect-account.test.ts b/src/__tests__/protect-account.test.ts index 2e8d2097..fdd845d4 100644 --- a/src/__tests__/protect-account.test.ts +++ b/src/__tests__/protect-account.test.ts @@ -19,9 +19,10 @@ import { AccountMigrationInterruptedError, protectAccount } from '../lib/grant/p import { isSealedAccount } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -70,7 +71,7 @@ afterEach(() => { describe('protecting an account an earlier mn made in plain text', () => { it('seals its records, roster and owner key, and leaves nothing secret in plain text', async () => { await writePlainAccount(); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY)).toBe('sealed-now'); + expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('sealed-now'); expect(isSealedAccount(dir)).toBe(true); expect(plainTextLeft()).toEqual([]); const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); @@ -82,7 +83,7 @@ describe('protecting an account an earlier mn made in plain text', () => { it('moves its private state onto a password of its own, off the public one', async () => { await writePlainAccount(); - await protectAccount(dir, PASSPHRASE, COIN_KEY); + await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines); const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); const own = await account.location.password(); expect(own).not.toBe(LEGACY_STORE_PASSWORD); @@ -92,22 +93,22 @@ describe('protecting an account an earlier mn made in plain text', () => { it('is left as it is once sealed', async () => { await writePlainAccount(); - await protectAccount(dir, PASSPHRASE, COIN_KEY); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY)).toBe('already-sealed'); + await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines); + expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('already-sealed'); }); it('has nothing to protect where there is no account', async () => { fs.mkdirSync(dir, { recursive: true }); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY)).toBe('nothing'); + expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('nothing'); }); it('is refused while caught half way, and finished by the next run', async () => { await writePlainAccount(); // A run that stopped after moving the private state, before the account was sealed. - await protectAccount(dir, PASSPHRASE, COIN_KEY, { stopBeforeSealing: true }); + await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines, { stopBeforeSealing: true }); expect(isSealedAccount(dir)).toBe(false); await expect(openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, warn: () => {} })).rejects.toThrow(AccountMigrationInterruptedError); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY)).toBe('sealed-now'); + expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('sealed-now'); const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); expect(await (await privateStateUnder(await account.location.password())).get(PRIVATE_STATE_ID)).toEqual(PRIVATE_STATE); expect(plainTextLeft()).toEqual([]); @@ -116,7 +117,7 @@ describe('protecting an account an earlier mn made in plain text', () => { it('seals the records of a deploy that never landed, kept aside in plain text', async () => { await writePlainAccount(); fs.writeFileSync(path.join(dir, 'owner.unlanded-1790000000000.json'), JSON.stringify({ ...RECORD, deviceArm: 'k1', deviceSk: DEVICE_SECRET })); - await protectAccount(dir, PASSPHRASE, COIN_KEY); + await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines); expect(plainTextLeft()).toEqual([]); expect(fs.readdirSync(dir).some((f) => f.startsWith('owner.unlanded-1790000000000') && f.endsWith('.sealed.json'))).toBe(true); }); diff --git a/src/__tests__/sealed-wallet.test.ts b/src/__tests__/sealed-wallet.test.ts index ac3710d1..e0e21c47 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/src/__tests__/sealed-wallet.test.ts @@ -15,9 +15,10 @@ import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midni import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; const MNEMONIC = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; @@ -52,7 +53,7 @@ describe('a sealed wallet', () => { it('shows its addresses without the passphrase', async () => { writeSealedWallet(file, PUBLIC, { seed: SEED }, PASSPHRASE); - const config = await loadWalletConfig(file); + const config = await loadWalletConfig(file, host.engines); expect(config.addresses).toEqual(PUBLIC.addresses); expect(config.shieldedAddresses).toEqual(PUBLIC.shieldedAddresses); expect(config.isSealed).toBe(true); @@ -88,17 +89,17 @@ describe('a wallet an earlier mn wrote in plain text', () => { const warnings: string[] = []; const wallet = await unlockWallet(file, { root: stateRootIn(home), host, warn: (line) => warnings.push(line) }); expect(wallet.seed).toBe(SEED); - expect((await loadWalletConfig(file)).isSealed).toBe(false); + expect((await loadWalletConfig(file, host.engines)).isSealed).toBe(false); expect(warnings.join('\n')).toMatch(/not protected[\s\S]*midnight wallet protect/); }); it('is sealed in place, keeping its seed, mnemonic and addresses, with nothing left in the clear', async () => { writePlain(); - await sealWalletInPlace(file, PASSPHRASE); + await sealWalletInPlace(file, PASSPHRASE, host.engines); const text = fs.readFileSync(file, 'utf8'); expect(text).not.toContain(SEED); expect(text).not.toContain('abandon'); - expect(await loadWalletConfig(file)).toMatchObject({ ...PUBLIC, isSealed: true }); + expect(await loadWalletConfig(file, host.engines)).toMatchObject({ ...PUBLIC, isSealed: true }); const wallet = await unlockWallet(file, withPassphrase(PASSPHRASE)); expect(wallet.seed).toBe(SEED); expect(wallet.mnemonic).toBe(MNEMONIC); @@ -107,7 +108,7 @@ describe('a wallet an earlier mn wrote in plain text', () => { it('is left as it was when it is already sealed', async () => { writeSealedWallet(file, PUBLIC, { seed: SEED }, PASSPHRASE); const before = fs.readFileSync(file, 'utf8'); - await sealWalletInPlace(file, PASSPHRASE); + await sealWalletInPlace(file, PASSPHRASE, host.engines); expect(fs.readFileSync(file, 'utf8')).toBe(before); }); }); @@ -125,7 +126,7 @@ describe('protecting every wallet', () => { const bob = writePlainAt('bob', OTHER_SEED); const carol = writePlainAt('carol', SEED); writeSealedWallet(file, PUBLIC, { seed: SEED }, PASSPHRASE); - const report = await protectAllWallets(stateRootIn(home), PASSPHRASE); + const report = await protectAllWallets(stateRootIn(home), PASSPHRASE, host.engines); expect(report).toEqual([ { name: 'alice', file, sealedNow: false }, { name: 'bob', file: bob, sealedNow: true }, @@ -136,7 +137,7 @@ describe('protecting every wallet', () => { }); it('protects nothing, and says so, where there is no wallet', async () => { - expect(await protectAllWallets(stateRootIn(home), PASSPHRASE)).toEqual([]); + expect(await protectAllWallets(stateRootIn(home), PASSPHRASE, host.engines)).toEqual([]); }); }); diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 5d4f0ca1..70c549fa 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -12,9 +12,10 @@ import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const PASSPHRASE = 'correct horse battery staple'; const ORIGINAL_HOME = process.env.HOME; diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index c0278457..94d163a3 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -12,9 +12,10 @@ import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-war import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const scratch = { node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws' }; diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index bf748600..48221de0 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -10,6 +10,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; import { cliCall } from './helpers/cli-call.ts'; @@ -43,7 +44,8 @@ async function writeEveryOwnersFiles(root: string): Promise { setConfigValue('network', 'preview', root); setConfigValue('node', 'ws://localhost:29944', root, 'undeployed'); bindCachesToIndexer('undeployed', 'ws://localhost:28088/api/v4/graphql/ws', root); - await createWallet(root, 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret(createHost(), root)); + const host = createHost({ engineLoader: loadInstalledEngine }); + await createWallet(root, 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret(host, root), await host.engines.any()); fs.mkdirSync(accountRecordsDir('undeployed', 'alice', root), { recursive: true }); } diff --git a/src/__tests__/swap-request.test.ts b/src/__tests__/swap-request.test.ts index 6cd3af83..306eeff9 100644 --- a/src/__tests__/swap-request.test.ts +++ b/src/__tests__/swap-request.test.ts @@ -14,9 +14,10 @@ import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../lib/swap/request.ts'; import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const NOW = new Date('2026-11-02T12:00:00.000Z'); // A state root with no config: the networks' own endpoints. diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index 07786070..b3caecfb 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -14,9 +14,10 @@ import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '@kuiralabs/midnight-cli-core/lib import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const HOME = path.join(os.tmpdir(), `midnight-transfer-request-test-${process.pid}`); const WALLETS = path.join(HOME, MIDNIGHT_DIR, WALLETS_DIR_NAME); diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 98b94b56..729dc0b4 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -9,9 +9,10 @@ import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants' import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const TEST_DIR = path.join(os.tmpdir(), `midnight-wallet-test-${process.pid}`); @@ -75,7 +76,7 @@ describe('loadWalletConfig', () => { it('loads a plain-text wallet an earlier mn wrote, without its secrets', async () => { const filePath = path.join(TEST_DIR, 'wallet.json'); saveWalletConfig(VALID_CONFIG, filePath); - const loaded = await loadWalletConfig(filePath); + const loaded = await loadWalletConfig(filePath, host.engines); expect(loaded).not.toHaveProperty('seed'); expect(loaded.isSealed).toBe(false); expect(loaded.addresses).toEqual(VALID_CONFIG.addresses); @@ -84,23 +85,23 @@ describe('loadWalletConfig', () => { it('throws when file does not exist', async () => { const filePath = path.join(TEST_DIR, 'nonexistent.json'); - await expect(loadWalletConfig(filePath)).rejects.toThrow('Wallet file not found'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('Wallet file not found'); }); it('includes actionable recovery guidance in missing file error', async () => { const filePath = path.join(TEST_DIR, 'nonexistent.json'); - await expect(loadWalletConfig(filePath)).rejects.toThrow('midnight wallet generate'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('midnight wallet generate'); }); it('includes the file path in missing file error', async () => { const filePath = path.join(TEST_DIR, 'nonexistent.json'); - await expect(loadWalletConfig(filePath)).rejects.toThrow(filePath); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow(filePath); }); it('throws on invalid JSON', async () => { const filePath = path.join(TEST_DIR, 'bad.json'); fs.writeFileSync(filePath, 'not json at all'); - await expect(loadWalletConfig(filePath)).rejects.toThrow('Invalid JSON'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('Invalid JSON'); }); it('throws when seed is missing', async () => { @@ -109,7 +110,7 @@ describe('loadWalletConfig', () => { addresses: VALID_ADDRESSES, createdAt: '2025-01-01T00:00:00.000Z', })); - await expect(loadWalletConfig(filePath)).rejects.toThrow('seed'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('seed'); }); it('throws when address and addresses are both missing', async () => { @@ -118,7 +119,7 @@ describe('loadWalletConfig', () => { seed: VALID_SEED, createdAt: '2025-01-01T00:00:00.000Z', })); - await expect(loadWalletConfig(filePath)).rejects.toThrow('address'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('address'); }); it('throws when createdAt is missing', async () => { @@ -127,7 +128,7 @@ describe('loadWalletConfig', () => { seed: 'aabb00', addresses: VALID_ADDRESSES, })); - await expect(loadWalletConfig(filePath)).rejects.toThrow('createdAt'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('createdAt'); }); it('throws on non-hex seed', async () => { @@ -137,7 +138,7 @@ describe('loadWalletConfig', () => { addresses: VALID_ADDRESSES, createdAt: '2025-01-01T00:00:00.000Z', })); - await expect(loadWalletConfig(filePath)).rejects.toThrow('Invalid seed format'); + await expect(loadWalletConfig(filePath, host.engines)).rejects.toThrow('Invalid seed format'); }); it('auto-migrates old format with address and network fields', async () => { @@ -148,7 +149,7 @@ describe('loadWalletConfig', () => { address: 'mn_addr_preprod1oldaddress', createdAt: '2025-01-01T00:00:00.000Z', })); - const loaded = await loadWalletConfig(filePath); + const loaded = await loadWalletConfig(filePath, host.engines); // Should have derived all addresses from the seed expect(loaded.addresses).toEqual(VALID_ADDRESSES); expect((loaded as any).network).toBeUndefined(); @@ -237,7 +238,7 @@ describe('a wallet written before stagenet', () => { it('gets its stagenet address derived and saved when a plain-text wallet is read', async () => { const filePath = path.join(TEST_DIR, 'plain.json'); fs.writeFileSync(filePath, JSON.stringify({ seed: VALID_SEED, addresses: earlierAddresses, createdAt: VALID_CONFIG.createdAt })); - const config = await loadWalletConfig(filePath); + const config = await loadWalletConfig(filePath, host.engines); expect(config.addresses.stagenet).toBe(stagenetAddress); expect(JSON.parse(fs.readFileSync(filePath, 'utf-8')).addresses).toEqual(VALID_ADDRESSES); expect(await walletAddress(filePath, 'stagenet', stateRootIn(TEST_DIR), host)).toBe(stagenetAddress); @@ -248,7 +249,7 @@ describe('a wallet written before stagenet', () => { writeSealedWallet(filePath, { addresses: earlierAddresses as typeof VALID_ADDRESSES, shieldedAddresses: earlierShielded as typeof VALID_ADDRESSES, createdAt: VALID_CONFIG.createdAt }, { seed: VALID_SEED }, PASSPHRASE); const sealedBefore = JSON.parse(fs.readFileSync(filePath, 'utf-8')).sealed; - expect((await loadWalletConfig(filePath)).addresses.stagenet).toBeUndefined(); + expect((await loadWalletConfig(filePath, host.engines)).addresses.stagenet).toBeUndefined(); const unlocked = await unlockWallet(filePath, UNLOCK); expect(unlocked.addresses.stagenet).toBe(stagenetAddress); @@ -258,6 +259,6 @@ describe('a wallet written before stagenet', () => { expect(saved.shieldedAddresses.stagenet).toBe(stagenetShielded); expect(saved.sealed).toEqual(sealedBefore); expect(saved.seed).toBeUndefined(); - expect((await loadWalletConfig(filePath)).addresses.stagenet).toBe(stagenetAddress); + expect((await loadWalletConfig(filePath, host.engines)).addresses.stagenet).toBe(stagenetAddress); }); }); diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index 4f71792d..e408f68c 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -14,9 +14,10 @@ import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine }); const CHOSEN = 'correct horse battery staple'; // The passphrase as a caller gets it: the first secret in a new home sets it. @@ -42,7 +43,7 @@ afterEach(() => { describe('createWallet', () => { it('writes a sealed wallet that unlocks to its new mnemonic, and makes it active', async () => { - const created = await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE); + const created = await createWallet(stateRootIn(home), 'alice', walletSecretFrom(), PASSPHRASE, await host.engines.any()); expect(created.file).toBe(walletFilePath(stateRootIn(home), 'alice')); expect(created.mnemonic!.split(' ')).toHaveLength(24); @@ -54,24 +55,24 @@ describe('createWallet', () => { }); it('derives its addresses from a given mnemonic', async () => { - const created = await createWallet(stateRootIn(home), 'bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE); + const created = await createWallet(stateRootIn(home), 'bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE, await host.engines.any()); expect(created.addresses).toEqual(deriveAllAddresses(Buffer.from(mnemonicToSeedSync(MNEMONIC)))); }); it('keeps a given seed and no mnemonic', async () => { const seed = Buffer.alloc(32, 2); - const created = await createWallet(stateRootIn(home), 'carol', walletSecretFrom({ seed }), PASSPHRASE); + const created = await createWallet(stateRootIn(home), 'carol', walletSecretFrom({ seed }), PASSPHRASE, await host.engines.any()); const unlocked = await unlockWallet(created.file, { root: stateRootIn(home) , host}); expect(unlocked.seed).toBe(seed.toString('hex')); expect(unlocked.mnemonic).toBeUndefined(); }); it('replaces an existing wallet only when asked', async () => { - const first = await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE); - await expect(createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE)).rejects.toThrow(`Wallet file already exists: ${first.file}`); + const first = await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 1) }), PASSPHRASE, await host.engines.any()); + await expect(createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, await host.engines.any())).rejects.toThrow(`Wallet file already exists: ${first.file}`); expect((await unlockWallet(first.file, { root: stateRootIn(home) , host})).seed).toBe(Buffer.alloc(32, 1).toString('hex')); - await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, { overwrite: true }); + await createWallet(stateRootIn(home), 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), PASSPHRASE, await host.engines.any(), { overwrite: true }); expect((await unlockWallet(first.file, { root: stateRootIn(home) , host})).seed).toBe(Buffer.alloc(32, 2).toString('hex')); }); diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index 354287c3..91677959 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -20,6 +20,7 @@ import { accountProtector } from '../lib/grant/account-protector.ts'; import type { WalletProtector } from '../lib/wallet-protector.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { testHost } from './helpers/test-host.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; @@ -58,7 +59,7 @@ describe('wallet protect', () => { const result = await protect(); expect(isPassphraseSet(stateRootIn(home))).toBe(true); expect(result).toMatchObject({ sealed: ['alice', 'bob'], alreadySealed: [] }); - expect((await loadWalletConfig(alice)).isSealed).toBe(true); + expect((await loadWalletConfig(alice, testHost().engines)).isSealed).toBe(true); expect(fs.readFileSync(alice, 'utf8')).not.toContain(SEED); }); @@ -74,7 +75,7 @@ describe('wallet protect', () => { const bob = plainWallet('bob'); process.env[PASSPHRASE_ENV] = 'another passphrase entirely'; await expect(protect()).rejects.toThrow(/Wrong passphrase/); - expect((await loadWalletConfig(bob)).isSealed).toBe(false); + expect((await loadWalletConfig(bob, testHost().engines)).isSealed).toBe(false); }); it("seals each wallet's plain-text account too, and names one whose wallet is gone", async () => { diff --git a/src/commands/address.ts b/src/commands/address.ts index 63088021..ed895be4 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -3,7 +3,6 @@ import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveSeed } from '../lib/seed-resolver.ts'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -21,7 +20,7 @@ export default async function addressCommand(args: ParsedArgs, ctx: CallContext) } const networkName = resolveNetworkName({ args, configDir: root }); - const address = (await engineFor(networkName, root)).keys.unshieldedAddress(seedBuffer, networkName, keyIndex); + const address = (await ctx.host.engines.for(networkName)).keys.unshieldedAddress(seedBuffer, networkName, keyIndex); const derivationPath = `m/44'/2400'/0'/NightExternal/${keyIndex}`; // JSON mode diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 3d45a69e..c85c24d1 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -15,7 +15,7 @@ import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAd import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import { parseAmount, nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -98,7 +98,7 @@ async function resolveDestination( const walletFlag = getFlag(args, 'wallet'); if (walletFlag !== undefined && looksLikeBech32mAddress(walletFlag)) { - return resolveAddressDestination(walletFlag, root, networkName, isShielded); + return resolveAddressDestination(walletFlag, host.engines, networkName, isShielded); } // Fall back to wallet file (name, path, or active wallet) @@ -109,7 +109,7 @@ async function resolveDestination( // (unless the network was added after the wallet was written). const stored = await walletShieldedAddress(walletPath, networkName, root, host); if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${networkName}.`); - const decoded = await resolveAddressDestination(stored, root, networkName, true) as ShieldedDestination; + const decoded = await resolveAddressDestination(stored, host.engines, networkName, true) as ShieldedDestination; return { kind: 'wallet', bech32m: decoded.bech32m, walletPath }; } @@ -118,7 +118,7 @@ async function resolveDestination( async function resolveAddressDestination( address: string, - root: string, + engines: HostEngines, networkName: NetworkName, isShielded: boolean, ): Promise { @@ -148,7 +148,7 @@ async function resolveAddressDestination( if (isShielded) { try { - (await engineFor(networkName, root)).keys.assertAddress(address, 'shielded', networkName); + (await engines.for(networkName)).keys.assertAddress(address, 'shielded', networkName); } catch (err: any) { throw new Error(`Invalid shielded address: ${err.message}`); } @@ -180,7 +180,7 @@ async function unshieldedAirdrop( const spinner = ctx.progress.start('Starting genesis wallet...'); try { - const result = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.airdrop({ + const result = await (await ctx.host.engines.for(networkName)).wallet.airdrop({ root: ctx.config.paths.stateRoot, notice: ctx.host.notice, networkConfig, @@ -282,7 +282,7 @@ async function shieldedAirdrop( const spinner = ctx.progress.start('Syncing genesis wallet...'); try { - const txHash = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.shieldedTransfer({ + const txHash = await (await ctx.host.engines.for(networkName)).wallet.shieldedTransfer({ seed: genesisSeedBuffer, root: ctx.config.paths.stateRoot, notice: ctx.host.notice, diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 96f7dcfb..304affb1 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -9,7 +9,6 @@ import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { isNativeToken } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; import { createEtaEstimator, formatSyncStatus } from '../lib/sync-eta.ts'; @@ -73,7 +72,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise // wallets we have the seed → run the full wallet sync (which shows shielded). // Otherwise there's nothing to decrypt with → fail with a clear, actionable error. if (hasFlag(args, 'shielded')) { - const owned = await findWalletByAddress(root, address); + const owned = await findWalletByAddress(root, address, ctx.host.engines); if (owned) { ctx.diagnostics.line('balance', `shielded positional → wallet ${owned.wallet.name} on ${owned.network}`); const delegated: ParsedArgs = { @@ -99,7 +98,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise const spinner = ctx.progress.start(`Checking balance on ${networkName}...`); try { - const result = await (await engineFor(networkName, root)).wallet.unshieldedBalance(address, networkConfig, { + const result = await (await ctx.host.engines.for(networkName)).wallet.unshieldedBalance(address, networkConfig, { forceFresh: hasFlag(args, 'no-cache'), signal: ctx.signal, log: ctx.diagnostics.line, @@ -180,7 +179,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise ctx.diagnostics.line('balance', `wallet path=${walletPath ?? '(from --seed/MN_SEED)'}`); // Derive the unshielded address from the seed so a --seed/MN_SEED caller (no wallet // file) behaves identically to a named wallet — for a wallet this equals the stored one. - const engine = await engineFor(networkName, root); + const engine = await ctx.host.engines.for(networkName); const address = config?.addresses[networkName] ?? engine.keys.unshieldedAddress(seedBuffer, networkName); const shieldedAddrStr = config?.shieldedAddresses?.[networkName] ?? ''; @@ -214,7 +213,7 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise // ── Phase 1: fast unshielded via GraphQL (no facade, no proof server) ── if (!isJson) activeSpinner = ctx.progress.start('Checking unshielded...'); ctx.diagnostics.line('balance', `phase=unshielded forceFresh=${noCache}`); - const unshieldedResult = await (await engineFor(networkName, root)).wallet.unshieldedBalance(address, networkConfig, { + const unshieldedResult = await (await ctx.host.engines.for(networkName)).wallet.unshieldedBalance(address, networkConfig, { forceFresh: noCache, signal: ctx.signal, log: ctx.diagnostics.line, diff --git a/src/commands/cache.ts b/src/commands/cache.ts index 15c43853..601f5364 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -5,7 +5,6 @@ import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/ import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { clearWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { green } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -36,7 +35,7 @@ export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): const address = config.addresses[networkName]; clearWalletCache(address, networkName, root); // Also clear the dust-direct cache for this wallet on this network. - const { keys } = await engineFor(networkName, root); + const { keys } = await ctx.host.engines.for(networkName); const dustPubkey = keys.dustPublicKeyHex(Buffer.from(config.seed, 'hex')); clearDustDirectCache(networkName, dustPubkey, root); clearNativeDustCheckpoint(networkName, dustPubkey, root); diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index dbc7d0d2..e703bf35 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -1,14 +1,15 @@ // The `contract` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; /** The subcommands that reach a chain: inspect reads only the compiled contract (--path, --managed, --name). */ const ON_CHAIN: readonly string[] = ['deploy', 'call', 'state']; -/** The wallet a deploy or call pays from, under the state root `root`, exists and can be read. */ -async function checkSendingWallet(params: Readonly>, root: string): Promise { +/** The wallet a deploy or call pays from, under the state root `root`, exists and can be read (with the host's `engines`). */ +async function checkSendingWallet(params: Readonly>, root: string, engines: HostEngines): Promise { const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); - await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined)); + await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined), engines); } export const contractDefinition: CommandDefinition = { @@ -219,8 +220,8 @@ export const contractDefinition: CommandDefinition = { const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; - await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy', root, call.host).network, root); - await checkSendingWallet(params, root); + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy', root, call.host).network, root, call.host.engines); + await checkSendingWallet(params, root, call.host.engines); }, }, order: 26, @@ -254,8 +255,8 @@ export const contractDefinition: CommandDefinition = { const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; - await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call', root, call.host).network, root); - await checkSendingWallet(params, root); + await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call', root, call.host).network, root, call.host.engines); + await checkSendingWallet(params, root, call.host.engines); }, }, order: 27, diff --git a/src/commands/contract.ts b/src/commands/contract.ts index c1c4f757..68fda833 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -12,7 +12,7 @@ import { type Payer, payerFor, resolvePayingTarget } from '@kuiralabs/midnight-c import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { validateContractAddress } from '../lib/contract/validate.ts'; -import { engineFor, type RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { @@ -120,7 +120,7 @@ async function handleDeploy(args: ParsedArgs, payer: Payer, ctx: CallContext): P const target = resolvePayingTarget(args, 'contract', 'deploy', ctx.config.paths.stateRoot, ctx.host); const { network } = target; - await assertContractRunsOn(info, network, target.root); + await assertContractRunsOn(info, network, target.root, ctx.host.engines); if (!jsonMode) { ctx.output.stderr(keyValue('Contract', info.name) + '\n'); @@ -194,7 +194,7 @@ async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Pro const target = resolvePayingTarget(args, 'contract', 'call', ctx.config.paths.stateRoot, ctx.host); const { network } = target; - await assertContractRunsOn(info, network, target.root); + await assertContractRunsOn(info, network, target.root, ctx.host.engines); if (!jsonMode) { ctx.output.stderr(keyValue('Contract', info.name) + '\n'); @@ -256,6 +256,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { dappDir, network, root, + engines: ctx.host.engines, networkConfig, managedDir: info.managedDir, contractName: info.name, @@ -299,7 +300,7 @@ async function handleState(args: ParsedArgs, ctx: CallContext): Promise { spinner.stop(yellow('⚠') + ' Parsed state unavailable, showing raw'); // The engine's query takes no signal: the call stops waiting for it when cancelled. - const raw = await untilCancelled((await engineFor(network, root)).contracts.rawState(networkConfig, address), ctx.signal); + const raw = await untilCancelled((await ctx.host.engines.for(network)).contracts.rawState(networkConfig, address), ctx.signal); if (!raw) { throw new Error(`No contract found at address ${address} on ${network}`); diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 6de07d2e..ed8d5a61 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -9,7 +9,6 @@ import { resolveSeed } from '../lib/seed-resolver.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { header, keyValue, divider, formatDust, successMessage, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -101,7 +100,7 @@ async function dustExport( ): Promise { const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); try { - const result = await (await engineFor(networkName, ctx.config.paths.stateRoot)).wallet.exportDust(seedBuffer, networkName, networkConfig, { + const result = await (await ctx.host.engines.for(networkName)).wallet.exportDust(seedBuffer, networkName, networkConfig, { root: ctx.config.paths.stateRoot, notice: ctx.host.notice, signal: ctx.signal, @@ -261,7 +260,7 @@ async function dustRegister( const spinner = ctx.progress.start('Syncing wallet...'); try { - const result = await (await engineFor(network, ctx.config.paths.stateRoot)).wallet.registerDust(seedBuffer, networkConfig, { + const result = await (await ctx.host.engines.for(network)).wallet.registerDust(seedBuffer, networkConfig, { root: ctx.config.paths.stateRoot, notice: ctx.host.notice, signal: ctx.signal, @@ -324,7 +323,7 @@ async function dustStatusDirect( const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); try { - const view = await (await engineFor(network, ctx.config.paths.stateRoot)).wallet.dustBalance(seedBuffer, networkConfig, { + const view = await (await ctx.host.engines.for(network)).wallet.dustBalance(seedBuffer, networkConfig, { root: ctx.config.paths.stateRoot, notice: ctx.host.notice, forceFresh: !useCache, diff --git a/src/commands/generate.ts b/src/commands/generate.ts index 644a74f3..b918e2a5 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -8,7 +8,6 @@ import * as path from 'path'; import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { passphraseForNewSecret } from '../lib/passphrase.ts'; @@ -67,7 +66,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic)); } - const addresses = (await engineFor(networkName, root)).keys.unshieldedAddresses(seedBuffer); + const addresses = (await ctx.host.engines.for(networkName)).keys.unshieldedAddresses(seedBuffer); const activeAddress = addresses[networkName]; const config: WalletPublic = { diff --git a/src/commands/genesis-address.ts b/src/commands/genesis-address.ts index e1d36842..2ec98618 100644 --- a/src/commands/genesis-address.ts +++ b/src/commands/genesis-address.ts @@ -2,7 +2,6 @@ import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -12,7 +11,7 @@ export default async function genesisAddressCommand(args: ParsedArgs, ctx: CallC const root = ctx.config.paths.stateRoot; const networkName = resolveNetworkName({ args, configDir: root }); const seedBuffer = Buffer.from(GENESIS_SEED, 'hex'); - const address = (await engineFor(networkName, root)).keys.unshieldedAddress(seedBuffer, networkName); + const address = (await ctx.host.engines.for(networkName)).keys.unshieldedAddress(seedBuffer, networkName); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index 67a575fd..b5909248 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -8,7 +8,7 @@ async function checkGrant(params: Readonly>, call: ToolC const root = call.host.paths().stateRoot; const prepared = await prepareGrant(call.argv(), root, call.host); const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); - await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined)); + await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined), call.host.engines); return prepared; } diff --git a/src/commands/grant.ts b/src/commands/grant.ts index dec5c296..cbc8db89 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -256,7 +256,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, await addOwnerDevice(await ownerSession(), named.attestation); const added = identityCodeOf(request.code); devices.write([...known.filter((code) => identityCodeOf(code) !== added), added]); - const written = request.backup === undefined ? undefined : await exportAccount(recordsDir, target.network, passphrase, request.backup, { forDevice: named }); + const written = request.backup === undefined ? undefined : await exportAccount(recordsDir, target.network, passphrase, request.backup, ctx.host.engines, { forDevice: named }); spinner.stop('Device added'); if (jsonMode) { ctx.output.result({ ...common, action: 'add', code: added, ...(written === undefined ? {} : { backup: written.file }) }); @@ -281,7 +281,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, case 'export': { const { exportAccount } = await import('../lib/grant/account-backup.ts'); const { unlockPassphrase } = await import('../lib/passphrase.ts'); - const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(ctx.host, target.root), request.file); + const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(ctx.host, target.root), request.file, ctx.host.engines); spinner.stop('Written'); if (jsonMode) { ctx.output.result({ ...common, address: outcome.contractAddress, file: outcome.file }); diff --git a/src/commands/info.ts b/src/commands/info.ts index 9c15f613..df7c6b45 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -12,7 +12,7 @@ import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context' export default async function infoCommand(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; const resolvedPath = resolveWalletPath(root, getFlag(args, 'wallet')); - const config = await loadWalletConfig(resolvedPath); + const config = await loadWalletConfig(resolvedPath, ctx.host.engines); const activeNetwork = resolveNetworkName({ args, configDir: root }); const activeAddress = await walletAddress(resolvedPath, activeNetwork, root, ctx.host); diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 4a020392..8cac9161 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -8,7 +8,6 @@ import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { fetchLedgerParameters } from '../lib/chain-params.ts'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; const UNITS: Record = { @@ -25,7 +24,7 @@ export default async function inspectCostCommand(args: ParsedArgs, ctx: CallCont // A ledger-8 chain's parameters aren't ledger-9 ones: refuse it like every other chain read. await assertLedgerSupported(networkName, config, fetchProtocolVersion, ctx.signal); const { height, parametersHex } = await fetchLedgerParameters(config.indexer, ctx.signal); - const limits = (await engineFor(networkName, root)).ledger.blockLimits(parametersHex); + const limits = (await ctx.host.engines.for(networkName)).ledger.blockLimits(parametersHex); // JSON mode if (hasFlag(args, 'json')) { diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index 81e3b827..df9cb2e5 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -72,14 +72,13 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) const { waitForAddressFunded } = await import('@kuiralabs/midnight-chain/lib/indexer-ready'); const { waitForProofServerReady } = await import('@kuiralabs/midnight-chain/lib/proof-server-ready'); const { getNetworkConfig } = await import('@kuiralabs/midnight-cli-core/lib/network'); - const { engineFor } = await import('@kuiralabs/midnight-cli-core/lib/engine'); const { GENESIS_SEED } = await import('@kuiralabs/midnight-cli-core/lib/constants'); const netCfg = getNetworkConfig('undeployed'); await waitForFirstBlock(netCfg.node, { timeoutMs: 30_000, signal: ctx.signal }); spinner.update('Waiting for indexer to ingest genesis state...'); - const genesisAddress = (await engineFor('undeployed', docker.root)).keys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const genesisAddress = (await ctx.host.engines.for('undeployed')).keys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); await waitForAddressFunded(netCfg.indexerWS, genesisAddress, { timeoutMs: 30_000, signal: ctx.signal }); spinner.update('Waiting for proof server...'); diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 69370f79..52915de5 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -6,7 +6,7 @@ import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuir import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; -import { engineFor, type DAppConnector, type DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; import type { PhaseTiming } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; @@ -101,7 +101,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): // preview/preprod). dApps there can only do unshielded + dust anyway. const syncMode = shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded')) ? 'full' : 'lite'; - await (await engineFor(networkName, root)).wallet.serveWallet({ seed: seedBuffer, root, notice: ctx.host.notice, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, + await (await ctx.host.engines.for(networkName)).wallet.serveWallet({ seed: seedBuffer, root, notice: ctx.host.notice, networkConfig, network: networkName, address, syncMode, signal: ctx.signal, log: ctx.diagnostics.line, onStatus: (s) => spinner.update(s), onSyncProgress: (applied, highest) => { if (highest > 0) { diff --git a/src/commands/swap.ts b/src/commands/swap.ts index b9bc91cf..004c0bc7 100644 --- a/src/commands/swap.ts +++ b/src/commands/swap.ts @@ -46,7 +46,7 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); try { const spinner = spinnerFor('Making the offer (proving its half)...'); - const made = await makeOffer(session, root, address, terms, expiresAt, now); + const made = await makeOffer(session, await ctx.host.engines.for(session.network), root, address, terms, expiresAt, now); const file = out ?? `offer-${made.envelope.id.slice(0, 16)}.json`; writeFileSync(file, made.file, { flag: 'wx' }); spinner.stop('Offer made'); diff --git a/src/commands/test.ts b/src/commands/test.ts index 6a8ef682..72e63930 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -562,6 +562,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): let currentAction: import('../lib/test/types.ts').TestAction | undefined; const actionResults = await runActions({ root: ctx.config.paths.stateRoot, + engines: ctx.host.engines, actions: actionsConfig.actions, config, dappDir, diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index c947ab7b..93505ed0 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -7,7 +7,6 @@ import { saveShieldedAddress, unlockWallet } from '../lib/wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; import { resolveTransferRequest, type TransferRequest } from '../lib/transfer-request.ts'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -50,7 +49,7 @@ async function unshieldedTransfer( const spinner = ctx.progress.start('Starting wallet...'); try { - const result = await (await engineFor(networkName, root)).wallet.transfer({ + const result = await (await ctx.host.engines.for(networkName)).wallet.transfer({ root, notice: ctx.host.notice, seedBuffer, @@ -150,7 +149,7 @@ async function shieldedTransfer( const spinner = ctx.progress.start('Syncing wallet...'); try { - const txHash = await (await engineFor(networkName, root)).wallet.shieldedTransfer({ + const txHash = await (await ctx.host.engines.for(networkName)).wallet.shieldedTransfer({ seed: seedBuffer, root, notice: ctx.host.notice, diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index 37321ad3..ef059176 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -87,7 +87,7 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise // Cancelled while the passphrase was asked for: no wallet is written, and no new passphrase saved. throwIfCancelled(ctx.signal); // Checked above: an existing wallet is replaced only with --force. - const created = await createWallet(root, name, secret, passphrase, { overwrite: hasFlag(args, 'force') }); + const created = await createWallet(root, name, secret, passphrase, await ctx.host.engines.any(), { overwrite: hasFlag(args, 'force') }); const { addresses, shieldedAddresses, mnemonic, file: savedPath } = created; const seedBuffer = created.seed; const activeAddress = addresses[networkName]; @@ -141,7 +141,7 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise async function walletList(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; - const wallets = await listWallets(root); + const wallets = await listWallets(root, ctx.host.engines); const networkName = resolveNetworkName({ args, configDir: root }); if (hasFlag(args, 'json')) { @@ -237,7 +237,7 @@ async function walletInfo(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; const name = getFlag(args, 'wallet') ?? args.positionals[0] ?? getActiveWalletName(root); const walletPath = resolveWalletPath(root, name); - const config = await loadWalletConfig(walletPath); + const config = await loadWalletConfig(walletPath, ctx.host.engines); const isActive = name === getActiveWalletName(root); const networkName = resolveNetworkName({ args, configDir: root }); const activeAddress = await walletAddress(walletPath, networkName, root, ctx.host); @@ -393,14 +393,14 @@ async function walletProtect(args: ParsedArgs, ctx: WalletCommandContext): Promi const root = ctx.config.paths.stateRoot; const passphrase = await passphraseForNewSecret(ctx.host, root, { signal: ctx.signal }); // Cancelled, it stops between wallets and before a protector, never in the middle of a file. - const report = await protectAllWallets(root, passphrase, ctx.signal); + const report = await protectAllWallets(root, passphrase, ctx.host.engines, ctx.signal); const sealed = report.filter((w) => w.sealedNow).map((w) => w.name); const alreadySealed = report.filter((w) => !w.sealedNow).map((w) => w.name); // What other domains keep for a wallet, sealed by the protectors the caller gave; each is told how to get a wallet's coin key. const results: Array<{ name: string; result: ProtectorResult }> = []; for (const protector of ctx.protectors ?? []) { throwIfCancelled(ctx.signal); - results.push({ name: protector.name, result: await protector.protect(root, passphrase, (wallet) => coinKeyOfWallet(root, ctx.host, wallet)) }); + results.push({ name: protector.name, result: await protector.protect(root, passphrase, (wallet) => coinKeyOfWallet(root, ctx.host, wallet), ctx.host.engines) }); } if (hasFlag(args, 'json')) { ctx.output.result({ sealed, alreadySealed, ...Object.fromEntries(results.map(({ name, result }) => [name, result.report])) }); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index d0e8e1c0..9f1e9701 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -15,14 +15,13 @@ import { installSdkNoiseFilters } from './sdk-noise.ts'; import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { bridgeEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from './installed-engines.ts'; /** * The CLI's host, or the MCP server's (`prompter` null: no terminal there). - * Until every library takes the host it is given, the module-level sources - * they still read are set from it. + * Until every library takes the host's settings, the module-level settings + * source they still read is set from it. */ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host { const host = createHost({ @@ -34,7 +33,5 @@ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host engineLoader: loadInstalledEngine, }); setSettingsSource(host.settings); - // The libraries that don't take the host's engines yet reach these, so the process has one engine. - bridgeEngines(host.engines); return host; } diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index 3d47e34a..67c49038 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -37,6 +37,7 @@ export async function callContract({ request, target, wallet, payer, progress, s dappDir, network: target.network, root: target.root, + engines: target.host.engines, networkConfig: target.networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index 975ee365..9d56225d 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -35,6 +35,7 @@ export async function deployContract({ request, target, wallet, payer, progress, dappDir, network: target.network, root: target.root, + engines: target.host.engines, networkConfig: target.networkConfig, managedDir: info.managedDir, contractName: info.name, diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index de882468..56ad6d15 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -13,7 +13,7 @@ import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { engineFor, type EngineContractScripts, type ScriptParts } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { sdkSetOf, type EngineContractScripts, type HostEngines, type ScriptParts } from '@kuiralabs/midnight-cli-core/lib/engine'; import { findContractInfo } from './inspect.ts'; import { assertContractRunsOn } from './runtime-check.ts'; import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; @@ -35,6 +35,8 @@ export interface RunnerOptions { network: NetworkName; /** The state root whose config names the network's SDK set. */ root: string; + /** The engines of the host the run is in: the network's engine writes the script. */ + engines: HostEngines; networkConfig: NetworkConfig; managedDir: string; contractName: string; @@ -75,6 +77,8 @@ export interface StateOptions { network: NetworkName; /** The state root whose config names the network's SDK set. */ root: string; + /** The engines of the host the run is in: the network's engine writes the script. */ + engines: HostEngines; networkConfig: NetworkConfig; managedDir: string; contractName: string; @@ -115,8 +119,8 @@ export function indexerEnvironment(networkConfig: NetworkConfig): Record { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); - await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root); - const engine = await engineFor(options.network, options.root); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root, options.engines); + const engine = await options.engines.load(sdkSetOf(options.network, options.root)); const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.state(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); @@ -130,8 +134,8 @@ export async function runState(options: StateOptions): Promise { export async function runDeploy(options: DeployOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); - await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root); - const engine = await engineFor(options.network, options.root); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root, options.engines); + const engine = await options.engines.load(sdkSetOf(options.network, options.root)); const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.deploy(options, SCRIPT_PARTS); // The private-state secret goes to the subprocess via env (never the on-disk @@ -151,8 +155,8 @@ export async function runDeploy(options: DeployOptions): Promise { export async function runCall(options: CallOptions): Promise { // Every run, whoever starts it (dev, test, a program): the contract must suit the network's engine. throwIfCancelled(options.signal); - await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root); - const engine = await engineFor(options.network, options.root); + await assertContractRunsOn(findContractInfo(options.managedDir).info, options.network, options.root, options.engines); + const engine = await options.engines.load(sdkSetOf(options.network, options.root)); const scripts = { ...engine.contracts.scripts, set: engine.set }; const script = scripts.call(options, SCRIPT_PARTS); const result = await executeScript({ dir: options.dappDir, script, packages: scripts, onMessage: options.onMessage, env: indexerEnvironment(options.networkConfig), signal: options.signal }); diff --git a/src/lib/contract/runtime-check.ts b/src/lib/contract/runtime-check.ts index 245ce44e..d193dccb 100644 --- a/src/lib/contract/runtime-check.ts +++ b/src/lib/contract/runtime-check.ts @@ -4,20 +4,20 @@ // its script after the wallet has synced ("Version mismatch"). import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { sdkSetOf, type HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import type { ContractInfo } from './inspect.ts'; /** - * Throws a UsageError unless the engine for `network` (by the config under - * the state root `root`) runs a contract + * Throws a UsageError unless the engine of `engines` for `network` (by the + * config under the state root `root`) runs a contract * compiled for `info.runtimeVersion`. A contract from a compiler that records * no runtime version is let through: its own code checks the runtime when it * loads. */ -export async function assertContractRunsOn(info: Pick, network: NetworkName, root: string): Promise { +export async function assertContractRunsOn(info: Pick, network: NetworkName, root: string, engines: HostEngines): Promise { if (info.runtimeVersion === 'unknown') return; - const { scripts } = (await engineFor(network, root)).contracts; + const { scripts } = (await engines.load(sdkSetOf(network, root))).contracts; if (scripts.acceptsRuntime(info.runtimeVersion)) return; throw new UsageError( `${info.name} was compiled by compactc ${info.compilerVersion} for compact-runtime ${info.runtimeVersion}, ` + diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 341604f3..c2b63a42 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -7,7 +7,7 @@ import { existsSync } from 'node:fs'; import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet, type UnlockHost } from '../wallet-config.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; import { passphraseForNewSecret } from '../passphrase.ts'; -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; @@ -54,7 +54,7 @@ function walletSteps(root: string, host: UnlockHost, network: NetworkConfig, sdk generate: (name, signal) => generateWallet(root, host, name, signal), airdrop: (name, amountNight, signal) => airdropToWallet(root, host, network, name, amountNight, signal, sdkWarnings), registerDust: (name, signal) => registerWalletDust(root, host, network, name, signal, sdkWarnings), - needsDust: (name, signal) => walletNeedsDust(root, network, name, signal), + needsDust: (name, signal) => walletNeedsDust(root, host, network, name, signal), }; } @@ -151,22 +151,22 @@ async function generateWallet(root: string, host: UnlockHost, name: string, sign const passphrase = await passphraseForNewSecret(host, root); // Cancelled while the passphrase was asked for: no wallet is written. throwIfCancelled(signal); - await createWallet(root, name, walletSecretFrom(), passphrase); + await createWallet(root, name, walletSecretFrom(), passphrase, await host.engines.any()); } async function airdropToWallet(root: string, host: UnlockHost, network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { - const recipientAddress = (await loadWalletConfig(resolveWalletPath(root, name))).addresses.undeployed; + const recipientAddress = (await loadWalletConfig(resolveWalletPath(root, name), host.engines)).addresses.undeployed; // dev's wallets live on the local chain. - await (await engineFor('undeployed', root)).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings, root, notice: host.notice }); + await (await host.engines.load(sdkSetOf('undeployed', root))).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings, root, notice: host.notice }); } -async function walletNeedsDust(root: string, network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { - const address = (await loadWalletConfig(resolveWalletPath(root, name))).addresses.undeployed; +async function walletNeedsDust(root: string, host: UnlockHost, network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { + const address = (await loadWalletConfig(resolveWalletPath(root, name), host.engines)).addresses.undeployed; const { registeredUtxos, unregisteredUtxos } = await checkBalance(address, network.indexerWS, undefined, signal); return registeredUtxos === 0 && unregisteredUtxos > 0; } async function registerWalletDust(root: string, host: UnlockHost, network: NetworkConfig, name: string, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { const { seed } = await unlockWallet(resolveWalletPath(root, name), { root, host }); - await (await engineFor('undeployed', root)).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings, root, notice: host.notice }); + await (await host.engines.load(sdkSetOf('undeployed', root))).wallet.registerDust(Buffer.from(seed, 'hex'), network, { signal, sdkWarnings, root, notice: host.notice }); } diff --git a/src/lib/grant/account-backup.ts b/src/lib/grant/account-backup.ts index 4c4f0283..0901b46b 100644 --- a/src/lib/grant/account-backup.ts +++ b/src/lib/grant/account-backup.ts @@ -10,7 +10,7 @@ // a second device (`midnight grant device add`). import * as fs from 'node:fs'; -import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { type OwnerRecord, type Roster, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; @@ -84,9 +84,10 @@ const sealedAccountIn = (dir: string, passphrase: string) => { * Writes the account in `dir` on `network` to `file`, sealed under * `passphrase`. Never over a file that exists. With `forDevice`, the backup * is for that device, just added to the account: it carries everything but - * this machine's owner key. + * this machine's owner key. Its private-state password is read under the + * policy of an engine of `engines`. */ -export async function exportAccount(dir: string, network: string, passphrase: string, file: string, { forDevice }: { forDevice?: DeviceIdentity } = {}): Promise<{ contractAddress: string; file: string }> { +export async function exportAccount(dir: string, network: string, passphrase: string, file: string, engines: HostEngines, { forDevice }: { forDevice?: DeviceIdentity } = {}): Promise<{ contractAddress: string; file: string }> { const key = sealedAccountIn(dir, passphrase); const record = sealedOwnerStore(dir, key).readOwner(); const device = sealedDeviceKeys(dir, key).read(); @@ -97,7 +98,7 @@ export async function exportAccount(dir: string, network: string, passphrase: st roster: sealedOwnerStore(dir, key).readRoster(), ...(forDevice === undefined ? { device: { arm: device.arm, secret: device.secretText(), readSecret: Buffer.from(sealedDeviceReadSecret(dir, key)).toString('hex') } } : {}), devices: [...new Set([...knownDevices(dir, key, device), ...(forDevice === undefined ? [] : [deviceCodeOf(forDevice, forDevice.readKey)])])], - privateStatePassword: sealedPrivateStatePassword(dir, key, (await anyEngine()).contracts.acceptsPrivateStatePassword), + privateStatePassword: sealedPrivateStatePassword(dir, key, (await engines.any()).contracts.acceptsPrivateStatePassword), privateState: fs.existsSync(database) ? Object.fromEntries(filesUnder(database).map((f) => [f, fs.readFileSync(path.join(database, f)).toString('base64')])) : {}, }; const backup: AccountBackupFile = { diff --git a/src/lib/grant/account-protector.ts b/src/lib/grant/account-protector.ts index f879b024..e6943e02 100644 --- a/src/lib/grant/account-protector.ts +++ b/src/lib/grant/account-protector.ts @@ -7,9 +7,9 @@ import type { WalletProtector } from '../wallet-protector.ts'; export const accountProtector: WalletProtector = { name: 'accounts', - async protect(root, passphrase, coinKeyOf) { + async protect(root, passphrase, coinKeyOf, engines) { const { protectAllAccounts } = await import('./protect-account.ts'); - const report = await protectAllAccounts(root, passphrase, coinKeyOf); + const report = await protectAllAccounts(root, passphrase, coinKeyOf, engines); return { report, items: report.map((account) => { diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 76db2a0e..15f56410 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -8,7 +8,6 @@ // owner key) and roster.json, with the private state in the directory's // midnight-level-db under the store name and password it was first made with. -import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; import { join } from 'node:path'; import { artefactCache } from '@kuiralabs/midnight-account-chain/artefacts'; import { type AccountContext, type ProgressEvent, accountContext, describeProgress, networkOf } from '@kuiralabs/midnight-account-chain/context'; @@ -130,7 +129,7 @@ export interface GrantAccount { export interface OpenAccountOptions { /** The state root holding mn's passphrase check and the proving artefacts. */ root: string; - /** The host: who is asked for the passphrase, the passphrase it has unlocked, and its notices. */ + /** The host: who is asked for the passphrase, the passphrase it has unlocked, its notices, and its engines (whose policy the private-state password meets). */ host: UnlockHost; source?: PassphraseSource; warn?: (line: string) => void; @@ -150,7 +149,7 @@ export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: const context = accountContext({ network, artefacts: artefactCache(accountArtifactsDir(root), { progress }), progress }); const database = join(recordsDir, PRIVATE_STATE_DATABASE); // The account's private state is midnight-js's, which the engine's policy checks a new password against. - const { contracts } = await anyEngine(); + const { contracts } = await options.host.engines.any(); const sealed = (key: Buffer): GrantAccount => ({ context, diff --git a/src/lib/grant/protect-account.ts b/src/lib/grant/protect-account.ts index 1c286ab8..cbe2f285 100644 --- a/src/lib/grant/protect-account.ts +++ b/src/lib/grant/protect-account.ts @@ -13,7 +13,7 @@ // never opened under the public password its private state has left. import * as fs from 'node:fs'; -import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { changePrivateStatePassword, directoryOwnerStore, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; @@ -45,10 +45,11 @@ const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.str /** * Seals the account in `dir` under `passphrase`, if it is in plain text. Its * private state is scoped to the paying wallet's shielded coin public key, - * `coinPublicKey` (hex). `stopBeforeSealing` stops after step 4, as an - * interrupted run would, for the tests. + * `coinPublicKey` (hex); its new password is one an engine of `engines` + * accepts. `stopBeforeSealing` stops after step 4, as an interrupted run + * would, for the tests. */ -export async function protectAccount(dir: string, passphrase: string, coinPublicKey: string, { stopBeforeSealing = false }: { stopBeforeSealing?: boolean } = {}): Promise { +export async function protectAccount(dir: string, passphrase: string, coinPublicKey: string, engines: HostEngines, { stopBeforeSealing = false }: { stopBeforeSealing?: boolean } = {}): Promise { if (isSealedAccount(dir)) { // A run that stopped after sealing, before the plain text was removed. for (const file of [PLAIN_OWNER_FILE, PLAIN_ROSTER_FILE]) fs.rmSync(path.join(dir, file), { force: true }); @@ -73,7 +74,7 @@ export async function protectAccount(dir: string, passphrase: string, coinPublic if (device !== undefined && keys.read() === undefined) keys.keep(device); // 3 - const password = sealedPrivateStatePassword(dir, key, (await anyEngine()).contracts.acceptsPrivateStatePassword); + const password = sealedPrivateStatePassword(dir, key, (await engines.any()).contracts.acceptsPrivateStatePassword); const location = privateStateLocationOf(dir, () => LEGACY_STORE_PASSWORD); if (record !== undefined && fs.existsSync(location.database)) { await changePrivateStatePassword({ getCoinPublicKey: () => coinPublicKey }, record.contractAddress, location, () => password); @@ -100,10 +101,11 @@ export type ProtectedAccount = /** * Seals every plain-text account under the state root `stateRootDir`, in network and wallet order. * `coinKeyOf` names the shielded coin public key of the wallet an account - * belongs to. An account that cannot be sealed is named with why, and the - * others are still sealed. + * belongs to; `engines` are the host's, as protectAccount takes them. An + * account that cannot be sealed is named with why, and the others are still + * sealed. */ -export async function protectAllAccounts(stateRootDir: string, passphrase: string, coinKeyOf: (wallet: string) => Promise): Promise { +export async function protectAllAccounts(stateRootDir: string, passphrase: string, coinKeyOf: (wallet: string) => Promise, engines: HostEngines): Promise { const root = path.join(stateRootDir, ACCOUNTS_DIR_NAME); const report: ProtectedAccount[] = []; const dirsIn = (dir: string): string[] => (fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort() : []); @@ -114,8 +116,8 @@ export async function protectAllAccounts(stateRootDir: string, passphrase: strin if (fs.readdirSync(dir).length === 0) continue; try { const outcome = isSealedAccount(dir) - ? await protectAccount(dir, passphrase, '') - : await protectAccount(dir, passphrase, await coinKeyOf(wallet)); + ? await protectAccount(dir, passphrase, '', engines) + : await protectAccount(dir, passphrase, await coinKeyOf(wallet), engines); if (outcome !== 'nothing') report.push({ network, wallet, outcome }); } catch (error) { report.push({ network, wallet, error: error instanceof Error ? error.message : String(error) }); diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 571b164f..99896c32 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -7,7 +7,7 @@ import { Socket } from 'node:net'; import { resolveWalletPath, unlockWallet, walletAddress, type UnlockHost } from './wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { engineFor, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { sdkSetOf, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; @@ -248,7 +248,7 @@ export async function openConnector(options: ServeManagerOptions): Promise { const { openConnector } = await import('./serve-manager.ts'); - const engine = await engineFor(network, root); + const engine = await host.engines.load(sdkSetOf(network, root)); const open = () => openConnector({ root, host, network, endpoints, wallet, onMessage: (msg) => progress.update(msg), dustWaitMs: OWN_COMMAND_DUST_WAIT_MS, sdkWarnings, forceShielded: options.shielded, signal }); return sessionOver(network, await open(), (tx, stage) => engine.ledger.readTransaction(tx, stage), { reopen: open, onMessage: (msg) => progress.update(msg) }); } diff --git a/src/lib/swap/offers.ts b/src/lib/swap/offers.ts index 9a42f0d3..e6aae0dc 100644 --- a/src/lib/swap/offers.ts +++ b/src/lib/swap/offers.ts @@ -5,7 +5,7 @@ // what the file says, that the terms are the agreed ones, that the maker's // expiry hasn't passed, and that none of its coins is spent. -import { engineFor } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { sdkSetOf, type Engine, type HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import type { WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; @@ -23,11 +23,11 @@ export interface MadeOffer { /** * Makes an offer with the session's wallet: its half of the swap, proved and - * signed, recorded among the wallet's open offers (under the state root - * `root`) so its later spends don't cancel it unawares. + * signed, read back by `engine` (the session network's), and recorded among + * the wallet's open offers (under the state root `root`) so its later spends + * don't cancel it unawares. */ -export async function makeOffer(session: WalletSession, root: string, walletAddress: string, terms: SwapTerms, expiresAt: Date, now: Date = new Date()): Promise { - const engine = await engineFor(session.network, root); +export async function makeOffer(session: WalletSession, engine: Engine, root: string, walletAddress: string, terms: SwapTerms, expiresAt: Date, now: Date = new Date()): Promise { const tx = await session.makeOffer(terms.give, terms.want); const read = engine.ledger.readOffer(tx); const envelope: OfferEnvelope = { network: session.network, id: read.id, terms: read.terms, expiresAt, tx }; @@ -41,13 +41,13 @@ export interface ReadOffer { contents: OfferContents; } -/** Reads an offer file's text for `network`, with the engine the config under the state root `root` gives it. Throws NotAnOfferError for anything that isn't one, or says other than its bytes. */ -export async function readOfferFile(root: string, text: string, network: NetworkName): Promise { +/** Reads an offer file's text for `network`, with the engine of `engines` the config under the state root `root` gives it. Throws NotAnOfferError for anything that isn't one, or says other than its bytes. */ +export async function readOfferFile(root: string, text: string, network: NetworkName, engines: HostEngines): Promise { const envelope = decodeOfferEnvelope(text); if (envelope.network !== network) { throw new UsageError(`The offer is for ${envelope.network}, not ${network}: take it on ${envelope.network} (--network ${envelope.network}).`); } - const contents = (await engineFor(network, root)).ledger.readOffer(envelope.tx); + const contents = (await engines.load(sdkSetOf(network, root))).ledger.readOffer(envelope.tx); assertEnvelopeMatches(envelope, contents); return { envelope, contents }; } diff --git a/src/lib/swap/request.ts b/src/lib/swap/request.ts index 97928366..f5be0b6e 100644 --- a/src/lib/swap/request.ts +++ b/src/lib/swap/request.ts @@ -64,7 +64,7 @@ export async function readOfferArg(args: ParsedArgs, target: PayingTarget): Prom } catch (err) { throw new UsageError(`Can't read the offer file ${file}: ${(err as Error).message}`); } - return readOfferFile(target.root, text, target.network); + return readOfferFile(target.root, text, target.network, target.host.engines); } /** A take, checked as far as it can be without the chain: the file, its network, the agreed terms and the expiry. */ diff --git a/src/lib/test/actions-runner.ts b/src/lib/test/actions-runner.ts index 69036c87..c772dd9a 100644 --- a/src/lib/test/actions-runner.ts +++ b/src/lib/test/actions-runner.ts @@ -4,6 +4,7 @@ import { existsSync, readFileSync } from 'node:fs'; import type { TestAction, DappTestConfig } from './types.ts'; import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import { runDeploy, runCall, runState, type StateResult } from '../contract/runner.ts'; import { findContractInfo, type ContractInfo } from '../contract/inspect.ts'; import { analyzeWitnessDependencies } from './circuit-witness-deps.ts'; @@ -33,6 +34,8 @@ export interface ActionResult { export interface ActionsRunnerOptions { /** The state root whose config names the network's SDK set. */ root: string; + /** The engines of the host the suite runs in: the network's engine runs each action's script. */ + engines: HostEngines; actions: TestAction[]; config: DappTestConfig; dappDir: string; @@ -50,7 +53,7 @@ export interface ActionsRunnerOptions { * Deploy address flows to subsequent call/state actions automatically. */ export async function runActions(options: ActionsRunnerOptions): Promise { - const { root, actions, config, dappDir, suiteName, networkConfig, servePort, redeploy, onActionStart, onActionComplete, onMessage } = options; + const { root, engines, actions, config, dappDir, suiteName, networkConfig, servePort, redeploy, onActionStart, onActionComplete, onMessage } = options; const results: ActionResult[] = []; // Load cached contract address (test replay). The address is only as good @@ -106,6 +109,7 @@ export async function runActions(options: ActionsRunnerOptions): Promise { callbacks.onMessage(`SDK: ${msg}`); }); @@ -177,7 +177,7 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre // Keep the SDK's transient errors and RPC noise off the terminal while this runs. const stopListening = ctx.sdkWarnings.listen(undefined); try { - const { dustAvailable } = await (await engineFor(network, ctx.root)).wallet.prepDust( + const { dustAvailable } = await (await ctx.host.engines.load(sdkSetOf(network, ctx.root))).wallet.prepDust( { seed: seedBuffer, root: ctx.root, notice: ctx.host.notice, network, networkConfig, address, signal: ctx.signal, onMessage: callbacks.onMessage }, DUST_WAIT_TIMEOUT_MS, ); diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 68f82818..593b2c17 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -6,7 +6,7 @@ import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/ import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { loadWalletConfig, resolveWalletPath, walletAddress, walletShieldedAddress, type UnlockHost, type WalletConfig } from './wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { engineFor, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { sdkSetOf, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; @@ -21,7 +21,7 @@ export interface TransferRequest { shielded: boolean; } -/** `transfer [--shielded] [--wallet] [--network]`, checked without touching the chain, against the wallets and config under the state root `root`; a sealed recipient wallet is unlocked through `host`. */ +/** `transfer [--shielded] [--wallet] [--network]`, checked without touching the chain, against the wallets and config under the state root `root`; a sealed recipient wallet is unlocked through `host`, and the recipient checked by its engine for the network. */ export async function resolveTransferRequest(args: ParsedArgs, root: string, host: UnlockHost): Promise { const recipientInput = args.subcommand; const amountStr = args.positionals[0]; @@ -47,7 +47,7 @@ export async function resolveTransferRequest(args: ParsedArgs, root: string, hos const recipientAddress = await resolveRecipient(recipientInput, args, shielded, root, host); const amountNight = parseAmount(amountStr); const walletPath = resolveWalletPath(root, getFlag(args, 'wallet')); - const walletConfig = await loadWalletConfig(walletPath); + const walletConfig = await loadWalletConfig(walletPath, host.engines); const networkName = resolveNetworkName({ args, configDir: root }); if (shielded) { @@ -55,7 +55,7 @@ export async function resolveTransferRequest(args: ParsedArgs, root: string, hos throw new Error(shieldedDisabledReason(networkName)); } } - assertRecipient((await engineFor(networkName, root)).keys, recipientAddress, shielded, networkName); + assertRecipient((await host.engines.load(sdkSetOf(networkName, root))).keys, recipientAddress, shielded, networkName); return { walletPath, walletConfig, networkName, recipientAddress, amountNight, shielded }; } diff --git a/src/lib/wallet-can-pay.ts b/src/lib/wallet-can-pay.ts index 821f6605..7622c94a 100644 --- a/src/lib/wallet-can-pay.ts +++ b/src/lib/wallet-can-pay.ts @@ -21,8 +21,8 @@ export async function assertWalletCanPay({ network, root, host, networkConfig }: const walletConfig = await unlockWallet(resolveWalletPath(root, wallet), { root, host }); const seedBuffer = Buffer.from(walletConfig.seed, 'hex'); const address = walletConfig.addresses[network as NetworkName]; - const { engineFor } = await import('@kuiralabs/midnight-cli-core/lib/engine'); - const { wallet: repo } = await engineFor(network, root); + const { sdkSetOf } = await import('@kuiralabs/midnight-cli-core/lib/engine'); + const { wallet: repo } = await host.engines.load(sdkSetOf(network, root)); try { // Two cheap reads through the repo: no facade, no proof server, no strict diff --git a/src/lib/wallet-config.ts b/src/lib/wallet-config.ts index 2f61afa2..e472dc1c 100644 --- a/src/lib/wallet-config.ts +++ b/src/lib/wallet-config.ts @@ -4,7 +4,7 @@ import { DEFAULT_WALLET_FILENAME, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, FILE_MO import { getValidNetworkNames, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { loadCliConfig, saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { getWalletsDir } from './wallet-paths.ts'; -import { anyEngine, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { EngineKeys, HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import { isSealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { FileExistsError, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; import { type PassphraseHost, type PassphraseSource, unlockPassphrase } from './passphrase.ts'; @@ -81,13 +81,13 @@ export function getAddress(config: WalletConfig, network: NetworkName): string { * saves it. */ export async function walletAddress(walletPath: string, network: NetworkName, root: string, host: UnlockHost): Promise { - const config = await loadWalletConfig(walletPath); + const config = await loadWalletConfig(walletPath, host.engines); return config.addresses[network] ?? (await unlockWallet(walletPath, { root, host })).addresses[network]; } /** A wallet's shielded address on `network`, unlocking a sealed wallet that has none saved yet (see walletAddress); undefined when the wallet keeps no shielded addresses. */ export async function walletShieldedAddress(walletPath: string, network: NetworkName, root: string, host: UnlockHost): Promise { - const config = await loadWalletConfig(walletPath); + const config = await loadWalletConfig(walletPath, host.engines); if (config.shieldedAddresses === undefined || config.shieldedAddresses[network] !== undefined) return config.shieldedAddresses?.[network]; return (await unlockWallet(walletPath, { root, host })).shieldedAddresses?.[network]; } @@ -97,12 +97,12 @@ function missingNetworks(map: Partial> | undefined): return (getValidNetworkNames() as NetworkName[]).filter((network) => typeof map?.[network] !== 'string' || map[network] === ''); } -/** The wallet's address maps with every network's address, derived from its seed where missing; null when none was missing. */ -async function completedAddresses(config: WalletConfig, seed: Buffer): Promise | null> { +/** The wallet's address maps with every network's address, derived from its seed (by an engine of `engines`) where missing; null when none was missing. */ +async function completedAddresses(config: WalletConfig, seed: Buffer, engines: HostEngines): Promise | null> { const lacksUnshielded = missingNetworks(config.addresses).length > 0; const lacksShielded = config.shieldedAddresses !== undefined && missingNetworks(config.shieldedAddresses).length > 0; if (!lacksUnshielded && !lacksShielded) return null; - const { keys } = await anyEngine(); + const { keys } = await engines.any(); return { // Saved addresses win: they are what the wallet has shown so far. addresses: { ...keys.unshieldedAddresses(seed), ...config.addresses }, @@ -170,16 +170,17 @@ export function setActiveWallet(root: string, name: string): void { } /** - * List all wallets in the wallets folder under the state root `root`. + * List all wallets in the wallets folder under the state root `root`; an old + * wallet's missing addresses are derived by an engine of `engines`. */ -export async function listWallets(root: string): Promise { +export async function listWallets(root: string, engines: HostEngines): Promise { const walletsDir = getWalletsDir(root); if (!fs.existsSync(walletsDir)) { return []; } // Only a plain-text wallet's missing addresses are derived, and so need the SDK. let keys: EngineKeys | undefined; - const engineKeys = async (): Promise => (keys ??= (await anyEngine()).keys); + const engineKeys = async (): Promise => (keys ??= (await engines.any()).keys); const activeName = getActiveWalletName(root); const files = fs.readdirSync(walletsDir).filter(f => f.endsWith('.json')).sort(); @@ -261,8 +262,9 @@ export function matchWalletAddress( export async function findWalletByAddress( root: string, address: string, + engines: HostEngines, ): Promise<{ wallet: WalletInfo; network: NetworkName } | undefined> { - return matchWalletAddress(await listWallets(root), address); + return matchWalletAddress(await listWallets(root, engines), address); } /** @@ -324,9 +326,11 @@ export function assertWalletFileExists(resolvedPath: string): void { /** * Load wallet config from a file. * Throws with an actionable message if file is missing or invalid. - * Callers should use resolveWalletPath() to get the path first. + * Callers should use resolveWalletPath() to get the path first. A plain-text + * wallet's addresses missing from the file are derived by an engine of + * `engines`, and saved. */ -export async function loadWalletConfig(walletPath: string): Promise { +export async function loadWalletConfig(walletPath: string, engines: HostEngines): Promise { const resolvedPath = path.resolve(walletPath); assertWalletFileExists(resolvedPath); @@ -384,14 +388,14 @@ export async function loadWalletConfig(walletPath: string): Promise | undefined> { let derived: Record | undefined; - const { keys } = await anyEngine(); + const { keys } = await engines.any(); try { derived = keys.shieldedAddresses(seedBuffer); } catch { /* derivation can fail on malformed seeds */ } @@ -508,11 +513,12 @@ export function writeSealedWallet(walletPath: string, wallet: WalletPublic, secr /** * Seals a plain-text wallet in place under `passphrase`, keeping every other * field it holds. What was sealed is opened again before the file is - * replaced, so a wallet is never left unreadable. A sealed wallet is left as it is. + * replaced, so a wallet is never left unreadable. A sealed wallet is left as + * it is. Addresses the file lacks are derived by an engine of `engines` first. */ -export async function sealWalletInPlace(walletPath: string, passphrase: string): Promise { +export async function sealWalletInPlace(walletPath: string, passphrase: string, engines: HostEngines): Promise { const resolvedPath = path.resolve(walletPath); - const config = await loadWalletConfig(resolvedPath); + const config = await loadWalletConfig(resolvedPath, engines); if (config.isSealed) return false; const raw = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8')); const secrets: WalletSecrets = typeof raw.mnemonic === 'string' ? { seed: raw.seed, mnemonic: raw.mnemonic } : { seed: raw.seed }; @@ -535,8 +541,9 @@ export interface ProtectedWallet { * Seals every wallet under the state root `root` that is still in plain text, * under `passphrase`, in name order. Cancelled (`signal`), it stops between * wallets, never in the middle of one: the wallets sealed by then stay sealed. + * Addresses a wallet lacks are derived by an engine of `engines`. */ -export async function protectAllWallets(root: string, passphrase: string, signal?: AbortSignal): Promise { +export async function protectAllWallets(root: string, passphrase: string, engines: HostEngines, signal?: AbortSignal): Promise { const walletsDir = path.join(root, WALLETS_DIR_NAME); const files = fs.existsSync(walletsDir) ? fs.readdirSync(walletsDir).filter((f) => f.endsWith('.json')).sort() : []; // A wallet from before named wallets, if it was never moved into wallets/. @@ -548,13 +555,13 @@ export async function protectAllWallets(root: string, passphrase: string, signal // Sealing runs synchronously; a cancellation that came meanwhile lands here, before the next wallet. await new Promise((resolve) => setImmediate(resolve)); throwIfCancelled(signal); - report.push({ name, file, sealedNow: await sealWalletInPlace(file, passphrase) }); + report.push({ name, file, sealedNow: await sealWalletInPlace(file, passphrase, engines) }); } return report; } -/** What a wallet is unlocked through: the host's prompter and its record of the passphrase unlocked, its notices, and its record of the plain-text wallets warned about. */ -export type UnlockHost = PassphraseHost & Pick; +/** What a wallet is unlocked through: the host's prompter and its record of the passphrase unlocked, its notices, its record of the plain-text wallets warned about, and its engines, which derive the addresses a wallet lacks. */ +export type UnlockHost = PassphraseHost & Pick; /** How a wallet is unlocked: the state root holding mn's passphrase check, the host, where the passphrase comes from, and where a warning goes (the host's notices, unless given). */ export interface UnlockOptions { @@ -570,7 +577,7 @@ const WARNED_PLAIN = defineHostSlot('wallet-config.warnedPlain', () => new Set { const resolvedPath = path.resolve(walletPath); - const config = await loadWalletConfig(resolvedPath); + const config = await loadWalletConfig(resolvedPath, options.host.engines); const raw = JSON.parse(fs.readFileSync(resolvedPath, 'utf-8')); if (!config.isSealed) { const warnedPlain = options.host.slot(WARNED_PLAIN); @@ -586,7 +593,7 @@ export async function unlockWallet(walletPath: string, options: UnlockOptions): const secrets = JSON.parse(openSecret(raw.sealed, passphrase, 'wallet').toString('utf8')) as WalletSecrets; // A network added since the wallet was written: now that its seed is open, // derive that network's addresses and save them beside the sealed secrets. - const completed = await completedAddresses(config, Buffer.from(secrets.seed, 'hex')); + const completed = await completedAddresses(config, Buffer.from(secrets.seed, 'hex'), options.host.engines); if (completed) { Object.assign(config, completed); try { diff --git a/src/lib/wallet-create.ts b/src/lib/wallet-create.ts index 1ef4744c..9b3187db 100644 --- a/src/lib/wallet-create.ts +++ b/src/lib/wallet-create.ts @@ -6,7 +6,7 @@ import * as path from 'path'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { anyEngine } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; import { writeSealedWallet, setActiveWallet, type WalletPublic } from './wallet-config.ts'; import { isValidWalletName } from '@kuiralabs/midnight-cli-core/lib/constants'; import { getWalletsDir } from './wallet-paths.ts'; @@ -52,12 +52,12 @@ export function walletSecretFrom(given: { seed?: Buffer; mnemonic?: string } = { /** * Writes the wallet `name` sealed under `passphrase` under the state root - * `root` and makes it the active wallet. An existing wallet of that name is - * replaced only with `overwrite`. + * `root` and makes it the active wallet; `engine` derives its addresses. An + * existing wallet of that name is replaced only with `overwrite`. */ -export async function createWallet(root: string, name: string, secret: WalletSecret, passphrase: string, { overwrite = false }: { overwrite?: boolean } = {}): Promise { +export async function createWallet(root: string, name: string, secret: WalletSecret, passphrase: string, engine: Engine, { overwrite = false }: { overwrite?: boolean } = {}): Promise { const targetPath = walletFilePath(root, name); - const { keys } = await anyEngine(); + const { keys } = engine; const addresses = keys.unshieldedAddresses(secret.seed); const shieldedAddresses = keys.shieldedAddresses(secret.seed); const config: WalletPublic = { addresses, shieldedAddresses, createdAt: new Date().toISOString() }; diff --git a/src/lib/wallet-protector.ts b/src/lib/wallet-protector.ts index 1d1545b5..cee71249 100644 --- a/src/lib/wallet-protector.ts +++ b/src/lib/wallet-protector.ts @@ -3,6 +3,7 @@ // caller passes it in the call context: wallet never imports that domain. import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveWalletPath, unlockWallet, type UnlockHost } from './wallet-config.ts'; /** What protecting one item did: sealed now, already sealed, or why it could not be. */ @@ -22,17 +23,16 @@ export interface WalletProtector { name: string; /** * Seals what it keeps under the state root `root` with `passphrase`. `coinKeyOf` gives the - * shielded coin public key of a wallet, by name. + * shielded coin public key of a wallet, by name; `engines` are the host's, for what the SDK decides. */ - protect(root: string, passphrase: string, coinKeyOf: (wallet: string) => Promise): Promise; + protect(root: string, passphrase: string, coinKeyOf: (wallet: string) => Promise, engines: HostEngines): Promise; } /** The wallet command's call context: a command's, with the protectors `wallet protect` runs. */ export type WalletCommandContext = CallContext; -/** The shielded coin public key of the wallet `name` under the state root `root`, unlocked with mn's passphrase through `host`. */ +/** The shielded coin public key of the wallet `name` under the state root `root`, unlocked with mn's passphrase through `host` and derived by an engine of its. */ export async function coinKeyOfWallet(root: string, host: UnlockHost, name: string): Promise { // The engine loads the SDK, which the other wallet subcommands don't need: loaded here, not up front. - const { anyEngine } = await import('@kuiralabs/midnight-cli-core/lib/engine'); - return (await anyEngine()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(root, name), { root, host })).seed, 'hex')); + return (await host.engines.any()).keys.shieldedCoinPublicKeyHex(Buffer.from((await unlockWallet(resolveWalletPath(root, name), { root, host })).seed, 'hex')); } From 5bbec090f214e7c9174ea7bd69e887e94a904146 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 05:12:45 -0800 Subject: [PATCH 61/88] Settings come from the host; no library exports a setter (3B, 7 of 7) No library or command reads settings from module state: commands take them from their call's host, libraries as a parameter (resolveNetwork, detectLocalStacks, the Blockfrost id, the passphrase and seed readers). The settings source goes, and with it the tests' setupFile and its helper, shell-settings.ts: every test runs with a host of its own. The process-safety check gains a rule: no library, ui or command code exports a setter of host state; only claimSdkSet, the approved SDK-set guard, is allowed. Module state allowed: 2 (the chain-id memo and that guard), from 14 at the start of 3B. two-hosts.test.ts runs two hosts with their own state roots and settings through the dispatch in one process: config, wallets, the passphrase each keystore takes, and open offers stay apart, and neither reads process.env or HOME. Behaviour snapshot unchanged; suite 2581, beta 171; fresh install loads both engines; scratch chain swap 30/30, MCP swap 12/12, tx 25/25; stagenet (beta) balance and Dust status read. --- packages/chain/src/commands/status.ts | 13 +- packages/chain/src/commands/tx.ts | 2 +- packages/cli-core/api-report.md | 16 +- packages/cli-core/src/lib/network.ts | 14 +- packages/cli-core/src/lib/payer.ts | 2 +- packages/cli-core/src/lib/resolve-network.ts | 34 ++-- packages/cli-core/src/lib/settings.ts | 23 +-- packages/cli-core/src/lib/wallet-session.ts | 10 +- scripts/check-process-safety.d.mts | 5 +- scripts/check-process-safety.mjs | 96 ++++++++- src/__tests__/balance-command.live.test.ts | 2 +- src/__tests__/command-registry.test.ts | 3 +- src/__tests__/fixtures/record-swap-offer.ts | 3 +- src/__tests__/generate-command.test.ts | 6 +- src/__tests__/helpers/shell-settings.ts | 8 - src/__tests__/local-stacks.test.ts | 12 +- src/__tests__/process-safety.test.ts | 78 ++++++++ src/__tests__/resolve-network.test.ts | 48 ++--- src/__tests__/seed-resolver.test.ts | 7 +- src/__tests__/settings.test.ts | 87 +++++--- src/__tests__/state-root.test.ts | 4 +- src/__tests__/swap-request.test.ts | 7 +- src/__tests__/two-hosts.test.ts | 187 ++++++++++++++++++ src/__tests__/wallet-create.test.ts | 7 +- .../wallet-state-to-restore.live.test.ts | 2 +- src/commands/airdrop.ts | 2 +- src/commands/balance.ts | 4 +- src/commands/dev.ts | 2 +- src/commands/dust.ts | 2 +- src/commands/inspect-cost.ts | 2 +- src/commands/serve.ts | 2 +- src/commands/test.ts | 2 +- src/commands/transfer.ts | 4 +- src/lib/cli-host.ts | 17 +- src/lib/dev/localnet-ready.ts | 12 +- src/lib/dev/provision-wallets.ts | 10 +- src/lib/passphrase.ts | 29 +-- src/lib/seed-resolver.ts | 5 +- src/lib/serve-manager.ts | 2 +- src/lib/test/prep-runner.ts | 12 +- vitest.config.ts | 2 - 41 files changed, 576 insertions(+), 209 deletions(-) delete mode 100644 src/__tests__/helpers/shell-settings.ts create mode 100644 src/__tests__/two-hosts.test.ts diff --git a/packages/chain/src/commands/status.ts b/packages/chain/src/commands/status.ts index 1d54b184..58bd4702 100644 --- a/packages/chain/src/commands/status.ts +++ b/packages/chain/src/commands/status.ts @@ -9,7 +9,7 @@ import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/ import { DASHBOARD_BASE_URL } from '@kuiralabs/midnight-cli-core/lib/constants'; import { BlockfrostProjectIdRequiredError, assertEndpointUsable, endpointRefusal } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { isValidNetworkName, resolveNetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { resolveBlockfrostProjectId } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { resolveBlockfrostProjectId, type NetworkSettings } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim, teal, green, red, gray } from '@kuiralabs/midnight-cli-core/ui/colors'; @@ -297,10 +297,13 @@ async function probeExplorer(explorerUrl: string | null, signal: AbortSignal): P } /** The live probes of one network; a cancelled call's probes stop at once (their results then mean nothing). */ -async function runLocalProbes(networkName: string, root: string, signal: AbortSignal): Promise> { +async function runLocalProbes(networkName: string, root: string, settings: NetworkSettings, signal: AbortSignal): Promise> { if (!isValidNetworkName(networkName)) return {}; - const netConfig = resolveNetworkConfig(networkName as NetworkName, { blockfrostProjectId: resolveBlockfrostProjectId(networkName as NetworkName, root) }); + const netConfig = resolveNetworkConfig(networkName as NetworkName, { + isLocalDetectOff: settings.isLocalDetectOff, + blockfrostProjectId: resolveBlockfrostProjectId(networkName as NetworkName, root, settings), + }); const extra = EXTRA_ENDPOINTS[networkName]; if (!extra) return {}; @@ -412,7 +415,7 @@ export default async function statusCommand(args: ParsedArgs, ctx: CallContext): return null; }), // Local probes per network - ...targetNetworks.map(name => runLocalProbes(name, ctx.config.paths.stateRoot, ctx.signal)), + ...targetNetworks.map(name => runLocalProbes(name, ctx.config.paths.stateRoot, ctx.config.settings, ctx.signal)), ]); // Cancelled: the probes stopped early, so what they found says nothing about the network. @@ -523,7 +526,7 @@ export default async function statusCommand(args: ParsedArgs, ctx: CallContext): fetchJson('/api/status', ctx.signal), fetchJson('/api/issues', ctx.signal), ]).catch(() => null), - ...targetNetworks.map(name => runLocalProbes(name, ctx.config.paths.stateRoot, ctx.signal)), + ...targetNetworks.map(name => runLocalProbes(name, ctx.config.paths.stateRoot, ctx.config.settings, ctx.signal)), ]); // Watching ended while this refresh ran: nothing to show. if (ctx.signal.aborted) return; diff --git a/packages/chain/src/commands/tx.ts b/packages/chain/src/commands/tx.ts index 0962d7ca..e70a1200 100644 --- a/packages/chain/src/commands/tx.ts +++ b/packages/chain/src/commands/tx.ts @@ -27,7 +27,7 @@ export default async function txCommand(args: ParsedArgs, ctx: CallContext): Pro const ref = parseTxReference(given); const timeoutMs = timeoutMsOf(args); const jsonMode = hasFlag(args, 'json'); - const { name: network, config } = resolveNetwork({ args, configDir: ctx.config.paths.stateRoot }); + const { name: network, config } = resolveNetwork({ args, configDir: ctx.config.paths.stateRoot }, ctx.config.settings); const wait = hasFlag(args, 'wait'); const spinner = jsonMode ? ctx.progress.silent() : ctx.progress.start(wait ? 'Waiting for the indexer to list it...' : 'Asking the indexer...'); diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 915d1127..2c0cba02 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -1174,6 +1174,7 @@ export declare function openWithKey(key: Uint8Array, sealed: unknown, purpose: S ## `@kuiralabs/midnight-cli-core/lib/network` ```ts +import type { Settings } from "./settings.ts"; import type { SdkSet } from "./engine.ts"; export type NetworkName = "preprod" | "preview" | "stagenet" | "undeployed"; export declare const LEDGER_9_FORK_VERSION = 2000000n; @@ -1213,10 +1214,11 @@ export interface NeededComponents { proofServer: boolean; } export declare function pickLocalStack(found: LocalStackPorts, need?: NeededComponents): TestcontainerPorts; -export declare function detectLocalStacks(): LocalStackPorts; +export declare function detectLocalStacks(settings: Pick): LocalStackPorts; export interface ResolveNetworkConfigOptions { given?: EndpointOverrides; detect?: () => LocalStackPorts; + isLocalDetectOff?: boolean; blockfrostProjectId?: string; } export declare function resolveNetworkConfig(name: NetworkName, options?: ResolveNetworkConfigOptions): NetworkConfig; @@ -1385,15 +1387,17 @@ export declare function clearNativeDustCheckpoint(network: string | undefined, p ```ts import { type ParsedArgs } from "./argv.ts"; import { type NetworkName, type NetworkConfig } from "./network.ts"; -import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV } from "./settings.ts"; +import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV, type Settings } from "./settings.ts"; +export type BlockfrostSettings = Pick; +export type NetworkSettings = BlockfrostSettings & Pick; export interface NetworkResolutionContext { args: ParsedArgs; configDir: string; } export declare function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName; export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; -export declare function resolveBlockfrostProjectId(name: NetworkName, configDir: string, env?: Record): string | undefined; -export declare function resolveNetwork(ctx: NetworkResolutionContext): { +export declare function resolveBlockfrostProjectId(name: NetworkName, configDir: string, settings: BlockfrostSettings): string | undefined; +export declare function resolveNetwork(ctx: NetworkResolutionContext, settings: NetworkSettings): { name: NetworkName; config: NetworkConfig; }; @@ -1477,8 +1481,6 @@ export interface Settings { sharedBlockfrostProjectId: string | undefined; } export declare function settingsFromEnvironment(env: Record): Settings; -export declare function setSettingsSource(next: (() => Settings) | null): void; -export declare function settings(): Settings; ``` ## `@kuiralabs/midnight-cli-core/lib/shielded-policy` @@ -1599,6 +1601,7 @@ export declare function clearWalletCache(address: string | undefined, network: s import { type HostEngines, type OpenedConnector, type TransactionDetail } from "./engine.ts"; import type { NetworkConfig, NetworkName } from "./network.ts"; import type { NoticeSink } from "./notices.ts"; +import { type NetworkSettings } from "./resolve-network.ts"; import type { SwapLeg } from "./swap-offer.ts"; import type { OpenOffer } from "./open-offers.ts"; export interface WalletAddresses { @@ -1654,6 +1657,7 @@ export interface OpenWalletSessionOptions { notice: NoticeSink; engines: HostEngines; networkConfig?: NetworkConfig; + settings?: NetworkSettings; forceShielded?: boolean; dustWaitMs?: number; signal?: AbortSignal; diff --git a/packages/cli-core/src/lib/network.ts b/packages/cli-core/src/lib/network.ts index 4676eddf..7903c47c 100644 --- a/packages/cli-core/src/lib/network.ts +++ b/packages/cli-core/src/lib/network.ts @@ -2,7 +2,7 @@ import { blockfrostEndpoints, usesBlockfrost } from './blockfrost.ts'; import { execSync } from 'child_process'; import { loadCliConfig, getEndpointOverridesForNetwork, getSdkSetOverride } from './cli-config.ts'; import { INDEXER_GRAPHQL_PATH, INDEXER_GRAPHQL_WS_PATH } from './constants.ts'; -import { settings } from './settings.ts'; +import type { Settings } from './settings.ts'; import type { SdkSet } from './engine.ts'; export type NetworkName = 'preprod' | 'preview' | 'stagenet' | 'undeployed'; @@ -183,11 +183,11 @@ export function pickLocalStack(found: LocalStackPorts, need: NeededComponents = /** * Read the local Midnight containers from docker (empty when docker isn't - * available, or when MN_NO_LOCAL_DETECT=1 turns detection off and leaves - * undeployed on its default endpoints). + * available, or when the settings turn detection off (MN_NO_LOCAL_DETECT=1) + * and leave undeployed on its default endpoints). */ -export function detectLocalStacks(): LocalStackPorts { - if (settings().isLocalDetectOff) return { node: [], indexer: [], proofServer: [] }; +export function detectLocalStacks(settings: Pick): LocalStackPorts { + if (settings.isLocalDetectOff) return { node: [], indexer: [], proofServer: [] }; try { return parseLocalStacks(execSync('docker ps --format "{{.Image}}|{{.Ports}}"', { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })); } catch { @@ -200,6 +200,8 @@ export interface ResolveNetworkConfigOptions { given?: EndpointOverrides; /** Local stack detection (tests inject docker output). */ detect?: () => LocalStackPorts; + /** MN_NO_LOCAL_DETECT: don't look for a local stack (looked for when not given). */ + isLocalDetectOff?: boolean; /** The user's Blockfrost project id, for a network Blockfrost serves. */ blockfrostProjectId?: string; } @@ -221,7 +223,7 @@ export function resolveNetworkConfig(name: NetworkName, options: ResolveNetworkC proofServer: given.proofServer === undefined, }; if (name === 'undeployed' && (need.node || need.indexer || need.proofServer)) { - const detected = pickLocalStack((options.detect ?? detectLocalStacks)(), need); + const detected = pickLocalStack((options.detect ?? (() => detectLocalStacks({ isLocalDetectOff: options.isLocalDetectOff ?? false })))(), need); if (detected.indexerPort) { config.indexer = `http://localhost:${detected.indexerPort}${INDEXER_GRAPHQL_PATH}`; diff --git a/packages/cli-core/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts index 2d721628..6e0bcefc 100644 --- a/packages/cli-core/src/lib/payer.ts +++ b/packages/cli-core/src/lib/payer.ts @@ -41,7 +41,7 @@ export function resolvePayingTarget(args: ParsedArgs, command: string, subcomman const { name, config: networkConfig } = resolveNetwork({ args: { command, subcommand, positionals: [], flags: { ...(network ? { network } : {}), ...endpointFlags(endpoints) } }, configDir: root, - }); + }, host.settings()); applyEndpointOverrides(networkConfig, endpoints, name, root); return { network: name, root, host, networkConfig, endpoints }; } diff --git a/packages/cli-core/src/lib/resolve-network.ts b/packages/cli-core/src/lib/resolve-network.ts index 78be4c86..a1617285 100644 --- a/packages/cli-core/src/lib/resolve-network.ts +++ b/packages/cli-core/src/lib/resolve-network.ts @@ -14,7 +14,13 @@ import { } from './network.ts'; import { checkProjectId, networkOfProjectId, usesBlockfrost } from './blockfrost.ts'; import { getBlockfrostProjectId, loadCliConfig, getEndpointOverridesForNetwork } from './cli-config.ts'; -import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV, settings } from './settings.ts'; +import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV, type Settings } from './settings.ts'; + +/** The Blockfrost project ids the settings give (MN_BLOCKFROST_PROJECT_ID, then BLOCKFROST_PROJECT_ID). */ +export type BlockfrostSettings = Pick; + +/** The settings resolving a network reads: whether to look for a local stack, and the Blockfrost ids. */ +export type NetworkSettings = BlockfrostSettings & Pick; export interface NetworkResolutionContext { args: ParsedArgs; @@ -53,27 +59,20 @@ export function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName { export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; /** - * The Blockfrost project id for `name`: the environment's (mn's own variable, + * The Blockfrost project id for `name`: the settings' (mn's own variable, * then the shared one), else the one set with `midnight config set`. * Undefined on a network Blockfrost doesn't serve, and when none is set (a * command that then connects is told so). mn's own variable is checked; both * are used only for the network their id is for. */ -export function resolveBlockfrostProjectId( - name: NetworkName, - configDir: string, - env: Record = { - [BLOCKFROST_PROJECT_ID_ENV]: settings().blockfrostProjectId, - [SHARED_BLOCKFROST_PROJECT_ID_ENV]: settings().sharedBlockfrostProjectId, - }, -): string | undefined { +export function resolveBlockfrostProjectId(name: NetworkName, configDir: string, settings: BlockfrostSettings): string | undefined { if (!usesBlockfrost(name)) return undefined; - const own = env[BLOCKFROST_PROJECT_ID_ENV]?.trim(); + const own = settings.blockfrostProjectId?.trim(); if (own) { const { projectId, network } = checkProjectId(own); if (network === name) return projectId; } - const shared = env[SHARED_BLOCKFROST_PROJECT_ID_ENV]?.trim(); + const shared = settings.sharedBlockfrostProjectId?.trim(); if (shared && /^[A-Za-z0-9]+$/.test(shared) && networkOfProjectId(shared) === name) return shared; return getBlockfrostProjectId(loadCliConfig(configDir), name); } @@ -83,9 +82,10 @@ export function resolveBlockfrostProjectId( * command's flags, then the saved config for this network, and only the * components given by neither are auto-detected on undeployed (detection * refuses when a needed component is ambiguous). Every caller gets the same - * fully resolved endpoints. + * fully resolved endpoints. `settings` are the host's: whether to look for a + * local stack, and the Blockfrost ids. */ -export function resolveNetwork(ctx: NetworkResolutionContext): { +export function resolveNetwork(ctx: NetworkResolutionContext, settings: NetworkSettings): { name: NetworkName; config: NetworkConfig; } { @@ -96,6 +96,10 @@ export function resolveNetwork(ctx: NetworkResolutionContext): { indexerWS: getFlag(ctx.args, 'indexer-ws') ?? configured['indexer-ws'], proofServer: getFlag(ctx.args, 'proof-server') ?? configured['proof-server'], }; - const config = resolveNetworkConfig(name, { given, blockfrostProjectId: resolveBlockfrostProjectId(name, ctx.configDir) }); + const config = resolveNetworkConfig(name, { + given, + isLocalDetectOff: settings.isLocalDetectOff, + blockfrostProjectId: resolveBlockfrostProjectId(name, ctx.configDir, settings), + }); return { name, config }; } diff --git a/packages/cli-core/src/lib/settings.ts b/packages/cli-core/src/lib/settings.ts index 292658ee..ada2bb09 100644 --- a/packages/cli-core/src/lib/settings.ts +++ b/packages/cli-core/src/lib/settings.ts @@ -1,8 +1,8 @@ // What the environment says, as settings libraries read. The environment -// variables are the shell's public contract: the shell gives the -// libraries a source of settings, read from them as each is needed, and a -// consumer gives its own. A library never reads the environment itself; with -// no source, every setting is unset. +// variables are the shell's public contract: the shell's host reads its +// settings from them as each is needed, and a consumer's host gives its own. +// A library never reads the environment itself: it takes the settings from +// its call's host, or as a parameter. /** The environment variables that become settings: their names, in one place. */ export const PASSPHRASE_ENV = 'MN_PASSPHRASE'; @@ -46,18 +46,3 @@ export function settingsFromEnvironment(env: Record) sharedBlockfrostProjectId: env[SHARED_BLOCKFROST_PROJECT_ID_ENV], }; } - -/** Every setting unset: what a library sees with no source. */ -const UNSET: Settings = settingsFromEnvironment({}); - -let source: (() => Settings) | null = null; - -/** Where settings come from from now on; null for none. */ -export function setSettingsSource(next: (() => Settings) | null): void { - source = next; -} - -/** The settings now. */ -export function settings(): Settings { - return source?.() ?? UNSET; -} diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index 70e44a9a..7da022fb 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -14,7 +14,8 @@ import { sdkSetOf, type DAppConnector, type HostEngines, type OpenedConnector, type TransactionDetail } from './engine.ts'; import type { NetworkConfig, NetworkName } from './network.ts'; import type { NoticeSink } from './notices.ts'; -import { resolveNetwork } from './resolve-network.ts'; +import { resolveNetwork, type NetworkSettings } from './resolve-network.ts'; +import { settingsFromEnvironment } from './settings.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; import { throwIfCancelled } from './errors.ts'; import { isColdStartRace } from './sdk-errors.ts'; @@ -230,6 +231,8 @@ export interface OpenWalletSessionOptions { engines: HostEngines; /** The network's endpoints; when absent, as a command without endpoint flags resolves them (the saved config, then the defaults). */ networkConfig?: NetworkConfig; + /** The host's settings, read only to resolve the endpoints when `networkConfig` is absent (local stack detection, the Blockfrost ids); every one unset when not given. */ + settings?: NetworkSettings; /** Whether to sync the shielded wallet; off where the network has no shielded faucet, unless forced. */ forceShielded?: boolean; /** How long to wait for the wallet's Dust once synced, in milliseconds; the connector's default when absent. */ @@ -242,14 +245,13 @@ export interface OpenWalletSessionOptions { /** * Opens a seed's wallet on a network: synced, its Dust ready, with the - * network's engine from `options.engines`. The host must have installed its - * settings first, as the CLI does at start. + * network's engine from `options.engines`. */ export async function openWalletSession(options: OpenWalletSessionOptions): Promise { const { seed, network, root, signal } = options; throwIfCancelled(signal); const networkConfig = options.networkConfig - ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } }, configDir: root }).config; + ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } }, configDir: root }, options.settings ?? settingsFromEnvironment({})).config; const engine = await options.engines.load(sdkSetOf(network, root)); const open = () => engine.wallet.openConnector({ seed, diff --git a/scripts/check-process-safety.d.mts b/scripts/check-process-safety.d.mts index dcb0e8f7..e825ea18 100644 --- a/scripts/check-process-safety.d.mts +++ b/scripts/check-process-safety.d.mts @@ -1,10 +1,13 @@ // Types for what scripts/check-process-safety.mjs exports when imported. export const ALLOWED: Record; export const ALLOWED_STATE: Record>; -export function moduleStateDeclarations(code: string): { line: number; name: string }[]; +export const ALLOWED_SETTERS: Record>; +export function moduleStateDeclarations(code: string): { line: number; name: string; kind: 'let' | 'var' | 'const' }[]; +export function exportedSetters(code: string): { line: number; name: string }[]; export function findViolations( files?: string[], allowed?: Record, allowedState?: Record>, src?: string, + allowedSetters?: Record>, ): { file: string; line: number; rule: string; name?: string }[]; diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index bab26b3e..e8222b71 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -17,7 +17,12 @@ // - only the shell sets the process's exit code; a handler returns its own; // - only the shell's noise filter (lib/sdk-noise.ts) may keep ambient per-call // storage (AsyncLocalStorage, async_hooks); everything else is passed the -// call's context explicitly. +// call's context explicitly; +// - library, ui and command code exports no setter of host state: no +// function named set…Source, set…Sink, setPrompter or setEngineLoader, and +// no exported function that assigns a module-level `let` or `var`. What a +// library needs from its host comes in through the host it is passed; the +// one process guard allowed is named below, with its reason. // // Usage: node scripts/check-process-safety.mjs // Exits 1 when a library does something the rules above forbid, or any code @@ -54,6 +59,8 @@ const COMMAND_RULES = RULES.filter(([rule]) => rule === 'writes to the terminal' // The module-state rules, each with the code it applies to. const MODULE_STATE = 'keeps module state'; const STALE_STATE = 'allowlists module state it no longer keeps'; +const SETTER = 'exports a setter of host state'; +const STALE_SETTER = 'allowlists a setter it no longer exports'; const AMBIENT = 'keeps ambient per-call storage'; const notNoiseFilter = (rel) => rel !== 'lib/sdk-noise.ts'; // [rule, pattern, the files it applies to, whether it reads the raw source (an import's specifier)]. @@ -87,10 +94,19 @@ export const ALLOWED_STATE = { 'lib/engine.ts': { loadedSet: 'shared on purpose: the SDK set this process loads, whichever host loads it (two WASM ledgers cannot share a process)', }, - // The host source, set once by the host at start (handlers see it through the context). - 'lib/settings.ts': { source: 'shared on purpose: the host sets the settings source once' }, }; +// Exported functions that set module state, which the setter rule allows, by +// file and name, and why. Host state is never one: a host passes it in. +export const ALLOWED_SETTERS = { + 'lib/engine.ts': { + claimSdkSet: 'the process guard, approved by the owner: records the one SDK set this process loads, whichever host loads it, and refuses the other (two WASM ledgers cannot share a process)', + }, +}; + +// The names a setter of host state goes by, whatever it assigns. +const SETTER_NAME = /^(set\w*Source|set\w*Sink|setPrompter|setEngineLoader)$/; + /** * Replaces string, template-literal text, regex-literal and comment contents * with spaces, keeping line breaks. The code inside a template's `${…}` is @@ -167,7 +183,7 @@ function codeOnly(source) { /** * The module-level declarations in `code` (as codeOnly leaves it) that hold - * mutable state: { line, name }. A `let` or `var`; a `const` made with + * mutable state: { line, name, kind }. A `let` or `var`; a `const` made with * `new Map/Set/WeakMap/WeakSet/Array` unless typed ReadonlyMap/ReadonlySet; * an array literal unless typed readonly or `as const`; an empty object * literal unless typed Readonly. A non-empty object literal is a table of @@ -192,7 +208,7 @@ export function moduleStateDeclarations(code) { if (head === null) continue; const statement = topLevelStatement(code, i); const [, kind, name] = head; - if (kind !== 'const' || isMutableInitializer(statement.slice(head[0].length))) found.push({ line: lineNumber, name }); + if (kind !== 'const' || isMutableInitializer(statement.slice(head[0].length))) found.push({ line: lineNumber, name, kind }); } return found; } @@ -209,6 +225,64 @@ function topLevelStatement(code, start) { return code.slice(start); } +/** + * The module-level statements in `code` (as codeOnly leaves it): { line, text }, + * each from a line that starts outside any bracket to the next such line. + */ +function topLevelStatements(code) { + const statements = []; + let depth = 0; + code.split('\n').forEach((text, at) => { + if (depth === 0 && text.trim() !== '') statements.push({ line: at + 1, text }); + else if (statements.length > 0) statements[statements.length - 1].text += '\n' + text; + for (const c of text) { + if (c === '{' || c === '[' || c === '(') depth += 1; + else if (c === '}' || c === ']' || c === ')') depth -= 1; + } + }); + return statements; +} + +/** + * The functions `code` exports that set host state: { line, name }. One named + * as a setter of host state, or one whose body assigns a module-level `let` or + * `var` (a local of the same name declared in it aside). Exported by + * declaration, as a const holding a function, or through an `export { … }` list. + */ +export function exportedSetters(code) { + const lets = moduleStateDeclarations(code).filter((d) => d.kind !== 'const').map((d) => d.name); + const functions = new Map(); + const exported = new Set(); + for (const { line, text } of topLevelStatements(code)) { + const declared = /^\s*(export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/.exec(text) + ?? /^\s*(export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]*)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]*)?=>|[A-Za-z_$][\w$]*\s*=>)/.exec(text); + if (declared !== null) { + functions.set(declared[2], { line, text }); + if (declared[1] !== undefined) exported.add(declared[2]); + continue; + } + const list = /^\s*export\s*\{([^}]*)\}/.exec(text); + if (list !== null) for (const item of list[1].split(',')) { + const local = item.trim().split(/\s+as\s+/)[0]; + if (local) exported.add(local); + } + } + const assigns = (text, bare) => { + const name = bare.replace(/\$/g, '\\$'); + if (new RegExp(`\\b(let|var|const)\\s+${name}\\b`).test(text)) return false; + return new RegExp(`(?>>?|\\?\\?|\\|\\||&&)?=(?![=>])|(?:\\+\\+|--)\\s*${name}\\b|(? assigns(body, n))) found.push({ line: fn.line, name }); + } + return found.sort((a, b) => a.line - b.line); +} + /** After a const's name: its type annotation and initializer hold mutable state. */ function isMutableInitializer(rest) { // The initializer's `=`: the first outside brackets, not part of `=>`, `==`. @@ -251,7 +325,7 @@ const isCommand = (rel) => rel.startsWith('commands/'); * the name for module state. `src` is the folder the files' kinds are read * from (commands/, ui/, …): src/, unless a test plants files elsewhere. */ -export function findViolations(files = sourceFiles(), allowed = ALLOWED, allowedState = ALLOWED_STATE, src = SRC) { +export function findViolations(files = sourceFiles(), allowed = ALLOWED, allowedState = ALLOWED_STATE, src = SRC, allowedSetters = ALLOWED_SETTERS) { const found = []; for (const file of files) { const rel = src === SRC ? relOf(file) : relative(src, file); @@ -283,6 +357,13 @@ export function findViolations(files = sourceFiles(), allowed = ALLOWED, allowed for (const name of Object.keys(allowedState[rel] ?? {})) { if (!declared.some((d) => d.name === name)) found.push({ file: rel, line: 0, rule: STALE_STATE, name }); } + const setters = exportedSetters(code); + for (const { line, name } of setters) { + if (!Object.hasOwn(allowedSetters[rel] ?? {}, name)) found.push({ file: rel, line, rule: SETTER, name }); + } + for (const name of Object.keys(allowedSetters[rel] ?? {})) { + if (!setters.some((s) => s.name === name)) found.push({ file: rel, line: 0, rule: STALE_SETTER, name }); + } } for (const [rule, pattern, appliesTo, isRaw] of CALL_RULES) { if (appliesTo(rel, file) && !rel.startsWith('__tests__/')) scanRule(rule, pattern, isRaw); @@ -297,6 +378,7 @@ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { for (const v of found) process.stdout.write(`src/${v.file}:${v.line} ${v.rule}${v.name === undefined ? '' : ` (${v.name})`}\n`); const allowedCount = Object.keys(ALLOWED).length; const stateCount = Object.values(ALLOWED_STATE).reduce((n, names) => n + Object.keys(names).length, 0); - process.stdout.write(`\n${found.length === 0 ? 'Libraries leave the process alone, commands write through their call, and no call keeps its state in a module' : `${found.length} place(s) where code touches the process or keeps a call's state`} (${allowedCount} file(s) and ${stateCount} module state(s) allowed, with their reasons).\n`); + const setterCount = Object.values(ALLOWED_SETTERS).reduce((n, names) => n + Object.keys(names).length, 0); + process.stdout.write(`\n${found.length === 0 ? 'Libraries leave the process alone, commands write through their call, no call keeps its state in a module, and no library exports a setter of host state' : `${found.length} place(s) where code touches the process, keeps a call's state or exports a setter of host state`} (${allowedCount} file(s), ${stateCount} module state(s) and ${setterCount} setter(s) allowed, with their reasons).\n`); process.exit(found.length === 0 ? 0 : 1); } diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index 90c69667..f0bfc8d8 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -57,7 +57,7 @@ afterEach(() => { beforeAll(async () => { const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); - const { indexer } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }).config; + const { indexer } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }, testHost().settings()).config; const answered = await fetch(indexer, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: '{ block { height } }' }), signal: AbortSignal.timeout(5_000) }) .then((r) => r.ok, () => false); if (!answered) throw new Error(`No ledger-9 indexer answers at ${indexer}: start the local chain (or point undeployed at one with midnight config set) before npm run test:live.`); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index ce14180d..af2e6c0b 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -31,7 +31,6 @@ import { FULL_FLAG, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-c import { CancelledError, isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError, EXIT_CANCELLED } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import type { CallContext, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; import { createSdkWarningRouter, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import type { WalletProtector } from '../lib/wallet-protector.ts'; @@ -141,7 +140,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => it('gives the handler the configuration the host gives when the call starts, and --verbose', async () => { const { ctx } = (await run('plain')).call; expect(ctx.config.paths).toStrictEqual(provisions.host.paths()); - expect(ctx.config.settings).toStrictEqual(settings()); + expect(ctx.config.settings).toStrictEqual(provisions.host.settings()); expect(ctx.diagnostics.isVerbose).toBe(false); received.length = 0; await dispatchCommand(testRegistry, 'plain', parseArgs(['plain', '--verbose']), provisions); diff --git a/src/__tests__/fixtures/record-swap-offer.ts b/src/__tests__/fixtures/record-swap-offer.ts index 618a46ad..aff30dfa 100644 --- a/src/__tests__/fixtures/record-swap-offer.ts +++ b/src/__tests__/fixtures/record-swap-offer.ts @@ -13,7 +13,7 @@ import { mkdtempSync, writeFileSync } from 'node:fs'; import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { loadInstalledEngine } from '../../lib/installed-engines.ts'; @@ -34,7 +34,6 @@ const networkConfig: NetworkConfig = { const home = mkdtempSync(join(tmpdir(), 'mn-record-offer-')); const root = join(home, '.midnight'); -setSettingsSource(() => settingsFromEnvironment(process.env)); const host = createHost({ settings: () => settingsFromEnvironment(process.env), paths: { stateRoot: root, home }, engineLoader: loadInstalledEngine }); const engine = await host.engines.for('undeployed'); diff --git a/src/__tests__/generate-command.test.ts b/src/__tests__/generate-command.test.ts index a6b305e3..413f1b6f 100644 --- a/src/__tests__/generate-command.test.ts +++ b/src/__tests__/generate-command.test.ts @@ -10,10 +10,10 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { testHost } from './helpers/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped. +const host = testHost(); const TEST_DIR = path.join(os.tmpdir(), `midnight-generate-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; diff --git a/src/__tests__/helpers/shell-settings.ts b/src/__tests__/helpers/shell-settings.ts deleted file mode 100644 index 221942d1..00000000 --- a/src/__tests__/helpers/shell-settings.ts +++ /dev/null @@ -1,8 +0,0 @@ -// The test run stands in for the shell: libraries read the environment the -// tests set (MN_PASSPHRASE, MN_SEED, …) as settings. Where state is kept and -// which engine runs, each test says: its host's paths and engines -// (test-host.ts), or the root and engines it passes a library. - -import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; - -setSettingsSource(() => settingsFromEnvironment(process.env)); diff --git a/src/__tests__/local-stacks.test.ts b/src/__tests__/local-stacks.test.ts index a1d6be3f..925bf87e 100644 --- a/src/__tests__/local-stacks.test.ts +++ b/src/__tests__/local-stacks.test.ts @@ -12,6 +12,10 @@ import { resolveNetworkConfig, AmbiguousLocalStacksError, } from '@kuiralabs/midnight-cli-core/lib/network'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; + +// Settings that turn detection off, for the resolutions whose docker output isn't the test's. +const NO_DETECT = settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }); const SCRATCH = [ 'midnightntwrk/indexer-standalone:4.4.0-rc.5|0.0.0.0:28088->8088/tcp, [::]:28088->8088/tcp', @@ -148,7 +152,7 @@ describe('resolveNetwork', () => { network: 'undeployed', networks: { undeployed: { node: 'ws://localhost:29944', 'indexer-ws': 'ws://localhost:28088/api/v4/graphql/ws', 'proof-server': 'http://localhost:26300' } }, }, (configDir) => { - const { config } = resolveNetwork({ args: parseArgs(['test']), configDir }); + const { config } = resolveNetwork({ args: parseArgs(['test']), configDir }, NO_DETECT); expect(config.node).toBe('ws://localhost:29944'); expect(config.indexer).toBe('http://localhost:28088/api/v4/graphql'); expect(config.indexerWS).toBe('ws://localhost:28088/api/v4/graphql/ws'); @@ -160,7 +164,7 @@ describe('resolveNetwork', () => { const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); await withConfig({ network: 'undeployed', networks: { undeployed: { node: 'ws://localhost:29944' } } }, (configDir) => { - const { config } = resolveNetwork({ args: parseArgs(['balance', '--node', 'ws://localhost:39944']), configDir }); + const { config } = resolveNetwork({ args: parseArgs(['balance', '--node', 'ws://localhost:39944']), configDir }, NO_DETECT); expect(config.node).toBe('ws://localhost:39944'); }); }); @@ -169,7 +173,7 @@ describe('resolveNetwork', () => { const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); await withConfig({ network: 'preview', networks: { preview: { 'proof-server': 'http://preview-prover:6300' } } }, (configDir) => { - const { config } = resolveNetwork({ args: parseArgs(['balance', '--network', 'preprod']), configDir }); + const { config } = resolveNetwork({ args: parseArgs(['balance', '--network', 'preprod']), configDir }, NO_DETECT); expect(config.proofServer).toBe('http://localhost:6300'); }); }); @@ -182,7 +186,7 @@ describe('resolveNetwork', () => { args: parseArgs(['balance', '--network', 'undeployed', '--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']), configDir, - }); + }, NO_DETECT); expect(name).toBe('undeployed'); expect(config.node).toBe('ws://localhost:29944'); expect(config.indexer).toBe('http://localhost:28088/api/v4/graphql'); diff --git a/src/__tests__/process-safety.test.ts b/src/__tests__/process-safety.test.ts index dd167000..ebbf85d3 100644 --- a/src/__tests__/process-safety.test.ts +++ b/src/__tests__/process-safety.test.ts @@ -200,6 +200,84 @@ describe("the process-safety check keeps calls' state out of modules", () => { }); }); +// What a library needs from its host comes in through the host it is passed, never a module-level setter. +describe('the process-safety check finds a library exporting a setter of host state', () => { + const plant = (rel: string, lines: string[]) => { + const file = join(dir, rel); + mkdirSync(join(file, '..'), { recursive: true }); + writeFileSync(file, lines.join('\n')); + return file; + }; + const setters = (file: string, allowedSetters?: Record>) => + findViolations([file], {}, {}, dir, allowedSetters).filter((v) => v.rule.includes('setter')).map((v) => `${v.line} ${v.rule} ${v.name}`); + + it('by its name, or by an exported function assigning a module-level let, however it is exported', () => { + const file = plant('lib/sources.ts', [ + "import type { Settings } from './settings.ts';", + 'export function setSettingsSource(next: (() => Settings) | null): void {}', + 'export const setNoticeSink = (sink: (line: string) => void) => {};', + 'export function setPrompter(p: unknown): void {}', + 'export async function setEngineLoader(l: unknown): Promise {}', + 'let root: string | undefined;', + 'export function useRoot(next: string): void {', + ' root = next;', + '}', + 'let calls = 0;', + 'function count(): number {', + ' return ++calls;', + '}', + 'export { count as countCall };', + ]); + expect(setters(file)).toEqual([ + '2 exports a setter of host state setSettingsSource', + '3 exports a setter of host state setNoticeSink', + '4 exports a setter of host state setPrompter', + '5 exports a setter of host state setEngineLoader', + '7 exports a setter of host state useRoot', + '11 exports a setter of host state count', + ]); + }); + + it('not a function that only reads module state, assigns its own local, or stays unexported, nor a setter of state on disk', () => { + const file = plant('lib/readers.ts', [ + 'let loaded: string | undefined;', + 'export function current(): string | undefined {', + ' return loaded === undefined ? undefined : loaded;', + '}', + 'export function tally(items: string[]): number {', + ' let loaded = 0;', + ' for (const _ of items) loaded += 1;', + ' return loaded;', + '}', + 'function remember(next: string): void {', + ' loaded = next;', + '}', + 'export const isLoaded = (x: string) => x === loaded;', + 'export function setConfigValue(key: string, value: string, root: string): void {}', + "const note = 'export function setSettingsSource() {}';", + ]); + expect(setters(file)).toEqual([]); + }); + + it('allows claimSdkSet, the process guard, only where the allowlist names it, and reports an entry whose setter is gone', () => { + const guard = plant('lib/engine.ts', [ + "let loadedSet: 'rc' | 'beta' | undefined;", + "export function claimSdkSet(set: 'rc' | 'beta'): void {", + ' if (loadedSet !== undefined && loadedSet !== set) throw new Error(set);', + ' loadedSet = set;', + '}', + ]); + expect(setters(guard)).toEqual([]); + expect(setters(guard, {})).toEqual(['2 exports a setter of host state claimSdkSet']); + const elsewhere = plant('lib/other.ts', [ + "let loadedSet: 'rc' | 'beta' | undefined;", + "export function claimSdkSet(set: 'rc' | 'beta'): void { loadedSet = set; }", + ]); + expect(setters(elsewhere)).toEqual(['2 exports a setter of host state claimSdkSet']); + expect(setters(plant('lib/engine.ts', ['export const NONE = 1;']))).toEqual(['0 allowlists a setter it no longer exports claimSdkSet']); + }); +}); + describe('the shell filters the SDK noise', () => { const run = (body: string) => { const script = join(dir, 'noise.mjs'); diff --git a/src/__tests__/resolve-network.test.ts b/src/__tests__/resolve-network.test.ts index aa1e8760..130c1cd7 100644 --- a/src/__tests__/resolve-network.test.ts +++ b/src/__tests__/resolve-network.test.ts @@ -5,6 +5,11 @@ import * as os from 'os'; import { resolveBlockfrostProjectId, resolveNetworkName, resolveNetwork, type NetworkResolutionContext } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { saveCliConfig, setConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; + +// The settings resolution is given: no Blockfrost id, and no local stack +// detection (what docker runs on this machine must not matter). +const SETTINGS = settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }); // Use a temp config dir to avoid polluting the real ~/.midnight/ const TEST_DIR = path.join(os.tmpdir(), `midnight-resolve-network-test-${process.pid}`); @@ -77,7 +82,7 @@ describe('resolveNetworkName', () => { describe('resolveNetwork', () => { it('returns both name and config', () => { const ctx = makeCtx({ args: makeArgs(['--network', 'preprod']) }); - const result = resolveNetwork(ctx); + const result = resolveNetwork(ctx, SETTINGS); expect(result.name).toBe('preprod'); expect(result.config.networkId).toBe('PreProd'); expect(result.config.indexer).toContain('preprod'); @@ -85,7 +90,7 @@ describe('resolveNetwork', () => { it('config contains all required fields', () => { const ctx = makeCtx({ args: makeArgs(['--network', 'undeployed']) }); - const result = resolveNetwork(ctx); + const result = resolveNetwork(ctx, SETTINGS); expect(result.config.indexer).toBeDefined(); expect(result.config.indexerWS).toBeDefined(); expect(result.config.node).toBeDefined(); @@ -99,71 +104,60 @@ describe('resolveBlockfrostProjectId', () => { const FROM_ENV = 'nightpreprodEnvEnvEnvEnvEnvEnv0002'; it('is undefined when none is set', () => { - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, {})).toBeUndefined(); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({}))).toBeUndefined(); }); it('is the one set with config set', () => { setConfigValue('blockfrost-project-id', FROM_CONFIG, TEST_DIR); - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, {})).toBe(FROM_CONFIG); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({}))).toBe(FROM_CONFIG); }); it('is the environment\'s over the config\'s', () => { setConfigValue('blockfrost-project-id', FROM_CONFIG, TEST_DIR); - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, { MN_BLOCKFROST_PROJECT_ID: FROM_ENV })).toBe(FROM_ENV); - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, { MN_BLOCKFROST_PROJECT_ID: ' ' })).toBe(FROM_CONFIG); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: FROM_ENV }))).toBe(FROM_ENV); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: ' ' }))).toBe(FROM_CONFIG); }); it('is undefined on a network Blockfrost doesn\'t serve, whatever is set', () => { setConfigValue('blockfrost-project-id', FROM_CONFIG, TEST_DIR); - expect(resolveBlockfrostProjectId('preview', TEST_DIR, { MN_BLOCKFROST_PROJECT_ID: FROM_ENV })).toBeUndefined(); - expect(resolveBlockfrostProjectId('undeployed', TEST_DIR, { MN_BLOCKFROST_PROJECT_ID: 'garbage' })).toBeUndefined(); + expect(resolveBlockfrostProjectId('preview', TEST_DIR, settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: FROM_ENV }))).toBeUndefined(); + expect(resolveBlockfrostProjectId('undeployed', TEST_DIR, settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: 'garbage' }))).toBeUndefined(); }); it('takes the variable Midnight\'s docs name, after mn\'s own and before the config', () => { const SHARED = 'nightpreprodSharedSharedShared0003'; setConfigValue('blockfrost-project-id', FROM_CONFIG, TEST_DIR); - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, { BLOCKFROST_PROJECT_ID: SHARED })).toBe(SHARED); - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, { BLOCKFROST_PROJECT_ID: ` ${SHARED}\n` })).toBe(SHARED); - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, { BLOCKFROST_PROJECT_ID: SHARED, MN_BLOCKFROST_PROJECT_ID: FROM_ENV })).toBe(FROM_ENV); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ BLOCKFROST_PROJECT_ID: SHARED }))).toBe(SHARED); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ BLOCKFROST_PROJECT_ID: ` ${SHARED}\n` }))).toBe(SHARED); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ BLOCKFROST_PROJECT_ID: SHARED, MN_BLOCKFROST_PROJECT_ID: FROM_ENV }))).toBe(FROM_ENV); }); // Other Blockfrost tools use the same variable for another network's id, or another chain's. it('passes over that variable when its id is not this network\'s, without refusing', () => { setConfigValue('blockfrost-project-id', FROM_CONFIG, TEST_DIR); for (const other of ['nightmainnetAbCdEfGhIjKlMnOp', 'mainnetAbCdEfGhIjKlMnOpQrSt', 'not an id', '']) { - expect(resolveBlockfrostProjectId('preprod', TEST_DIR, { BLOCKFROST_PROJECT_ID: other })).toBe(FROM_CONFIG); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ BLOCKFROST_PROJECT_ID: other }))).toBe(FROM_CONFIG); } - expect(resolveBlockfrostProjectId('preprod', TEST_DIR + '-none', { BLOCKFROST_PROJECT_ID: 'mainnetAbCdEfGhIjKlMnOpQrSt' })).toBeUndefined(); + expect(resolveBlockfrostProjectId('preprod', TEST_DIR + '-none', settingsFromEnvironment({ BLOCKFROST_PROJECT_ID: 'mainnetAbCdEfGhIjKlMnOpQrSt' }))).toBeUndefined(); }); it('refuses an environment value that is no project id', () => { - expect(() => resolveBlockfrostProjectId('preprod', TEST_DIR, { MN_BLOCKFROST_PROJECT_ID: 'nightmainnetAbCdEfGhIjKl' })) + expect(() => resolveBlockfrostProjectId('preprod', TEST_DIR, settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: 'nightmainnetAbCdEfGhIjKl' }))) .toThrow('it should start with "nightpreprod" (preprod)'); }); }); describe('resolveNetwork on preprod', () => { - let origEnv: string | undefined; - let origShared: string | undefined; - beforeEach(() => { - origEnv = process.env.MN_BLOCKFROST_PROJECT_ID; delete process.env.MN_BLOCKFROST_PROJECT_ID; - origShared = process.env.BLOCKFROST_PROJECT_ID; delete process.env.BLOCKFROST_PROJECT_ID; - }); - afterEach(() => { - if (origEnv !== undefined) process.env.MN_BLOCKFROST_PROJECT_ID = origEnv; - if (origShared !== undefined) process.env.BLOCKFROST_PROJECT_ID = origShared; - }); - it('gives Blockfrost\'s endpoints with the project id that is set', () => { setConfigValue('blockfrost-project-id', 'nightpreprodConfigConfigConfig0001', TEST_DIR); - const { name, config } = resolveNetwork(makeCtx({ args: makeArgs(['--network', 'preprod']) })); + const { name, config } = resolveNetwork(makeCtx({ args: makeArgs(['--network', 'preprod']) }), SETTINGS); expect(name).toBe('preprod'); expect(config.indexerWS).toBe('wss://midnight-preprod.blockfrost.io/api/v0/ws?project_id=nightpreprodConfigConfigConfig0001'); expect(config.node).toBe('wss://rpc.midnight-preprod.blockfrost.io?project_id=nightpreprodConfigConfigConfig0001'); }); it('resolves without one, so a command that never connects is not stopped', () => { - const { config } = resolveNetwork(makeCtx({ args: makeArgs(['--network', 'preprod']) })); + const { config } = resolveNetwork(makeCtx({ args: makeArgs(['--network', 'preprod']) }), SETTINGS); expect(config.indexer).toBe('https://midnight-preprod.blockfrost.io/api/v0'); }); }); diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 70c549fa..04578270 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -11,11 +11,10 @@ import { parseSeedHex, resolveSeedSource, resolveSeed } from '../lib/seed-resolv import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { testHost } from './helpers/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. -const host = createHost({ engineLoader: loadInstalledEngine }); +// The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = testHost(); const PASSPHRASE = 'correct horse battery staple'; const ORIGINAL_HOME = process.env.HOME; diff --git a/src/__tests__/settings.test.ts b/src/__tests__/settings.test.ts index 4b52b22c..e907b34b 100644 --- a/src/__tests__/settings.test.ts +++ b/src/__tests__/settings.test.ts @@ -1,17 +1,30 @@ -// The environment variables reach libraries only as settings -// the shell gives them: each maps to its setting, and a library with no -// settings source behaves as if none were set, whatever the environment says. +// The environment variables reach libraries only as settings their host +// gives them (or a caller passes): each maps to its setting, and a library +// given none behaves as if none were set, whatever the environment says. -import { afterEach, describe, expect, it } from 'vitest'; -import { setSettingsSource, settings, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { resolveBlockfrostProjectId } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { detectLocalStacks } from '@kuiralabs/midnight-cli-core/lib/network'; -import { readPassphrase, NoPassphraseError } from '../lib/passphrase.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { readPassphrase, passphraseForNewSecret, NoPassphraseError } from '../lib/passphrase.ts'; +import { resolveSeedSource } from '../lib/seed-resolver.ts'; -afterEach(() => { - // Back to what the test harness gives, as the shell does. - setSettingsSource(() => settingsFromEnvironment(process.env)); -}); +/** Runs `fn` with `name` set in the process's environment, then restores it. */ +async function withProcessEnv(name: string, value: string, fn: () => Promise | void): Promise { + const before = process.env[name]; + process.env[name] = value; + try { + await fn(); + } finally { + if (before === undefined) delete process.env[name]; + else process.env[name] = before; + } +} describe('settings from the environment', () => { it('maps each variable to its setting', () => { @@ -28,35 +41,53 @@ describe('settings from the environment', () => { expect(settingsFromEnvironment({ MN_NO_LOCAL_DETECT: 'yes', MN_DISABLE_NATIVE_DUST: '0' })).toMatchObject({ isLocalDetectOff: false, isNativeDustOff: false }); }); - it('reads the source each time, so a variable changed during the run is seen', () => { + it('are read from a host\'s source each time, so a variable changed during the run is seen', () => { const env: Record = { MN_SEED: 'first' }; - setSettingsSource(() => settingsFromEnvironment(env)); - expect(settings().seed).toBe('first'); + const host = createHost({ settings: () => settingsFromEnvironment(env) }); + expect(host.settings().seed).toBe('first'); env.MN_SEED = 'second'; - expect(settings().seed).toBe('second'); + expect(host.settings().seed).toBe('second'); }); }); -describe('a library with no settings source', () => { - it('takes no passphrase from the environment', async () => { - process.env.MN_PASSPHRASE = 'set in the environment'; - try { - setSettingsSource(null); +describe('a library takes its settings from its host or its caller, never the environment', () => { + it('takes no passphrase from the environment when none is given', async () => { + await withProcessEnv('MN_PASSPHRASE', 'set in the environment', async () => { await expect(readPassphrase(null)).rejects.toThrow(NoPassphraseError); + }); + }); + + it('takes the passphrase from its host\'s settings, not the environment', async () => { + const home = mkdtempSync(join(tmpdir(), 'mn-settings-')); + try { + await withProcessEnv('MN_PASSPHRASE', 'set in the environment', async () => { + const root = join(home, '.midnight'); + await expect(passphraseForNewSecret(createHost(), root)).rejects.toThrow(NoPassphraseError); + const host = createHost({ settings: settingsFromEnvironment({ MN_PASSPHRASE: 'the host gives this one' }) }); + expect(await passphraseForNewSecret(host, root)).toBe('the host gives this one'); + }); } finally { - delete process.env.MN_PASSPHRASE; + rmSync(home, { recursive: true, force: true }); } }); - it('takes no Blockfrost id from the environment', () => { - setSettingsSource(() => settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: 'nightpreprodAbc123' })); - expect(resolveBlockfrostProjectId('preprod', '/nonexistent-config-dir')).toBe('nightpreprodAbc123'); - setSettingsSource(null); - expect(resolveBlockfrostProjectId('preprod', '/nonexistent-config-dir')).toBeUndefined(); + it('takes MN_SEED from its host\'s settings, not the environment', async () => { + const seed = '11'.repeat(32); + await withProcessEnv('MN_SEED', '22'.repeat(32), async () => { + const host = createHost({ settings: settingsFromEnvironment({ MN_SEED: seed }) }); + const resolved = await resolveSeedSource(parseArgs(['address']), '/nonexistent-state-root', host); + expect(resolved.seed.toString('hex')).toBe(seed); + }); + }); + + it('takes the Blockfrost id it is given, not the environment\'s', async () => { + await withProcessEnv('MN_BLOCKFROST_PROJECT_ID', 'nightpreprodFromTheEnvironment', () => { + expect(resolveBlockfrostProjectId('preprod', '/nonexistent-config-dir', settingsFromEnvironment({ MN_BLOCKFROST_PROJECT_ID: 'nightpreprodAbc123' }))).toBe('nightpreprodAbc123'); + expect(resolveBlockfrostProjectId('preprod', '/nonexistent-config-dir', settingsFromEnvironment({}))).toBeUndefined(); + }); }); - it('looks for a local stack unless the settings say not to', () => { - setSettingsSource(() => settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' })); - expect(detectLocalStacks()).toEqual({ node: [], indexer: [], proofServer: [] }); + it('looks for a local stack unless the settings it is given say not to', () => { + expect(detectLocalStacks(settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }))).toEqual({ node: [], indexer: [], proofServer: [] }); }); }); diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 48221de0..2f18be9c 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -10,7 +10,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { testHost } from './helpers/test-host.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; import { cliCall } from './helpers/cli-call.ts'; @@ -44,7 +44,7 @@ async function writeEveryOwnersFiles(root: string): Promise { setConfigValue('network', 'preview', root); setConfigValue('node', 'ws://localhost:29944', root, 'undeployed'); bindCachesToIndexer('undeployed', 'ws://localhost:28088/api/v4/graphql/ws', root); - const host = createHost({ engineLoader: loadInstalledEngine }); + const host = testHost(); await createWallet(root, 'alice', walletSecretFrom({ seed: Buffer.alloc(32, 2) }), await passphraseForNewSecret(host, root), await host.engines.any()); fs.mkdirSync(accountRecordsDir('undeployed', 'alice', root), { recursive: true }); } diff --git a/src/__tests__/swap-request.test.ts b/src/__tests__/swap-request.test.ts index 306eeff9..1963d95d 100644 --- a/src/__tests__/swap-request.test.ts +++ b/src/__tests__/swap-request.test.ts @@ -13,11 +13,10 @@ import { NotAnOfferError, TermsMismatchError } from '@kuiralabs/midnight-cli-cor import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../lib/swap/request.ts'; import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { testHost } from './helpers/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. -const host = createHost({ engineLoader: loadInstalledEngine }); +// The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = testHost(); const NOW = new Date('2026-11-02T12:00:00.000Z'); // A state root with no config: the networks' own endpoints. diff --git a/src/__tests__/two-hosts.test.ts b/src/__tests__/two-hosts.test.ts new file mode 100644 index 00000000..edd81172 --- /dev/null +++ b/src/__tests__/two-hosts.test.ts @@ -0,0 +1,187 @@ +// Two hosts in one process, each with its own state root and its own +// settings, run real commands through the registry's dispatch, as the shell +// does: each generates a wallet sealed under its own passphrase (given as its +// host's MN_PASSPHRASE, never the process's), sets and reads its own config, +// lists its own wallets and its own open swap offers. Nothing of one shows in +// the other, nothing lands in the process's home, and no setting is read from +// the process's environment. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { WebSocketServer } from 'ws'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import type { CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { dispatchCommand } from '../lib/command-dispatch.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { checkPassphrase } from '../lib/passphrase.ts'; + +const PASSPHRASE_A = 'host A passphrase, twelve or more'; +const PASSPHRASE_B = 'host B passphrase, twelve or more'; +// Set in the process's environment while the hosts run: neither may take it. +const PROCESS_PASSPHRASE = 'the process environment passphrase'; + +/** An open offer of the wallet's, recorded as `swap make` records one. */ +const offer = (id: string, nullifier: string): OpenOffer => ({ + id: id.repeat(32), + terms: { give: { token: '00'.repeat(31) + '01', amount: 10n }, want: { token: '00'.repeat(31) + '02', amount: 7n } }, + nullifiers: [nullifier.repeat(32)], + madeAt: new Date('2026-11-02T10:00:00.000Z'), + expiresAt: new Date('2100-01-01T00:00:00.000Z'), +}); + +/** + * An indexer standing in for the chain's, on one port as a real one is: its + * GraphQL endpoint answers the tip query, and its WebSocket answers each + * spend check with no spends. Records the nullifiers each check asks about. + */ +async function startSpendIndexer(): Promise<{ wsUrl: string; asked: string[][]; close: () => Promise }> { + const asked: string[][] = []; + const server: Server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ data: { block: { height: 812 } } })); + }); + }); + const wss = new WebSocketServer({ server, path: '/api/v4/graphql/ws' }); + wss.on('connection', (ws) => ws.on('message', (raw) => { + const msg = JSON.parse(raw.toString()) as { type: string; id?: string; payload?: { variables?: { prefixes?: string[] } } }; + if (msg.type === 'connection_init') ws.send(JSON.stringify({ type: 'connection_ack' })); + else if (msg.type === 'subscribe') { + asked.push(msg.payload?.variables?.prefixes ?? []); + ws.send(JSON.stringify({ id: msg.id, type: 'complete' })); + } + })); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + wsUrl: `ws://127.0.0.1:${port}/api/v4/graphql/ws`, + asked, + close: async () => { + for (const client of wss.clients) client.terminate(); + await new Promise((resolve) => wss.close(() => resolve())); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} + +let base: string; +let processHome: string; +let originalHome: string | undefined; +let originalEnv: NodeJS.ProcessEnv; +// The settings and the home the process's environment was asked for while the hosts ran. +let envReads: string[]; + +/** A host of its own: its state root under `home`, its settings as values (no local stack detection: docker's containers must not matter), and an engine of its own. */ +function hostAt(home: string, passphrase: string): Host { + return createHost({ + paths: { stateRoot: path.join(home, MIDNIGHT_DIR), home }, + settings: settingsFromEnvironment({ MN_PASSPHRASE: passphrase, MN_NO_LOCAL_DETECT: '1' }), + engineLoader: loadInstalledEngine, + }); +} + +/** Runs `argv` with --json through the registry's dispatch in `host`, as the shell does; returns its result. */ +async function run(host: Host, argv: string[]): Promise> { + let result: Record | undefined; + const output: CallOutput = { result: (data) => { result = JSON.parse(JSON.stringify(data)) as Record; }, stdout: () => {}, stderr: () => {} }; + const args = parseArgs([...argv, '--json']); + await dispatchCommand(installedCommands, argv[0] as string, args, { + signal: new AbortController().signal, + output, + host, + loadPayer: async () => (await import('../lib/serve-payer.ts')).servePayer, + loadProtectors: async () => [(await import('../lib/grant/account-protector.ts')).accountProtector], + }); + if (result === undefined) throw new Error(`${argv.join(' ')} wrote no result`); + return result; +} + +beforeEach(() => { + base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-two-hosts-'))); + // The process's home is a third, empty folder: neither host's state may land there. + processHome = path.join(base, 'process-home'); + fs.mkdirSync(processHome); + originalHome = process.env.HOME; + process.env.HOME = processHome; + // A passphrase neither host has, and a watch on what the process's environment is asked for. + originalEnv = process.env; + envReads = []; + const watched = { ...originalEnv, MN_PASSPHRASE: PROCESS_PASSPHRASE }; + process.env = new Proxy(watched, { + get(target, key, receiver) { + if (typeof key === 'string' && /^(MN_|BLOCKFROST_|HOME$)/.test(key)) envReads.push(key); + return Reflect.get(target, key, receiver); + }, + }); +}); + +afterEach(() => { + process.env = originalEnv; + process.env.HOME = originalHome; + fs.rmSync(base, { recursive: true, force: true }); +}); + +describe('two hosts in one process, each with its own state root and settings', () => { + it('run real commands without mixing: wallets, passphrases, config and open swap offers stay each in its own host', async () => { + const indexer = await startSpendIndexer(); + try { + const hostA = hostAt(path.join(base, 'a'), PASSPHRASE_A); + const hostB = hostAt(path.join(base, 'b'), PASSPHRASE_B); + const rootA = hostA.paths().stateRoot; + const rootB = hostB.paths().stateRoot; + + // Each sets its own config: the network, its own node, and the indexer both read offers from. + for (const [host, node] of [[hostA, 'ws://127.0.0.1:19944'], [hostB, 'ws://127.0.0.1:29944']] as const) { + expect(await run(host, ['config', 'set', 'network', 'undeployed'])).toEqual({ action: 'set', key: 'network', value: 'undeployed' }); + expect(await run(host, ['config', 'set', 'node', node])).toEqual({ action: 'set', key: 'node', value: node }); + await run(host, ['config', 'set', 'indexer-ws', indexer.wsUrl]); + } + expect(await run(hostA, ['config', 'get', 'node'])).toEqual({ action: 'get', key: 'node', value: 'ws://127.0.0.1:19944' }); + expect(await run(hostB, ['config', 'get', 'node'])).toEqual({ action: 'get', key: 'node', value: 'ws://127.0.0.1:29944' }); + + // Each generates a wallet, sealed under its own host's passphrase. + const alice = await run(hostA, ['wallet', 'generate', 'alice']); + const bob = await run(hostB, ['wallet', 'generate', 'bob']); + expect(alice.file).toBe(path.join(rootA, 'wallets', 'alice.json')); + expect(bob.file).toBe(path.join(rootB, 'wallets', 'bob.json')); + expect(() => checkPassphrase(rootA, PASSPHRASE_A)).not.toThrow(); + expect(() => checkPassphrase(rootB, PASSPHRASE_B)).not.toThrow(); + expect(() => checkPassphrase(rootA, PASSPHRASE_B)).toThrow(); + expect(() => checkPassphrase(rootB, PASSPHRASE_A)).toThrow(); + expect(() => checkPassphrase(rootA, PROCESS_PASSPHRASE)).toThrow(); + expect(() => checkPassphrase(rootB, PROCESS_PASSPHRASE)).toThrow(); + + // Each lists its own wallets, and only those. + const names = (listed: Record) => (listed.wallets as { name: string }[]).map((w) => w.name); + expect(names(await run(hostA, ['wallet', 'list']))).toEqual(['alice']); + expect(names(await run(hostB, ['wallet', 'list']))).toEqual(['bob']); + + // Each wallet's open offer is recorded under its own host's root, as `swap make` records it; each host lists its own. + const addressA = (alice.addresses as Record).undeployed as string; + const addressB = (bob.addresses as Record).undeployed as string; + recordOpenOffer(rootA, 'undeployed', addressA, offer('a1', 'aa')); + recordOpenOffer(rootB, 'undeployed', addressB, offer('b2', 'bb')); + const ids = (listed: Record) => (listed.offers as { id: string; taken: boolean }[]).map((o) => `${o.id.slice(0, 4)} ${o.taken ? 'taken' : 'open'}`); + expect(ids(await run(hostA, ['swap', 'list']))).toEqual(['a1a1 open']); + expect(ids(await run(hostB, ['swap', 'list']))).toEqual(['b2b2 open']); + expect(indexer.asked).toEqual([['aa'.repeat(32)], ['bb'.repeat(32)]]); + + // Nothing in the process's home, and no setting asked of the process's environment. + expect(fs.readdirSync(processHome)).toEqual([]); + expect(fs.readdirSync(base).sort()).toEqual(['a', 'b', 'process-home']); + expect(envReads).toEqual([]); + } finally { + await indexer.close(); + } + }); +}); diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index e408f68c..f0938c84 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -13,11 +13,10 @@ import { getActiveWalletName, unlockWallet } from '../lib/wallet-config.ts'; import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { testHost } from './helpers/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. -const host = createHost({ engineLoader: loadInstalledEngine }); +// The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. +const host = testHost(); const CHOSEN = 'correct horse battery staple'; // The passphrase as a caller gets it: the first secret in a new home sets it. diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/src/__tests__/wallet-state-to-restore.live.test.ts index 2a506bbf..ddd8edaf 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/src/__tests__/wallet-state-to-restore.live.test.ts @@ -22,7 +22,7 @@ import { testHost } from './helpers/test-host.ts'; let NETWORK: NetworkConfig; beforeAll(async () => { - NETWORK = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }).config; + NETWORK = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }, testHost().settings()).config; const answered = await fetch(NETWORK.indexer, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: '{ block { protocolVersion } }' }), signal: AbortSignal.timeout(5_000) }) .then(async (r) => ((await r.json()) as { data?: { block?: { protocolVersion?: number } } }).data?.block?.protocolVersion ?? null, () => null); if (answered === null) throw new Error(`No indexer answers at ${NETWORK.indexer}: start the local chain (or point undeployed at one with midnight config set) before npm run test:live.`); diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index c85c24d1..b0f33600 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -38,7 +38,7 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) const amountNight = parseAmount(amountStr); const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 304affb1..69e46dfb 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -65,7 +65,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise } const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); // Shielded balances are private: reading one needs the wallet's secret key, // which an address alone doesn't carry. If this address belongs to one of our @@ -172,7 +172,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); ctx.diagnostics.line('balance', `network=${networkName} indexerWS=${networkConfig.indexerWS}`); // Seed source: --seed → MN_SEED → --wallet → active wallet (shared resolver). const { seed: seedBuffer, walletPath, config } = await resolveSeedSource(args, root, ctx.host); diff --git a/src/commands/dev.ts b/src/commands/dev.ts index 4a15d595..28bbb356 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -54,7 +54,7 @@ export default async function devCommand(args: ParsedArgs, ctx: CallContext): Pr // ── Phase 2: ensure localnet running ────────────────────── const localnetSpinner = ctx.progress.start('Checking localnet...'); try { - const result = await ensureLocalnetRunning(ctx.config.paths.stateRoot, (msg) => localnetSpinner.update(msg)); + const result = await ensureLocalnetRunning(ctx.config.paths.stateRoot, ctx.config.settings, (msg) => localnetSpinner.update(msg)); const stateLabel = { 'already-running': 'Ledger-9 stack reachable', }[result.state]; diff --git a/src/commands/dust.ts b/src/commands/dust.ts index ed8d5a61..8fd95f4b 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -31,7 +31,7 @@ export default async function dustCommand(args: ParsedArgs, ctx: CallContext): P // Resolve network first — independent of the wallet (--network flag / config / fallback). const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); // Apply endpoint overrides: --flag > config > network default applyEndpointOverrides(networkConfig, { diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 8cac9161..3be49552 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -20,7 +20,7 @@ const UNITS: Record = { export default async function inspectCostCommand(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; - const { name: networkName, config } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config } = resolveNetwork({ args, configDir: root }, ctx.config.settings); // A ledger-8 chain's parameters aren't ledger-9 ones: refuse it like every other chain read. await assertLedgerSupported(networkName, config, fetchProtocolVersion, ctx.signal); const { height, parametersHex } = await fetchLedgerParameters(config.indexer, ctx.signal); diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 52915de5..68463ea0 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -55,7 +55,7 @@ export default async function serveCommand(args: ParsedArgs, ctx: CallContext): const config = await unlockWallet(resolveWalletPath(root, getFlag(args, 'wallet')), { root, host: ctx.host }); const seedBuffer = Buffer.from(config.seed, 'hex'); - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); const address = config.addresses[networkName]; // Apply endpoint overrides: --flag > config > network default diff --git a/src/commands/test.ts b/src/commands/test.ts index 72e63930..b8368bf6 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -550,7 +550,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: 'run', positionals: [], flags: { network } }, configDir: ctx.config.paths.stateRoot, - }); + }, ctx.config.settings); // mn serve should already be started by the prep step (mn-serve) // Use the serve port from the prep context if available, otherwise default diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index 93505ed0..ef8995a6 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -30,7 +30,7 @@ async function unshieldedTransfer( const root = ctx.config.paths.stateRoot; const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root, host: ctx.host })).seed, 'hex'); - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); const address = config.addresses[networkName]; applyEndpointOverrides(networkConfig, { @@ -129,7 +129,7 @@ async function shieldedTransfer( const root = ctx.config.paths.stateRoot; const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root, host: ctx.host })).seed, 'hex'); - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }); + const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); applyEndpointOverrides(networkConfig, { proofServer: getFlag(args, 'proof-server'), diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 9f1e9701..b4526ce3 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -1,6 +1,5 @@ -// A shell concern: what the CLI and the MCP server, as hosts, give the -// libraries at start. Libraries never set these -// themselves; a consumer sets its own. +// A shell concern: the host the CLI and the MCP server each build at start, +// which their calls pass to the libraries. A consumer builds its own. // - the filters for the SDK's noise, acting while a call listens, and the // calls it runs, whose SDK warnings go to the call that raised them; // - a notice sink: stderr; @@ -12,19 +11,15 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; import { installSdkNoiseFilters } from './sdk-noise.ts'; -import { setSettingsSource, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from './installed-engines.ts'; -/** - * The CLI's host, or the MCP server's (`prompter` null: no terminal there). - * Until every library takes the host's settings, the module-level settings - * source they still read is set from it. - */ +/** The CLI's host, or the MCP server's (`prompter` null: no terminal there). */ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host { - const host = createHost({ + return createHost({ settings: () => settingsFromEnvironment(process.env), paths: () => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() }), notice: (line) => process.stderr.write(line + '\n'), @@ -32,6 +27,4 @@ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host sdkWarnings: installSdkNoiseFilters(), engineLoader: loadInstalledEngine, }); - setSettingsSource(host.settings); - return host; } diff --git a/src/lib/dev/localnet-ready.ts b/src/lib/dev/localnet-ready.ts index 3f53bbb6..3e3e7c20 100644 --- a/src/lib/dev/localnet-ready.ts +++ b/src/lib/dev/localnet-ready.ts @@ -3,7 +3,7 @@ // running stack at the endpoints `undeployed` resolves to (saved config, or // the single local stack docker shows). -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { resolveNetwork, type NetworkSettings } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { assertLedger9StackReachable } from '@kuiralabs/midnight-chain/lib/ledger-guard'; export type LocalnetState = 'already-running'; @@ -12,12 +12,16 @@ export interface EnsureLocalnetResult { state: LocalnetState; } -/** Require a running ledger-9 stack, at the endpoints saved under the state root `root`; throws with setup instructions if none answers. */ -export async function ensureLocalnetRunning(root: string, onProgress?: (msg: string) => void): Promise { +/** + * Require a running ledger-9 stack, at the endpoints saved under the state + * root `root` (or the local stack detected, unless the host's `settings` turn + * detection off); throws with setup instructions if none answers. + */ +export async function ensureLocalnetRunning(root: string, settings: NetworkSettings, onProgress?: (msg: string) => void): Promise { const { name, config } = resolveNetwork({ args: { command: 'dev', subcommand: undefined, positionals: [], flags: { network: 'undeployed' } }, configDir: root, - }); + }, settings); onProgress?.(`Checking the ledger-9 stack at ${config.node}`); await assertLedger9StackReachable(name, config); return { state: 'already-running' }; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index c2b63a42..84765424 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -9,7 +9,7 @@ import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create import { passphraseForNewSecret } from '../passphrase.ts'; import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { resolveNetwork, type NetworkSettings } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; @@ -70,7 +70,7 @@ function walletSteps(root: string, host: UnlockHost, network: NetworkConfig, sdk */ export async function provisionDevWallets(opts: ProvisionOptions): Promise { const { root } = opts; - const steps = 'steps' in opts ? opts.steps : walletSteps(root, opts.host, undeployedNetwork(root), opts.sdkWarnings); + const steps = 'steps' in opts ? opts.steps : walletSteps(root, opts.host, undeployedNetwork(root, opts.host.settings()), opts.sdkWarnings); const results: ProvisionedWallet[] = []; const created: string[] = []; @@ -139,12 +139,12 @@ function walletExists(root: string, name: string): boolean { return existsSync(walletFilePath(root, name)); } -/** The local network, with any endpoints saved for it, as the wallet commands resolve it. */ -function undeployedNetwork(root: string): NetworkConfig { +/** The local network, with any endpoints saved for it, as the wallet commands resolve it with the host's settings. */ +function undeployedNetwork(root: string, settings: NetworkSettings): NetworkConfig { return resolveNetwork({ args: { command: 'dev', subcommand: undefined, positionals: [], flags: { network: 'undeployed' } }, configDir: root, - }).config; + }, settings).config; } async function generateWallet(root: string, host: UnlockHost, name: string, signal?: AbortSignal): Promise { diff --git a/src/lib/passphrase.ts b/src/lib/passphrase.ts index 603e1d3a..20baac96 100644 --- a/src/lib/passphrase.ts +++ b/src/lib/passphrase.ts @@ -13,7 +13,7 @@ import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/e import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { defineHostSlot, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { PASSPHRASE_ENV, settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core/lib/settings'; /** The variable a non-interactive run sets the passphrase in (named in settings.ts). */ export { PASSPHRASE_ENV }; @@ -34,8 +34,9 @@ export class NoPassphraseError extends UsageError { } } -/** Where the passphrase is read from besides the prompter: the environment (the settings', unless given). */ +/** Where the passphrase is read from besides the prompter. */ export interface PassphraseSource { + /** The environment to read MN_PASSPHRASE from: given, it stands in for the host's settings; readPassphrase reads none without it. */ env?: Record; /** Ask twice and refuse two that differ: for setting the passphrase. */ confirm?: boolean; @@ -51,9 +52,9 @@ const ask = async (prompter: Prompter, question: string): Promise => { return line; }; -/** The passphrase: from MN_PASSPHRASE, else asked for through `prompter` (at the terminal) when it can ask. */ +/** The passphrase: from MN_PASSPHRASE in `source.env`, else asked for through `prompter` (at the terminal) when it can ask. */ export async function readPassphrase(prompter: Prompter | null, source: PassphraseSource = {}): Promise { - const fromEnv = source.env !== undefined ? source.env[PASSPHRASE_ENV] : settings().passphrase; + const fromEnv = source.env?.[PASSPHRASE_ENV]; if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv; if (prompter === null || !prompter.isInteractive()) throw new NoPassphraseError(); const passphrase = await ask(prompter, source.confirm ? 'New passphrase for mn: ' : 'Passphrase for mn: '); @@ -87,24 +88,30 @@ export function checkPassphrase(root: string, passphrase: string): void { /** The shortest passphrase mn accepts when one is set. */ export const MIN_PASSPHRASE_LENGTH = 12; -/** What a passphrase is had through: the host's prompter, and the host's record of the passphrases it has unlocked. */ -export type PassphraseHost = Pick; +/** What a passphrase is had through: the host's settings (MN_PASSPHRASE), its prompter, and its record of the passphrases it has unlocked. */ +export type PassphraseHost = Pick; + +/** `source`, reading MN_PASSPHRASE from the host's settings unless it gives an environment of its own. */ +const withHostPassphrase = (host: PassphraseHost, source: PassphraseSource): PassphraseSource => + source.env !== undefined ? source : { ...source, env: { [PASSPHRASE_ENV]: host.settings().passphrase } }; // The passphrase each host has unlocked, by state root: one prompt per run. const UNLOCKED = defineHostSlot('passphrase.unlocked', () => new Map()); /** * mn's passphrase, read and checked against the one set; asked for once per - * run of `host`. One already checked is taken again only when the environment - * names no other: a changed MN_PASSPHRASE is checked afresh. + * run of `host`. One already checked is taken again only when the host's + * settings (or `source.env`) name no other: a changed MN_PASSPHRASE is + * checked afresh. */ export async function unlockPassphrase(host: PassphraseHost, root: string, source: PassphraseSource = {}): Promise { const unlocked = host.slot(UNLOCKED); const known = unlocked.get(root); - const fromEnv = source.env !== undefined ? source.env[PASSPHRASE_ENV] : settings().passphrase; + const read = withHostPassphrase(host, source); + const fromEnv = read.env?.[PASSPHRASE_ENV]; if (known !== undefined && (fromEnv === undefined || fromEnv === '' || fromEnv === known)) return known; if (!isPassphraseSet(root)) throw new UsageError('mn has no passphrase yet. Set one with: midnight wallet protect'); - const passphrase = await readPassphrase(host.prompter, source); + const passphrase = await readPassphrase(host.prompter, read); checkPassphrase(root, passphrase); unlocked.set(root, passphrase); return passphrase; @@ -116,7 +123,7 @@ export async function unlockPassphrase(host: PassphraseHost, root: string, sourc */ export async function passphraseForNewSecret(host: PassphraseHost, root: string, source: PassphraseSource = {}): Promise { if (isPassphraseSet(root)) return unlockPassphrase(host, root, source); - const passphrase = await readPassphrase(host.prompter, { ...source, confirm: true }); + const passphrase = await readPassphrase(host.prompter, { ...withHostPassphrase(host, source), confirm: true }); if ([...passphrase].length < MIN_PASSPHRASE_LENGTH) { throw new UsageError(`mn's passphrase must be at least ${MIN_PASSPHRASE_LENGTH} characters.`); } diff --git a/src/lib/seed-resolver.ts b/src/lib/seed-resolver.ts index f065352f..f149e8fb 100644 --- a/src/lib/seed-resolver.ts +++ b/src/lib/seed-resolver.ts @@ -6,7 +6,6 @@ import { getFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { resolveWalletPath, unlockWallet, type UnlockHost, type WalletConfig } from './wallet-config.ts'; -import { settings } from '@kuiralabs/midnight-cli-core/lib/settings'; export interface ResolvedSeed { /** The wallet seed: 32-byte raw, or 64-byte BIP-39 (mnemonic-derived). */ @@ -52,11 +51,11 @@ export function parseSeedHex(input: string, label: string): Buffer { * `--seed ` → `MN_SEED` (env, kept off the process list) → `--wallet ` → active wallet. * Returns the seed plus the backing wallet file/config (both null for a `--seed` / `MN_SEED` * source), so a caller that caches to the wallet file can skip that when there is none. - * Wallets are the ones under the state root `root`. + * Wallets are the ones under the state root `root`; MN_SEED is the one in `host`'s settings. */ export async function resolveSeedSource(args: ParsedArgs, root: string, host: UnlockHost, opts: ResolveSeedOptions = {}): Promise { const seedFlag = getFlag(args, 'seed'); - const seedSource = seedFlag ?? settings().seed; + const seedSource = seedFlag ?? host.settings().seed; if (seedSource) { return { seed: parseSeedHex(seedSource, seedFlag ? '--seed' : 'MN_SEED'), diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 99896c32..5f5c169a 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -51,7 +51,7 @@ export function resolveServeTarget(options: ServeManagerOptions): { networkName: flags: { ...(options.network ? { network: options.network } : {}), ...endpointFlags(options.endpoints ?? {}) }, }, configDir: options.root, - }); + }, options.host.settings()); applyEndpointOverrides(networkConfig, options.endpoints ?? {}, networkName, options.root); return { networkName, networkConfig }; } diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index 45fc61ad..a8bd198b 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -62,7 +62,7 @@ async function runStep( return stepCacheClear(config, ctx.root); } if (step === 'localnet-up') { - return stepLocalnetUp(config, ctx.root, callbacks); + return stepLocalnetUp(config, ctx, callbacks); } if (step.startsWith('balance:')) { const amount = parseInt(step.split(':')[1], 10); @@ -90,14 +90,14 @@ async function stepCacheClear(config: DappTestConfig, root: string): Promise { +async function stepLocalnetUp(config: DappTestConfig, ctx: PrepContext, callbacks: PrepCallbacks): Promise { // This build can't start a localnet (no published ledger-9 indexer image), // so the step requires a running ledger-9 stack at the resolved endpoints. const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: undefined, positionals: [], flags: { network } }, - configDir: root, - }); + configDir: ctx.root, + }, ctx.host.settings()); await assertLedger9StackReachable(network, networkConfig); callbacks.onMessage(`Using the ledger-9 stack at ${networkConfig.node} (indexer ${networkConfig.indexer})`); } @@ -107,7 +107,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: undefined, positionals: [], flags: { network } }, configDir: ctx.root, - }); + }, ctx.host.settings()); // On a ledger-8 chain the SDK's sync would retry forever. await assertLedgerSupported(network, networkConfig); @@ -167,7 +167,7 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre const { config: networkConfig } = resolveNetwork({ args: { command: 'test', subcommand: undefined, positionals: [], flags: { network } }, configDir: ctx.root, - }); + }, ctx.host.settings()); await assertLedgerSupported(network, networkConfig); const walletConfig = await unlockWallet(resolveWalletPath(ctx.root), { root: ctx.root, host: ctx.host }); diff --git a/vitest.config.ts b/vitest.config.ts index 2c28b339..8ed02be3 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -14,8 +14,6 @@ export default defineConfig({ // Likewise, local stack detection must not depend on what docker runs on // the machine; it's covered with captured docker output in local-stacks.test.ts. env: { MN_DISABLE_NATIVE_DUST: '1', MN_NO_LOCAL_DETECT: '1', NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --conditions=midnight-cli-source`.trim() }, - // Libraries read those variables, and the ones tests set, as settings the shell gives them. - setupFiles: ['src/__tests__/helpers/shell-settings.ts'], // Tests seal and open wallets and accounts at their real cost (scrypt at // 128 MiB, the private state's own key derivation): a backup test takes // 3 s on a laptop, 8 s on a CI runner, and 32 s on a runner that was four From 4ae70d541075913244bba869c26ca36070908f4d Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 08:59:19 -0800 Subject: [PATCH 62/88] Error codes owned per package, classified by code (3C, 1-2 of 8) Each package defines its codes beside its guidance (core, chain, wallet, contract, dev, grant), each with its exit code and summary; the registry assembles the installed packages' codes and refuses one defined twice. classifyError looks an error's code up first; the old message rules stay only as a fallback, deleted in a later commit. Approved changes (Y52): NO_STATE_ROOT, NO_PAYER and NO_NODE_RUNTIME come out by name, an escaped stale cache as STALE_CACHE, a failed MCP command run as the new COMMAND_FAILED; and the CLI classifies like the MCP server: a usage error carries its own code, so a missing passphrase reports PASSPHRASE_REQUIRED, not INVALID_ARGS. A snapshot probe with no passphrase shows it. Suite 2626, beta 172; the snapshot changes only by the four new rows in the agent manual and the new probe. --- packages/chain/api-report.md | 25 ++ packages/chain/src/commands/chain.codes.ts | 11 + packages/cli-core/api-report.md | 226 +++++++++++++++++- packages/cli-core/src/commands/core.codes.ts | 51 ++++ .../cli-core/src/commands/core.guidance.ts | 7 + .../cli-core/src/lib/command-definition.ts | 16 +- packages/cli-core/src/lib/error-codes.ts | 41 ++++ packages/cli-core/src/lib/errors.ts | 9 +- packages/cli-core/src/lib/exit-codes.ts | 39 ++- packages/cli-core/src/lib/json-output.ts | 4 +- scripts/behaviour-snapshot.mjs | 17 +- scripts/check-layering.mjs | 6 +- src/__tests__/command-flags.test.ts | 5 +- .../engine-beta-error-code-parity.test.ts | 16 ++ src/__tests__/error-code-parity.test.ts | 124 ++++++++++ src/__tests__/error-code-registry.test.ts | 74 ++++++ src/__tests__/shell-error-codes.test.ts | 55 +++++ src/commands/contract.codes.ts | 8 + src/commands/contract.guidance.ts | 8 + src/commands/dev.codes.ts | 8 + src/commands/grant.codes.ts | 8 + src/commands/wallet.codes.ts | 8 + src/lib/installed-commands.ts | 22 +- src/mcp-server.ts | 2 +- src/wallet.ts | 27 +-- 25 files changed, 763 insertions(+), 54 deletions(-) create mode 100644 packages/chain/src/commands/chain.codes.ts create mode 100644 packages/cli-core/src/commands/core.codes.ts create mode 100644 packages/cli-core/src/lib/error-codes.ts create mode 100644 src/__tests__/engine-beta-error-code-parity.test.ts create mode 100644 src/__tests__/error-code-parity.test.ts create mode 100644 src/__tests__/error-code-registry.test.ts create mode 100644 src/__tests__/shell-error-codes.test.ts create mode 100644 src/commands/contract.codes.ts create mode 100644 src/commands/dev.codes.ts create mode 100644 src/commands/grant.codes.ts create mode 100644 src/commands/wallet.codes.ts diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md index e4f284e1..5e34d170 100644 --- a/packages/chain/api-report.md +++ b/packages/chain/api-report.md @@ -2,6 +2,31 @@ Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. +## `@kuiralabs/midnight-chain/commands/chain.codes` + +```ts +export declare const chainCodes: readonly [ + { + readonly code: "UNSUPPORTED_LEDGER"; + readonly exitCode: 4; + readonly summary: "The chain is on ledger 8; this build supports ledger 9 only."; + readonly recovery: "Use midnight-wallet-cli 0.5.x for that network."; + }, + { + readonly code: "LOCAL_STACK_UNREACHABLE"; + readonly exitCode: 4; + readonly summary: "No ledger-9 stack answers at the configured endpoints."; + readonly recovery: "Start one, or fix the endpoints."; + }, + { + readonly code: "CHAIN_CLOCK_BEHIND"; + readonly exitCode: 4; + readonly summary: "The chain's clock is behind this computer's (a local chain after the machine slept), so Dust estimates don't hold."; + readonly recovery: "Wait for it to catch up, or restart the local chain."; + } +]; +``` + ## `@kuiralabs/midnight-chain/commands/chain.guidance` ```ts diff --git a/packages/chain/src/commands/chain.codes.ts b/packages/chain/src/commands/chain.codes.ts new file mode 100644 index 00000000..6acd9de4 --- /dev/null +++ b/packages/chain/src/commands/chain.codes.ts @@ -0,0 +1,11 @@ +// The error codes the chain package's checks raise: the chain's ledger, the +// local stack's endpoints, and the chain's clock. + +import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +export const chainCodes = defineCodes([ + { code: 'UNSUPPORTED_LEDGER', exitCode: EXIT_NETWORK_ERROR, summary: 'The chain is on ledger 8; this build supports ledger 9 only.', recovery: 'Use midnight-wallet-cli 0.5.x for that network.' }, + { code: 'LOCAL_STACK_UNREACHABLE', exitCode: EXIT_NETWORK_ERROR, summary: 'No ledger-9 stack answers at the configured endpoints.', recovery: 'Start one, or fix the endpoints.' }, + { code: 'CHAIN_CLOCK_BEHIND', exitCode: EXIT_NETWORK_ERROR, summary: "The chain's clock is behind this computer's (a local chain after the machine slept), so Dust estimates don't hold.", recovery: 'Wait for it to catch up, or restart the local chain.' }, +]); diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 2c0cba02..1031fc9f 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -17,6 +17,195 @@ import type { CommandDefinition } from "../lib/command-definition.ts"; export declare const configDefinition: CommandDefinition; ``` +## `@kuiralabs/midnight-cli-core/commands/core.codes` + +```ts +export declare const coreCodes: readonly [ + { + readonly code: "INVALID_ARGS"; + readonly exitCode: 2; + readonly summary: "Missing or invalid arguments."; + readonly recovery: "Fix the arguments and run it again; `midnight help ` shows them."; + }, + { + readonly code: "WRONG_PASSPHRASE"; + readonly exitCode: 2; + readonly summary: "mn's passphrase was wrong, or a sealed secret was changed."; + readonly recovery: "Run it again with the passphrase mn was protected with."; + }, + { + readonly code: "PASSPHRASE_REQUIRED"; + readonly exitCode: 2; + readonly summary: "A secret was needed and no passphrase could be had."; + readonly recovery: "Set MN_PASSPHRASE, or run at a terminal."; + }, + { + readonly code: "NETWORK_ERROR"; + readonly exitCode: 4; + readonly summary: "Connection refused, timeout, DNS failure."; + readonly recovery: "Check that the node, indexer and proof server at the configured endpoints are running."; + }, + { + readonly code: "AMBIGUOUS_LOCAL_STACKS"; + readonly exitCode: 4; + readonly summary: "Several local Midnight stacks run and no endpoints were given."; + readonly recovery: "Pass endpoint flags or `midnight config set` them."; + }, + { + readonly code: "BLOCKFROST_PROJECT_ID_REQUIRED"; + readonly exitCode: 4; + readonly summary: "The network is served by Blockfrost and no project id is set."; + readonly recovery: "`mn config set blockfrost-project-id `."; + }, + { + readonly code: "BLOCKFROST_PROJECT_ID_REJECTED"; + readonly exitCode: 4; + readonly summary: "Blockfrost refused the project id."; + readonly recovery: "Check it at blockfrost.io and set it again."; + }, + { + readonly code: "BLOCKFROST_LIMIT_REACHED"; + readonly exitCode: 4; + readonly summary: "Blockfrost is holding the project back (its plan's daily limit, or too many requests at once)."; + readonly recovery: "Wait, or see the project's plan."; + }, + { + readonly code: "ENDPOINT_SHUT_DOWN"; + readonly exitCode: 4; + readonly summary: "An endpoint set by flag or config was shut down by its operator."; + readonly recovery: "Unset it (`mn config unset indexer-ws`)."; + }, + { + readonly code: "CANCELLED"; + readonly exitCode: 7; + readonly summary: "Operation cancelled (SIGINT)."; + }, + { + readonly code: "OTHER_SDK_SET"; + readonly exitCode: 1; + readonly summary: "The process has loaded one SDK set's engine and the call's network runs on the other."; + readonly recovery: "Run the call in a process of its own (for MCP, a server for that network)."; + }, + { + readonly code: "MIXED_SDK_LAYOUT"; + readonly exitCode: 1; + readonly summary: "An engine's SDK packages reach more than one copy of its ledger: mn was installed without its shrinkwrap (bun's installer)."; + readonly recovery: "Install mn with npm."; + }, + { + readonly code: "UNSUPPORTED_NODE"; + readonly exitCode: 1; + readonly summary: "This Node.js is older than mn supports (22)."; + readonly recovery: "Install a current Node.js."; + }, + { + readonly code: "NO_STATE_ROOT"; + readonly exitCode: 1; + readonly summary: "The host gave mn no place to keep its state."; + readonly recovery: "Give the host its paths (createHost paths)."; + }, + { + readonly code: "NO_PAYER"; + readonly exitCode: 1; + readonly summary: "A command that submits a transaction was called without a payer."; + readonly recovery: "Give the call a payer."; + }, + { + readonly code: "COMMAND_FAILED"; + readonly exitCode: 1; + readonly summary: "A command ended with a non-zero exit code without throwing (a test run whose tests failed); the message carries its result."; + readonly recovery: "Read the command's result in the message."; + }, + { + readonly code: "UNKNOWN"; + readonly exitCode: 1; + readonly summary: "Unclassified error."; + }, + { + readonly code: "PROOF_TIMEOUT"; + readonly exitCode: 6; + readonly summary: "ZK proof generation timed out."; + readonly recovery: "Retry: proofs can be slow under load."; + }, + { + readonly code: "PROOF_FAILURE"; + readonly exitCode: 6; + readonly summary: "Proof server rejected or failed to generate the ZK proof."; + readonly recovery: "Ensure the proof server is running, then retry; if persistent, `mn cache clear` to force a fresh sync."; + }, + { + readonly code: "INVALID_DUST_PROOF"; + readonly exitCode: 6; + readonly summary: "Chain rejected the dust spend proof as malformed (substrate \"Custom error 170\")."; + readonly recovery: "`mn cache clear --wallet ` then retry."; + }, + { + readonly code: "TX_REJECTED"; + readonly exitCode: 6; + readonly summary: "Transaction rejected by the node."; + }, + { + readonly code: "STALE_UTXO"; + readonly exitCode: 6; + readonly summary: "UTXOs consumed by another transaction (substrate \"error code 115\")."; + readonly recovery: "Re-sync (the next call refreshes the state) and retry."; + }, + { + readonly code: "STALE_CACHE"; + readonly exitCode: 6; + readonly summary: "Local wallet cache disagrees with chain state (a localnet reset, a remote testnet re-index)."; + readonly recovery: "`mn cache clear --wallet ` then retry."; + }, + { + readonly code: "SYNC_TIMEOUT"; + readonly exitCode: 4; + readonly summary: "Wallet sync exceeded its deadline."; + readonly recovery: "Retry: the cache resumes from the last applied event."; + }, + { + readonly code: "DUST_REQUIRED"; + readonly exitCode: 5; + readonly summary: "Not enough Dust for the fee."; + readonly recovery: "Not registered: `mn dust register`. Generating: retry when the message says, or register more NIGHT."; + }, + { + readonly code: "DUST_GENERATING"; + readonly exitCode: 5; + readonly summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust."; + readonly recovery: "Run `mn dust register` again at the time the message gives, or add NIGHT."; + }, + { + readonly code: "INSUFFICIENT_BALANCE"; + readonly exitCode: 5; + readonly summary: "Not enough NIGHT for the operation."; + }, + { + readonly code: "NOT_AN_OFFER"; + readonly exitCode: 2; + readonly summary: "Bytes given as a swap offer are not one."; + readonly recovery: "Ask the maker for the offer again."; + }, + { + readonly code: "TERMS_MISMATCH"; + readonly exitCode: 2; + readonly summary: "A swap offer's own terms differ from the agreed ones."; + readonly recovery: "Don't take it; agree the terms again with the maker."; + }, + { + readonly code: "OFFER_EXPIRED"; + readonly exitCode: 2; + readonly summary: "A swap offer is past the expiry its maker set."; + readonly recovery: "Ask the maker for a new one."; + }, + { + readonly code: "OFFER_COINS_IN_USE"; + readonly exitCode: 2; + readonly summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it."; + readonly recovery: "Cancel the offer first (mn swap cancel), or wait until it is taken."; + } +]; +``` + ## `@kuiralabs/midnight-cli-core/commands/core.guidance` ```ts @@ -289,6 +478,7 @@ export declare function getValidConfigKeys(): readonly string[]; ```ts import { type ParsedArgs } from "./argv.ts"; import { type PackageGuidance } from "./agent-guidance.ts"; +import type { CodeDefinition, CodeRegistry } from "./error-codes.ts"; import type { CallContext, CommandOutcome } from "./call-context.ts"; import type { Host } from "./host.ts"; export interface ParamSchema { @@ -409,6 +599,7 @@ export interface CommandPackage { readonly name: string; readonly commands: readonly CommandDefinition[]; readonly guidance: PackageGuidance; + readonly codes?: readonly CodeDefinition[]; } export interface RegisteredTool extends ToolDefinition { readonly inputSchema: ToolInputSchema; @@ -418,7 +609,7 @@ export interface GlobalFlagHelp { readonly name: string; readonly description: string; } -export interface CommandRegistry { +export interface CommandRegistry extends CodeRegistry { readonly commands: readonly CommandDefinition[]; readonly globalFlags: readonly FlagDefinition[]; readonly globalFlagsHelp: readonly GlobalFlagHelp[]; @@ -967,6 +1158,25 @@ export declare class OtherSdkSetError extends Error { export declare function claimSdkSet(set: SdkSet): void; ``` +## `@kuiralabs/midnight-cli-core/lib/error-codes` + +```ts +export interface CodeDefinition { + readonly code: string; + readonly exitCode: number; + readonly summary: string; + readonly recovery?: string; + readonly order?: number; +} +export interface CodeRegistry { + code(code: string): CodeDefinition | undefined; +} +export declare class CodeDefinitionError extends Error { + constructor(message: string); +} +export declare function defineCodes(codes: T): T; +``` + ## `@kuiralabs/midnight-cli-core/lib/error-trim` ```ts @@ -977,6 +1187,7 @@ export declare function trimAgentMessage(raw: string): string; ```ts export declare class UsageError extends Error { + readonly code: string; constructor(message: string); } export declare function isUsageError(err: unknown): err is UsageError; @@ -992,6 +1203,7 @@ export declare class TransactionRefusedError extends Error { }); } export declare class CommandFailedError extends Error { + readonly code = "COMMAND_FAILED"; readonly exitCode: number; readonly result: Readonly>; constructor(command: string, exitCode: number, result: Readonly>); @@ -1025,6 +1237,7 @@ export declare const execProgram: ExecRunner; ## `@kuiralabs/midnight-cli-core/lib/exit-codes` ```ts +import type { CodeRegistry } from "./error-codes.ts"; export declare const EXIT_SUCCESS = 0; export declare const EXIT_GENERAL_ERROR = 1; export declare const EXIT_INVALID_ARGS = 2; @@ -1067,14 +1280,18 @@ export declare const ERROR_CODES: { readonly OFFER_COINS_IN_USE: "OFFER_COINS_IN_USE"; readonly WRONG_PASSPHRASE: "WRONG_PASSPHRASE"; readonly PASSPHRASE_REQUIRED: "PASSPHRASE_REQUIRED"; + readonly NO_STATE_ROOT: "NO_STATE_ROOT"; + readonly NO_PAYER: "NO_PAYER"; + readonly NO_NODE_RUNTIME: "NO_NODE_RUNTIME"; + readonly COMMAND_FAILED: "COMMAND_FAILED"; readonly UNKNOWN: "UNKNOWN"; }; export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES]; interface ClassifiedError { exitCode: number; - errorCode: ErrorCode; + errorCode: string; } -export declare function classifyError(err: Error): ClassifiedError; +export declare function classifyError(err: Error, codes?: CodeRegistry): ClassifiedError; export declare function humanizeNetworkError(message: string): string; ``` @@ -1130,9 +1347,8 @@ export declare function createHost(options?: HostOptions): Host; ## `@kuiralabs/midnight-cli-core/lib/json-output` ```ts -import { type ErrorCode } from "./exit-codes.ts"; export declare function writeJsonResult(data: Readonly>): void; -export declare function writeJsonError(err: Error, errorCode: ErrorCode, exitCode: number): void; +export declare function writeJsonError(err: Error, errorCode: string, exitCode: number): void; ``` ## `@kuiralabs/midnight-cli-core/lib/keystore` diff --git a/packages/cli-core/src/commands/core.codes.ts b/packages/cli-core/src/commands/core.codes.ts new file mode 100644 index 00000000..e416ab61 --- /dev/null +++ b/packages/cli-core/src/commands/core.codes.ts @@ -0,0 +1,51 @@ +// The error codes core owns: those its base raises or more than one package +// does (arguments, the passphrase, networks and Blockfrost, cancellation, the +// SDK set and its layout, the Node.js version, the state root, the payer, a +// failed command), and those of the engine contract, which every engine +// raises (proofs, transactions, stale state, sync, Dust and balance, swap offers). + +import { defineCodes } from '../lib/error-codes.ts'; +import { + EXIT_CANCELLED, + EXIT_GENERAL_ERROR, + EXIT_INSUFFICIENT_BALANCE, + EXIT_INVALID_ARGS, + EXIT_NETWORK_ERROR, + EXIT_TX_REJECTED, +} from '../lib/exit-codes.ts'; + +export const coreCodes = defineCodes([ + { code: 'INVALID_ARGS', exitCode: EXIT_INVALID_ARGS, summary: 'Missing or invalid arguments.', recovery: 'Fix the arguments and run it again; `midnight help ` shows them.' }, + { code: 'WRONG_PASSPHRASE', exitCode: EXIT_INVALID_ARGS, summary: "mn's passphrase was wrong, or a sealed secret was changed.", recovery: 'Run it again with the passphrase mn was protected with.' }, + { code: 'PASSPHRASE_REQUIRED', exitCode: EXIT_INVALID_ARGS, summary: 'A secret was needed and no passphrase could be had.', recovery: 'Set MN_PASSPHRASE, or run at a terminal.' }, + { code: 'NETWORK_ERROR', exitCode: EXIT_NETWORK_ERROR, summary: 'Connection refused, timeout, DNS failure.', recovery: 'Check that the node, indexer and proof server at the configured endpoints are running.' }, + { code: 'AMBIGUOUS_LOCAL_STACKS', exitCode: EXIT_NETWORK_ERROR, summary: 'Several local Midnight stacks run and no endpoints were given.', recovery: 'Pass endpoint flags or `midnight config set` them.' }, + { code: 'BLOCKFROST_PROJECT_ID_REQUIRED', exitCode: EXIT_NETWORK_ERROR, summary: 'The network is served by Blockfrost and no project id is set.', recovery: '`mn config set blockfrost-project-id `.' }, + { code: 'BLOCKFROST_PROJECT_ID_REJECTED', exitCode: EXIT_NETWORK_ERROR, summary: 'Blockfrost refused the project id.', recovery: 'Check it at blockfrost.io and set it again.' }, + { code: 'BLOCKFROST_LIMIT_REACHED', exitCode: EXIT_NETWORK_ERROR, summary: "Blockfrost is holding the project back (its plan's daily limit, or too many requests at once).", recovery: "Wait, or see the project's plan." }, + { code: 'ENDPOINT_SHUT_DOWN', exitCode: EXIT_NETWORK_ERROR, summary: 'An endpoint set by flag or config was shut down by its operator.', recovery: 'Unset it (`mn config unset indexer-ws`).' }, + { code: 'CANCELLED', exitCode: EXIT_CANCELLED, summary: 'Operation cancelled (SIGINT).' }, + { code: 'OTHER_SDK_SET', exitCode: EXIT_GENERAL_ERROR, summary: "The process has loaded one SDK set's engine and the call's network runs on the other.", recovery: 'Run the call in a process of its own (for MCP, a server for that network).' }, + { code: 'MIXED_SDK_LAYOUT', exitCode: EXIT_GENERAL_ERROR, summary: "An engine's SDK packages reach more than one copy of its ledger: mn was installed without its shrinkwrap (bun's installer).", recovery: 'Install mn with npm.' }, + { code: 'UNSUPPORTED_NODE', exitCode: EXIT_GENERAL_ERROR, summary: 'This Node.js is older than mn supports (22).', recovery: 'Install a current Node.js.' }, + { code: 'NO_STATE_ROOT', exitCode: EXIT_GENERAL_ERROR, summary: 'The host gave mn no place to keep its state.', recovery: 'Give the host its paths (createHost paths).' }, + { code: 'NO_PAYER', exitCode: EXIT_GENERAL_ERROR, summary: 'A command that submits a transaction was called without a payer.', recovery: 'Give the call a payer.' }, + { code: 'COMMAND_FAILED', exitCode: EXIT_GENERAL_ERROR, summary: 'A command ended with a non-zero exit code without throwing (a test run whose tests failed); the message carries its result.', recovery: "Read the command's result in the message." }, + { code: 'UNKNOWN', exitCode: EXIT_GENERAL_ERROR, summary: 'Unclassified error.' }, + + // The engine contract: what every engine raises. + { code: 'PROOF_TIMEOUT', exitCode: EXIT_TX_REJECTED, summary: 'ZK proof generation timed out.', recovery: 'Retry: proofs can be slow under load.' }, + { code: 'PROOF_FAILURE', exitCode: EXIT_TX_REJECTED, summary: 'Proof server rejected or failed to generate the ZK proof.', recovery: 'Ensure the proof server is running, then retry; if persistent, `mn cache clear` to force a fresh sync.' }, + { code: 'INVALID_DUST_PROOF', exitCode: EXIT_TX_REJECTED, summary: 'Chain rejected the dust spend proof as malformed (substrate "Custom error 170").', recovery: '`mn cache clear --wallet ` then retry.' }, + { code: 'TX_REJECTED', exitCode: EXIT_TX_REJECTED, summary: 'Transaction rejected by the node.' }, + { code: 'STALE_UTXO', exitCode: EXIT_TX_REJECTED, summary: 'UTXOs consumed by another transaction (substrate "error code 115").', recovery: 'Re-sync (the next call refreshes the state) and retry.' }, + { code: 'STALE_CACHE', exitCode: EXIT_TX_REJECTED, summary: 'Local wallet cache disagrees with chain state (a localnet reset, a remote testnet re-index).', recovery: '`mn cache clear --wallet ` then retry.' }, + { code: 'SYNC_TIMEOUT', exitCode: EXIT_NETWORK_ERROR, summary: 'Wallet sync exceeded its deadline.', recovery: 'Retry: the cache resumes from the last applied event.' }, + { code: 'DUST_REQUIRED', exitCode: EXIT_INSUFFICIENT_BALANCE, summary: 'Not enough Dust for the fee.', recovery: 'Not registered: `mn dust register`. Generating: retry when the message says, or register more NIGHT.' }, + { code: 'DUST_GENERATING', exitCode: EXIT_INSUFFICIENT_BALANCE, summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust.", recovery: 'Run `mn dust register` again at the time the message gives, or add NIGHT.' }, + { code: 'INSUFFICIENT_BALANCE', exitCode: EXIT_INSUFFICIENT_BALANCE, summary: 'Not enough NIGHT for the operation.' }, + { code: 'NOT_AN_OFFER', exitCode: EXIT_INVALID_ARGS, summary: 'Bytes given as a swap offer are not one.', recovery: 'Ask the maker for the offer again.' }, + { code: 'TERMS_MISMATCH', exitCode: EXIT_INVALID_ARGS, summary: "A swap offer's own terms differ from the agreed ones.", recovery: "Don't take it; agree the terms again with the maker." }, + { code: 'OFFER_EXPIRED', exitCode: EXIT_INVALID_ARGS, summary: 'A swap offer is past the expiry its maker set.', recovery: 'Ask the maker for a new one.' }, + { code: 'OFFER_COINS_IN_USE', exitCode: EXIT_INVALID_ARGS, summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it.", recovery: 'Cancel the offer first (mn swap cancel), or wait until it is taken.' }, +]); diff --git a/packages/cli-core/src/commands/core.guidance.ts b/packages/cli-core/src/commands/core.guidance.ts index b14d26c9..e8763c82 100644 --- a/packages/cli-core/src/commands/core.guidance.ts +++ b/packages/cli-core/src/commands/core.guidance.ts @@ -54,6 +54,13 @@ export const coreGuidance: PackageGuidance = { server for that network MIXED_SDK_LAYOUT 1 mn was installed without its shrinkwrap (bun's installer): install it with npm + NO_STATE_ROOT 1 The host gave mn no place to keep its state + (a program's createHost without paths) + NO_PAYER 1 A command that submits a transaction was + called without a payer + COMMAND_FAILED 1 A command ended with a non-zero exit code + (an MCP test run whose tests failed); the + message carries its result NOT_AN_OFFER 2 The bytes given as a swap offer are not one; ask the maker for it again TERMS_MISMATCH 2 A swap offer's own terms differ from the agreed diff --git a/packages/cli-core/src/lib/command-definition.ts b/packages/cli-core/src/lib/command-definition.ts index 67396e09..7fb9cd1a 100644 --- a/packages/cli-core/src/lib/command-definition.ts +++ b/packages/cli-core/src/lib/command-definition.ts @@ -13,6 +13,7 @@ import { getValidNetworkNames } from './network.ts'; import { FULL_FLAG, type ParsedArgs } from './argv.ts'; import { type PackageGuidance, type ToolsTableRow, assertDistinctPlaces } from './agent-guidance.ts'; +import type { CodeDefinition, CodeRegistry } from './error-codes.ts'; import type { CallContext, CommandOutcome } from './call-context.ts'; import type { Host } from './host.ts'; @@ -205,11 +206,13 @@ export interface CommandDefinition { readonly mcp?: { readonly tools: readonly ToolDefinition[] }; } -/** A package as the shell installs it: its commands and what it tells agents. */ +/** A package as the shell installs it: its commands, what it tells agents, and the error codes it owns. */ export interface CommandPackage { readonly name: string; readonly commands: readonly CommandDefinition[]; readonly guidance: PackageGuidance; + /** The error codes its errors carry; none: it owns no code. */ + readonly codes?: readonly CodeDefinition[]; } /** A tool as the registry holds it: its definition, its generated schema, and the command it runs. */ @@ -225,7 +228,8 @@ export interface GlobalFlagHelp { readonly description: string; } -export interface CommandRegistry { +/** The installed commands, and (through `code`) the error codes of the installed packages. */ +export interface CommandRegistry extends CodeRegistry { /** The definitions, in help's order. */ readonly commands: readonly CommandDefinition[]; /** Flags every command accepts. */ @@ -433,6 +437,7 @@ export function createCommandRegistry( find: (name) => commands.find((command) => command.name === name), tools: tools.sort((a, b) => a.order - b.order), packages: [], + code: () => undefined, }; } @@ -457,7 +462,7 @@ function checkGuidance(packages: readonly CommandPackage[]): void { /** * Collects packages into a registry, its commands in their definitions' - * order. Every command is in one package. + * order. Every command is in one package, and every error code in one package. */ export function createPackageRegistry( packages: readonly CommandPackage[], @@ -470,7 +475,10 @@ export function createPackageRegistry( assertUnique(all.map((command) => String(command.order)), 'command place'); const commands = [...all].sort((a, b) => a.order - b.order); checkGuidance(packages); - return { ...createCommandRegistry(commands, globalFlags, globalFlagsHelp), packages }; + const codes = packages.flatMap((pkg) => pkg.codes ?? []); + assertUnique(codes.map((definition) => definition.code), 'error code'); + const byCode = new Map(codes.map((definition) => [definition.code, definition])); + return { ...createCommandRegistry(commands, globalFlags, globalFlagsHelp), packages, code: (code) => byCode.get(code) }; } /** The Flags section of `help `, line by line, as shown. */ diff --git a/packages/cli-core/src/lib/error-codes.ts b/packages/cli-core/src/lib/error-codes.ts new file mode 100644 index 00000000..5e5c60c6 --- /dev/null +++ b/packages/cli-core/src/lib/error-codes.ts @@ -0,0 +1,41 @@ +// Error codes, owned per package: each package defines the codes its errors +// carry (in its .codes.ts, beside its guidance), with the exit code +// each ends the CLI with, and the shell assembles the installed packages' +// codes into one lookup, refusing a code two packages define. classifyError +// reads an error's `code` through that lookup. + +/** One error code: what `--json` and MCP report as `code`, and the CLI's exit code for it. */ +export interface CodeDefinition { + readonly code: string; + readonly exitCode: number; + /** What went wrong, in one line. */ + readonly summary: string; + /** What to do about it. */ + readonly recovery?: string; + /** Its place in the manual's table of codes: rows read in ascending order. */ + readonly order?: number; +} + +/** The codes known where an error is classified: the definition of a code, or undefined for one no installed package defines. */ +export interface CodeRegistry { + code(code: string): CodeDefinition | undefined; +} + +/** Thrown when a package's codes contradict themselves: one code defined twice. */ +export class CodeDefinitionError extends Error { + constructor(message: string) { + super(message); + this.name = 'CodeDefinitionError'; + Object.setPrototypeOf(this, CodeDefinitionError.prototype); + } +} + +/** A package's codes, as it exports them; refuses a code it defines twice. */ +export function defineCodes(codes: T): T { + const seen = new Set(); + for (const { code } of codes) { + if (seen.has(code)) throw new CodeDefinitionError(`Error code "${code}" is defined twice`); + seen.add(code); + } + return codes; +} diff --git a/packages/cli-core/src/lib/errors.ts b/packages/cli-core/src/lib/errors.ts index 7c0b4a5c..9bcb33de 100644 --- a/packages/cli-core/src/lib/errors.ts +++ b/packages/cli-core/src/lib/errors.ts @@ -12,9 +12,12 @@ /** * Thrown when the user invoked the CLI with missing or invalid arguments * that they should fix and retry. Renders in yellow with a "Usage" header - * instead of red "Error". + * instead of red "Error". Its code is INVALID_ARGS; a subclass names its own + * (NoPassphraseError: PASSPHRASE_REQUIRED). */ export class UsageError extends Error { + readonly code: string = 'INVALID_ARGS'; + constructor(message: string) { super(message); this.name = 'UsageError'; @@ -61,9 +64,11 @@ export class TransactionRefusedError extends Error { /** * A command that ended with a non-zero exit code without throwing (a test run * whose tests failed): the code, and the JSON result it wrote. A runner with no - * process exit code to set, such as the MCP server, reports it as a failure. + * process exit code to set, such as the MCP server, reports it as a failure, + * with the code COMMAND_FAILED. */ export class CommandFailedError extends Error { + readonly code = 'COMMAND_FAILED'; readonly exitCode: number; readonly result: Readonly>; diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index 630385c3..c7c872fd 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -1,4 +1,5 @@ import { CANCELLED_MESSAGE, isUsageError } from './errors.ts'; +import type { CodeRegistry } from './error-codes.ts'; // Structured exit codes and error classification for CLI // Used by both JSON mode and non-JSON error reporting @@ -13,6 +14,11 @@ export const EXIT_TX_REJECTED = 6; export const EXIT_CANCELLED = 7; // ── Machine-readable error code strings ───────────────── +/** + * @deprecated Each package defines its own codes (`.codes.ts`, made + * with defineCodes), and classifyError reads them from the installed + * packages' registry. Kept, with every code those define, until callers move. + */ export const ERROR_CODES = { INVALID_ARGS: 'INVALID_ARGS', WALLET_NOT_FOUND: 'WALLET_NOT_FOUND', @@ -71,6 +77,14 @@ export const ERROR_CODES = { WRONG_PASSPHRASE: 'WRONG_PASSPHRASE', /** A secret was needed and no passphrase could be had. Recovery: set MN_PASSPHRASE, or run at a terminal. */ PASSPHRASE_REQUIRED: 'PASSPHRASE_REQUIRED', + /** The host gave mn no place to keep its state. Recovery: give the host its paths. */ + NO_STATE_ROOT: 'NO_STATE_ROOT', + /** A command that submits a transaction was called without a payer. Recovery: give the call a payer. */ + NO_PAYER: 'NO_PAYER', + /** Contract scripts run under Node.js, and none was found on PATH. Recovery: install Node.js 22 or later, or run mn under Node. */ + NO_NODE_RUNTIME: 'NO_NODE_RUNTIME', + /** A command ended with a non-zero exit code without throwing (a test run whose tests failed), run where no process exit code can be set (MCP). */ + COMMAND_FAILED: 'COMMAND_FAILED', UNKNOWN: 'UNKNOWN', } as const; @@ -89,19 +103,34 @@ const SETUP_ERROR_CODES: ReadonlySet = new Set([ ERROR_CODES.ENDPOINT_SHUT_DOWN, ]); +/** @deprecated A code is a string a package defines; see ERROR_CODES. */ export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES]; interface ClassifiedError { exitCode: number; - errorCode: ErrorCode; + /** A code one of the installed packages defines (a plugin's included), or one of ERROR_CODES. */ + errorCode: string; +} + +/** + * The error's code and the exit code it ends the CLI with. An error that + * carries a code `codes` defines is classified by it; any other falls back to + * the rules below, which read its message. + */ +export function classifyError(err: Error, codes?: CodeRegistry): ClassifiedError { + const code = (err as { code?: unknown }).code; + const defined = typeof code === 'string' ? codes?.code(code) : undefined; + if (defined !== undefined) return { exitCode: defined.exitCode, errorCode: defined.code }; + return legacyByMessage(err); } /** - * Inspect an error message to determine the appropriate exit code and error code. - * Pattern-matches against known error messages from the CLI and Midnight SDK. - * Order matters: more specific patterns are checked before broader ones. + * The classification before codes were owned per package, unchanged: the + * typed codes it knew, then patterns over the message from the CLI and the + * Midnight SDK. Order matters: more specific patterns are checked before + * broader ones. */ -export function classifyError(err: Error): ClassifiedError { +function legacyByMessage(err: Error): ClassifiedError { // A usage error is the caller's to fix, whatever its text (the CLI and MCP agree on this). // (Tested through `unknown`: UsageError has Error's shape, so narrowing `err` itself would leave `never`.) const code = (err as { code?: unknown }).code; diff --git a/packages/cli-core/src/lib/json-output.ts b/packages/cli-core/src/lib/json-output.ts index bf1a05bf..332544c2 100644 --- a/packages/cli-core/src/lib/json-output.ts +++ b/packages/cli-core/src/lib/json-output.ts @@ -10,8 +10,6 @@ // benefit — stderr output doesn't pollute the stdout JSON that consumers // actually read. Simpler to not suppress stderr at all. -import { type ErrorCode } from './exit-codes.ts'; - /** * Write a structured JSON result to stdout: the CLI's way to write a call's * result (its context's output). Always outputs a single line of JSON @@ -26,7 +24,7 @@ export function writeJsonResult(data: Readonly>): void { * Write a structured JSON error to stdout. * Format: { "error": true, "code": "ERROR_CODE", "message": "..." } */ -export function writeJsonError(err: Error, errorCode: ErrorCode, exitCode: number): void { +export function writeJsonError(err: Error, errorCode: string, exitCode: number): void { const json = JSON.stringify({ error: true, code: errorCode, diff --git a/scripts/behaviour-snapshot.mjs b/scripts/behaviour-snapshot.mjs index bb22d728..d05fc67d 100644 --- a/scripts/behaviour-snapshot.mjs +++ b/scripts/behaviour-snapshot.mjs @@ -36,12 +36,15 @@ const NOT_A_FLAG = 'zz-not-a-flag'; // ---------- running the CLI ---------- -function cleanEnv(home) { +// `unset` names variables of the fixed environment a case runs without. +function cleanEnv(home, unset = []) { const env = {}; for (const [key, value] of Object.entries(process.env)) { if (!key.startsWith('MN_') && key !== 'NODE_OPTIONS' && key !== 'FORCE_COLOR') env[key] = value; } - return { ...env, HOME: home, MN_NO_LOCAL_DETECT: '1', MN_PASSPHRASE: 'behaviour-snapshot', NO_COLOR: '1', TERM: 'dumb' }; + const fixed = { ...env, HOME: home, MN_NO_LOCAL_DETECT: '1', MN_PASSPHRASE: 'behaviour-snapshot', NO_COLOR: '1', TERM: 'dumb' }; + for (const key of unset) delete fixed[key]; + return fixed; } function normalise(text, home) { @@ -52,9 +55,9 @@ function normalise(text, home) { .replace(/\b\d{13}\b/g, ''); } -function runCli(home, args, nodeArgs = []) { +function runCli(home, args, nodeArgs = [], unset = []) { const result = spawnSync(process.execPath, [...nodeArgs, BIN, ...args], { - cwd: home, env: cleanEnv(home), encoding: 'utf8', timeout: TIMEOUT_MS, input: '', + cwd: home, env: cleanEnv(home, unset), encoding: 'utf8', timeout: TIMEOUT_MS, input: '', }); return { args, @@ -107,7 +110,7 @@ function acceptedFlags(home, helpCasesRecorded) { } // Commands that need no network, run in order in one HOME, so later ones see -// what earlier ones wrote. +// what earlier ones wrote. A third element names variables the case runs without. const OFFLINE = [ ['config-get-network', ['config', 'get', 'network', '--json']], ['config-set-network', ['config', 'set', 'network', 'undeployed']], @@ -117,6 +120,8 @@ const OFFLINE = [ ['wallet-list-empty', ['wallet', 'list', '--json']], ['wallet-generate', ['wallet', 'generate', 'snap', '--seed', SEED, '--network', 'undeployed', '--json']], ['wallet-generate-again', ['wallet', 'generate', 'snap', '--seed', SEED, '--network', 'undeployed', '--json']], + // No passphrase and no terminal to ask at: refused before it writes anything. + ['wallet-generate-no-passphrase', ['wallet', 'generate', 'nopass', '--seed', SEED, '--network', 'undeployed', '--json'], ['MN_PASSPHRASE']], ['wallet-list', ['wallet', 'list', '--json']], ['wallet-info', ['wallet', 'info', '--json']], ['wallet-use', ['wallet', 'use', 'snap', '--json']], @@ -141,7 +146,7 @@ const OFFLINE = [ function offlineCases(home) { const cases = {}; - for (const [name, args] of OFFLINE) cases[name] = runCli(home, args); + for (const [name, args, unset = []] of OFFLINE) cases[name] = runCli(home, args, [], unset); cases['home-files'] = listFiles(join(home, '.midnight'), home); return cases; } diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 02fac7a8..0ce00280 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -34,15 +34,15 @@ const HOMES = [ ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], - // A package's agent guidance (.guidance.ts) sits beside its commands. - ...PACKAGES.map((pkg) => [pkg, new RegExp(`^commands/${pkg}\\.guidance\\.ts$`)]), + // A package's agent guidance (.guidance.ts) and its error codes (.codes.ts) sit beside its commands. + ...PACKAGES.map((pkg) => [pkg, new RegExp(`^commands/${pkg}\\.(guidance|codes)\\.ts$`)]), // A command's definition (.definition.ts) lives in its command's package. ['core', /^commands\/config(\.definition)?\.ts$/], // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 4124f887..d88dbc4b 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -130,10 +130,11 @@ describe('the accepted flags match the code', () => { } // A command's definition (.definition.ts) sits beside it and is not a - // command, nor is a package's agent guidance (.guidance.ts). + // command, nor is a package's agent guidance (.guidance.ts) or its + // error codes (.codes.ts). // Commands sit in commands/ under src/ or a workspace package. const commandPaths = new Map(sourceFiles() - .filter((f) => /\/commands\/[^/]+\.ts$/.test(f) && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts')) + .filter((f) => /\/commands\/[^/]+\.ts$/.test(f) && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts') && !f.endsWith('.codes.ts')) .map((f) => [basename(f), f])); const commandFiles = [...commandPaths.keys()]; diff --git a/src/__tests__/engine-beta-error-code-parity.test.ts b/src/__tests__/engine-beta-error-code-parity.test.ts new file mode 100644 index 00000000..f1a84ecd --- /dev/null +++ b/src/__tests__/engine-beta-error-code-parity.test.ts @@ -0,0 +1,16 @@ +// The beta engine's stale-cache error, as error-code-parity.test.ts checks the +// rc engine's: in a file of its own, since one process loads one SDK set. +// Approved (Y52): an escaped stale cache reports STALE_CACHE, where it was UNKNOWN. + +import { describe, expect, it } from 'vitest'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { StaleCacheError } from '@kuiralabs/midnight-engine-beta/facade'; +import { installedCommands } from '../lib/installed-commands.ts'; + +describe("the beta engine's stale cache", () => { + it('reports STALE_CACHE (exit 6) through the installed codes, where the message alone gave UNKNOWN', () => { + const err = new StaleCacheError('applied 120 of 80 events'); + expect(classifyError(err)).toStrictEqual({ exitCode: 1, errorCode: 'UNKNOWN' }); + expect(classifyError(err, installedCommands)).toStrictEqual({ exitCode: 6, errorCode: 'STALE_CACHE' }); + }); +}); diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts new file mode 100644 index 00000000..714db51c --- /dev/null +++ b/src/__tests__/error-code-parity.test.ts @@ -0,0 +1,124 @@ +// What each typed error, thrown where mn throws it, reports: its code and the +// exit code it ends the CLI with. Each row records the classification without +// the registry (what mn reported before codes were owned per package) and with +// the installed registry (what the shell and the MCP server report now). They +// differ only where the owner approved it (Y52): NO_STATE_ROOT, NO_PAYER and +// NO_NODE_RUNTIME by name instead of UNKNOWN, an escaped stale cache as +// STALE_CACHE, and a failed command run through MCP as COMMAND_FAILED. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { CancelledError, CommandFailedError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { checkTerms, NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { assertOfferUnexpired } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { OfferCoinsInUseError } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { AmbiguousLocalStacksError } from '@kuiralabs/midnight-cli-core/lib/network'; +import { + BlockfrostLimitError, + BlockfrostProjectIdRejectedError, + BlockfrostProjectIdRequiredError, + EndpointShutDownError, +} from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { MixedSdkLayoutError } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; +import { LocalStackUnreachableError, UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { ChainClockBehindError } from '@kuiralabs/midnight-chain/lib/chain-clock'; +import { StaleCacheError } from '@kuiralabs/midnight-engine-rc/facade'; +import { readPassphrase } from '../lib/passphrase.ts'; +import { assertWalletFileExists, setActiveWallet } from '../lib/wallet-config.ts'; +import { UnsupportedNodeError } from '../lib/node-version.ts'; +import { LocalnetUnavailableError } from '../lib/localnet.ts'; +import { scriptRuntime } from '../lib/contract/runner.ts'; +import { NoSuchOfferError } from '../lib/swap/offers.ts'; +import { NoAccountError } from '../lib/grant/prepare.ts'; +import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; + +let root: string; +beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'mn-code-parity-')); }); +afterAll(() => { rmSync(root, { recursive: true, force: true }); }); + +/** What the function throws; fails the test when it throws nothing. */ +async function thrownBy(run: () => unknown): Promise { + try { + await run(); + } catch (err) { + return err as Error; + } + throw new Error('expected it to throw'); +} + +const A = '0'.repeat(64); +const B = '1'.repeat(64); +const AGREED = { give: { token: A, amount: 10n }, want: { token: B, amount: 7n } }; +const TWENTY_NIGHT = { dust: { generatedNow: 337_954_960_000_000n, rate: 165_340_000_000n, maxCap: 100_000_000_000_000_000n } }; + +type Classified = { errorCode: string; exitCode: number }; +const as = (errorCode: string, exitCode: number): Classified => ({ errorCode, exitCode }); + +/** [where it is thrown, how to throw it, without the registry, with it]. */ +const ROWS: [string, () => unknown, Classified, Classified][] = [ + // The caller's to fix: exit 2. + ['a usage error', () => { throw new UsageError('Missing required flag: --to'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['no passphrase to be had', () => readPassphrase(null, { env: {} }), as('PASSPHRASE_REQUIRED', 2), as('PASSPHRASE_REQUIRED', 2)], + ['a wrong passphrase', () => openSecret(sealSecret(Buffer.from('secret'), 'the right passphrase', 'wallet'), 'a wrong passphrase', 'wallet'), as('WRONG_PASSPHRASE', 2), as('WRONG_PASSPHRASE', 2)], + ['bytes that are no offer', () => { throw new NotAnOfferError('it is not hex'); }, as('NOT_AN_OFFER', 2), as('NOT_AN_OFFER', 2)], + ['an offer on other terms', () => checkTerms({ give: AGREED.want, want: AGREED.give }, AGREED), as('TERMS_MISMATCH', 2), as('TERMS_MISMATCH', 2)], + ['an expired offer', () => assertOfferUnexpired({ network: 'undeployed', id: 'ab', terms: AGREED, expiresAt: new Date(0), tx: '' }, new Date(1)), as('OFFER_EXPIRED', 2), as('OFFER_EXPIRED', 2)], + ['coins an open offer holds', () => { throw new OfferCoinsInUseError(['ab'.repeat(32)]); }, as('OFFER_COINS_IN_USE', 2), as('OFFER_COINS_IN_USE', 2)], + ['no such open offer (a usage error)', () => { throw new NoSuchOfferError('ab'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['an account unreachable on this set (a usage error)', () => { throw new UnreachableByAccountError('undeployed'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + + // No such wallet: exit 3, by its message. + ['no wallet of that name', () => setActiveWallet(root, 'nobody'), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], + ['no wallet file', () => assertWalletFileExists(join(root, 'wallets', 'nobody.json')), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], + + // Setup and network: exit 4. + ['several local stacks', () => { throw new AmbiguousLocalStacksError({ node: [9944, 9945], indexer: [8088], proofServer: [6300] }); }, as('AMBIGUOUS_LOCAL_STACKS', 4), as('AMBIGUOUS_LOCAL_STACKS', 4)], + ['no Blockfrost project id', () => { throw new BlockfrostProjectIdRequiredError('preprod'); }, as('BLOCKFROST_PROJECT_ID_REQUIRED', 4), as('BLOCKFROST_PROJECT_ID_REQUIRED', 4)], + ['a refused Blockfrost project id', () => { throw new BlockfrostProjectIdRejectedError('preprod'); }, as('BLOCKFROST_PROJECT_ID_REJECTED', 4), as('BLOCKFROST_PROJECT_ID_REJECTED', 4)], + ["Blockfrost's limit", () => { throw new BlockfrostLimitError(429); }, as('BLOCKFROST_LIMIT_REACHED', 4), as('BLOCKFROST_LIMIT_REACHED', 4)], + ['an endpoint shut down', () => { throw new EndpointShutDownError('wss://indexer.example/api/v3/graphql/ws'); }, as('ENDPOINT_SHUT_DOWN', 4), as('ENDPOINT_SHUT_DOWN', 4)], + ['a ledger-8 chain', () => { throw new UnsupportedLedgerError('preprod', 8_000_000n); }, as('UNSUPPORTED_LEDGER', 4), as('UNSUPPORTED_LEDGER', 4)], + ['no stack at the endpoints', () => { throw new LocalStackUnreachableError('node', 'ws://127.0.0.1:1'); }, as('LOCAL_STACK_UNREACHABLE', 4), as('LOCAL_STACK_UNREACHABLE', 4)], + ["the chain's clock behind", () => { throw new ChainClockBehindError(new Date(0), new Date(3_600_000)); }, as('CHAIN_CLOCK_BEHIND', 4), as('CHAIN_CLOCK_BEHIND', 4)], + ['localnet up refused', () => { throw new LocalnetUnavailableError(); }, as('LOCALNET_UNAVAILABLE', 4), as('LOCALNET_UNAVAILABLE', 4)], + + // Balance: exit 5. + ['a Dust fee not generated yet', () => { throw new DustFeeNotGeneratedError(planRegistration(526_587_115_818_352n, [TWENTY_NIGHT]), new Date('2026-10-05T04:05:23.000Z')); }, as('DUST_GENERATING', 5), as('DUST_GENERATING', 5)], + + // Refused transactions and stale state: exit 6. + ["the node's refusal", () => { throw new TransactionRefusedError('Invalid transaction'); }, as('TX_REJECTED', 6), as('TX_REJECTED', 6)], + ['a stale cache that escapes (approved: was UNKNOWN)', () => { throw new StaleCacheError('applied 120 of 80 events'); }, as('UNKNOWN', 1), as('STALE_CACHE', 6)], + + // Cancelled: exit 7. + ['a cancelled call', () => { throw new CancelledError(); }, as('CANCELLED', 7), as('CANCELLED', 7)], + + // General: exit 1. + ['an old Node.js', () => { throw new UnsupportedNodeError('20.10.0'); }, as('UNSUPPORTED_NODE', 1), as('UNSUPPORTED_NODE', 1)], + ['an old Node.js for the account', () => { throw new NodeTooOldForAccountError('22.0.0'); }, as('UNSUPPORTED_NODE', 1), as('UNSUPPORTED_NODE', 1)], + ['two copies of a ledger', () => { throw new MixedSdkLayoutError('rc', '@midnight-ntwrk/ledger-v8', ['a', 'b']); }, as('MIXED_SDK_LAYOUT', 1), as('MIXED_SDK_LAYOUT', 1)], + ['the other SDK set', () => { throw new OtherSdkSetError('rc', 'beta'); }, as('OTHER_SDK_SET', 1), as('OTHER_SDK_SET', 1)], + ['no account', () => { throw new NoAccountError('alice', 'undeployed'); }, as('NO_ACCOUNT', 1), as('NO_ACCOUNT', 1)], + ['no state root (approved: was UNKNOWN)', () => createHost().paths(), as('UNKNOWN', 1), as('NO_STATE_ROOT', 1)], + ['no payer (approved: was UNKNOWN)', () => payerFor('transfer', undefined), as('UNKNOWN', 1), as('NO_PAYER', 1)], + ['no Node.js for a contract script (approved: was UNKNOWN)', () => scriptRuntime({ execPath: '/opt/bun/bin/bun', isNode: false }, ''), as('UNKNOWN', 1), as('NO_NODE_RUNTIME', 1)], + // Without the registry its code came from its result's text: here, words that read as a network error. + ['a failed command (approved: was by its text)', () => { throw new CommandFailedError('test run', 1, { overall: 'fail', error: 'network error' }); }, as('NETWORK_ERROR', 4), as('COMMAND_FAILED', 1)], + ['an error no rule knows', () => { throw new Error('Something unexpected happened'); }, as('UNKNOWN', 1), as('UNKNOWN', 1)], +]; + +describe('the code and exit code of each typed error', () => { + it.each(ROWS)('%s', async (_where, run, before, now) => { + const err = await thrownBy(run); + expect(classifyError(err)).toStrictEqual(before); + expect(classifyError(err, installedCommands)).toStrictEqual(now); + }); +}); diff --git a/src/__tests__/error-code-registry.test.ts b/src/__tests__/error-code-registry.test.ts new file mode 100644 index 00000000..562ec8c0 --- /dev/null +++ b/src/__tests__/error-code-registry.test.ts @@ -0,0 +1,74 @@ +// Error codes owned per package: each package defines its own, the installed +// packages' codes assemble into one lookup (a plugin's with them), and no code +// is defined twice. + +import { describe, expect, it } from 'vitest'; +import { CodeDefinitionError, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { CommandDefinitionError, createCommandRegistry, createPackageRegistry, type CommandPackage } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { classifyError, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { chainCodes } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { installedCommands } from '../lib/installed-commands.ts'; + +/** A package with no commands and no guidance: only codes. */ +const codesOnly = (name: string, codes: CommandPackage['codes']): CommandPackage => ({ name, commands: [], guidance: { pieces: [] }, codes }); + +const PLUGIN_CODES = defineCodes([ + { code: 'PLUGIN_ORACLE_DOWN', exitCode: 4, summary: "The plugin's price oracle did not answer.", recovery: 'Retry later.' }, +]); + +/** An error a plugin throws, carrying its own code. */ +class OracleDownError extends Error { + readonly code = 'PLUGIN_ORACLE_DOWN'; +} + +describe('defineCodes', () => { + it('refuses a code a package defines twice', () => { + expect(() => defineCodes([ + { code: 'TWICE', exitCode: 1, summary: 'once' }, + { code: 'TWICE', exitCode: 2, summary: 'again' }, + ])).toThrow(new CodeDefinitionError('Error code "TWICE" is defined twice')); + }); +}); + +describe('the package registry\'s codes', () => { + it('refuses a code two packages define', () => { + expect(() => createPackageRegistry([ + codesOnly('one', defineCodes([{ code: 'SHARED', exitCode: 1, summary: 'from one' }])), + codesOnly('two', defineCodes([{ code: 'SHARED', exitCode: 1, summary: 'from two' }])), + ], [])).toThrow(new CommandDefinitionError('error code "SHARED" is defined twice')); + }); + + it('refuses a plugin that defines a code an installed package owns', () => { + expect(() => createPackageRegistry([ + ...installedCommands.packages, + codesOnly('plugin', defineCodes([{ code: 'WALLET_NOT_FOUND', exitCode: 3, summary: 'mine too' }])), + ], installedCommands.globalFlags)).toThrow(new CommandDefinitionError('error code "WALLET_NOT_FOUND" is defined twice')); + }); + + it('assembles the codes of several packages, each found as its package defines it', () => { + const registry = createPackageRegistry([codesOnly('core', coreCodes), codesOnly('chain', chainCodes)], []); + expect(registry.code('INVALID_ARGS')).toBe(coreCodes.find((c) => c.code === 'INVALID_ARGS')); + expect(registry.code('CHAIN_CLOCK_BEHIND')).toBe(chainCodes.find((c) => c.code === 'CHAIN_CLOCK_BEHIND')); + expect(registry.code('WALLET_NOT_FOUND')).toBeUndefined(); + }); + + it('finds every code mn has published in the installed packages, the new ones with them', () => { + const missing = Object.values(ERROR_CODES).filter((code) => installedCommands.code(code) === undefined); + expect(missing).toStrictEqual([]); + expect(installedCommands.code('NO_NODE_RUNTIME')).toMatchObject({ code: 'NO_NODE_RUNTIME', exitCode: 1 }); + expect(installedCommands.code('COMMAND_FAILED')).toMatchObject({ code: 'COMMAND_FAILED', exitCode: 1 }); + }); + + it('finds a plugin package\'s codes, and classifies its errors by them', () => { + const registry = createPackageRegistry([...installedCommands.packages, codesOnly('plugin', PLUGIN_CODES)], installedCommands.globalFlags); + expect(registry.code('PLUGIN_ORACLE_DOWN')).toBe(PLUGIN_CODES[0]); + expect(classifyError(new OracleDownError('no answer'), registry)).toStrictEqual({ exitCode: 4, errorCode: 'PLUGIN_ORACLE_DOWN' }); + // Without the plugin installed, its code is no one's: the error is unclassified. + expect(classifyError(new OracleDownError('no answer'), installedCommands)).toStrictEqual({ exitCode: 1, errorCode: 'UNKNOWN' }); + }); + + it('knows no code in a registry made from bare commands', () => { + expect(createCommandRegistry([], []).code('INVALID_ARGS')).toBeUndefined(); + }); +}); diff --git a/src/__tests__/shell-error-codes.test.ts b/src/__tests__/shell-error-codes.test.ts new file mode 100644 index 00000000..0232cb9a --- /dev/null +++ b/src/__tests__/shell-error-codes.test.ts @@ -0,0 +1,55 @@ +// The shell reports an error's code as the MCP server does: from its code, +// a usage error's included. Run as the CLI is: this checkout's entry point in +// its own process, with a temporary home and no MN_PASSPHRASE, where nothing +// can ask for the passphrase. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const entryPoint = resolve(import.meta.dirname, '../wallet.ts'); +const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href; +const SEED = '0000000000000000000000000000000000000000000000000000000000000001'; + +let home: string; + +beforeAll(() => { home = realpathSync(mkdtempSync(join(tmpdir(), 'mn-shell-codes-'))); }); +afterAll(() => { rmSync(home, { recursive: true, force: true }); }); + +function mn(...args: string[]) { + const env: Record = { ...process.env, HOME: home, NO_COLOR: '1' }; + delete env.MN_PASSPHRASE; + const run = spawnSync(process.execPath, ['--import', tsxLoader, entryPoint, ...args], { env, encoding: 'utf8', input: '', timeout: 30_000 }); + return { status: run.status, stdout: run.stdout, stderr: run.stderr }; +} + +describe('the shell\'s error codes', () => { + it('reports PASSPHRASE_REQUIRED (exit 2) under --json when a command needs the passphrase and none can be had', () => { + const run = mn('wallet', 'generate', 'alice', '--seed', SEED, '--network', 'undeployed', '--json'); + expect(run.status).toBe(2); + expect(JSON.parse(run.stdout)).toStrictEqual({ + error: true, + code: 'PASSPHRASE_REQUIRED', + message: "This needs mn's passphrase. Set MN_PASSPHRASE, or run it at a terminal to be asked for it.", + exitCode: 2, + }); + // Refused before it wrote anything: no wallet. + expect(existsSync(join(home, '.midnight', 'wallets', 'alice.json'))).toBe(false); + }); + + it('shows it as a usage problem at a terminal, with exit 2', () => { + const run = mn('wallet', 'generate', 'alice', '--seed', SEED, '--network', 'undeployed'); + expect(run.status).toBe(2); + expect(run.stderr).toContain("Usage: This needs mn's passphrase."); + }); + + it('still reports any other usage error as INVALID_ARGS (exit 2)', () => { + const run = mn('transfer', '--json'); + expect(run.status).toBe(2); + expect(JSON.parse(run.stdout)).toMatchObject({ error: true, code: 'INVALID_ARGS', exitCode: 2 }); + }); +}); diff --git a/src/commands/contract.codes.ts b/src/commands/contract.codes.ts new file mode 100644 index 00000000..6a0a09a4 --- /dev/null +++ b/src/commands/contract.codes.ts @@ -0,0 +1,8 @@ +// The error codes the contract package owns. + +import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +export const contractCodes = defineCodes([ + { code: 'NO_NODE_RUNTIME', exitCode: EXIT_GENERAL_ERROR, summary: 'Contract scripts run under Node.js, and none was found on PATH.', recovery: 'Install Node.js 22 or later, or run mn under Node.' }, +]); diff --git a/src/commands/contract.guidance.ts b/src/commands/contract.guidance.ts index 03a78cce..12ec6df7 100644 --- a/src/commands/contract.guidance.ts +++ b/src/commands/contract.guidance.ts @@ -6,6 +6,14 @@ import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-gui export const contractGuidance: PackageGuidance = { pieces: [ + { + text: 'agent-manual', + section: 'error-codes', + order: 95, + body: ` NO_NODE_RUNTIME 1 Contract scripts run under Node.js and none + is on PATH: install Node.js 22 or later +`, + }, { text: 'skill-full', section: 'what-you-can-do', diff --git a/src/commands/dev.codes.ts b/src/commands/dev.codes.ts new file mode 100644 index 00000000..2cb8615c --- /dev/null +++ b/src/commands/dev.codes.ts @@ -0,0 +1,8 @@ +// The error codes the dev package owns. + +import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +export const devCodes = defineCodes([ + { code: 'LOCALNET_UNAVAILABLE', exitCode: EXIT_NETWORK_ERROR, summary: "`mn localnet up` can't start a ledger-9 stack on this build.", recovery: 'Run one yourself and point mn at it (endpoint flags or `midnight config set`).' }, +]); diff --git a/src/commands/grant.codes.ts b/src/commands/grant.codes.ts new file mode 100644 index 00000000..e8ecd135 --- /dev/null +++ b/src/commands/grant.codes.ts @@ -0,0 +1,8 @@ +// The error codes the grant package owns. + +import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +export const grantCodes = defineCodes([ + { code: 'NO_ACCOUNT', exitCode: EXIT_GENERAL_ERROR, summary: 'The wallet has no account on this network yet.', recovery: '`mn grant deploy`.' }, +]); diff --git a/src/commands/wallet.codes.ts b/src/commands/wallet.codes.ts new file mode 100644 index 00000000..3d900244 --- /dev/null +++ b/src/commands/wallet.codes.ts @@ -0,0 +1,8 @@ +// The error codes the wallet package owns. + +import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { EXIT_WALLET_NOT_FOUND } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; + +export const walletCodes = defineCodes([ + { code: 'WALLET_NOT_FOUND', exitCode: EXIT_WALLET_NOT_FOUND, summary: 'Wallet file does not exist.', recovery: '`midnight wallet list` shows the wallets there are.' }, +]); diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 892498d1..2a5415be 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -1,9 +1,10 @@ -// The packages this mn has, with their commands and agent guidance, collected +// The packages this mn has, with their commands, agent guidance and error codes, collected // into one registry. The shell assembles it: a definition and a package's // guidance sit beside its commands, and the base can't import a package's // commands. Reading it loads no handler, so no SDK. The shell's dispatch and // flag checks read it, and so do help, the manual and the intro, the MCP -// server's tools, and the agent manual and skills. +// server's tools, the agent manual and skills, and the shell's and the MCP +// server's classification of an error by its code. import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core/lib/command-definition'; @@ -38,6 +39,12 @@ import { connectGuidance } from '../commands/connect.guidance.ts'; import { devGuidance } from '../commands/dev.guidance.ts'; import { grantGuidance } from '../commands/grant.guidance.ts'; import { swapGuidance } from '../commands/swap.guidance.ts'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { chainCodes } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { walletCodes } from '../commands/wallet.codes.ts'; +import { contractCodes } from '../commands/contract.codes.ts'; +import { devCodes } from '../commands/dev.codes.ts'; +import { grantCodes } from '../commands/grant.codes.ts'; /** The shell answers these before any command runs: no tool passes them on. */ const SHELL_ANSWERS = { notForAgents: 'the shell answers it before any command runs' }; @@ -65,17 +72,18 @@ const GLOBAL_FLAGS_HELP: readonly GlobalFlagHelp[] = [ /** Every package, in the layering's order; the shell's own commands last, its guidance being the skeletons. */ export const installedCommands = createPackageRegistry([ - { name: 'core', commands: [configDefinition], guidance: coreGuidance }, - { name: 'chain', commands: [statusDefinition, txDefinition], guidance: chainGuidance }, + { name: 'core', commands: [configDefinition], guidance: coreGuidance, codes: coreCodes }, + { name: 'chain', commands: [statusDefinition, txDefinition], guidance: chainGuidance, codes: chainCodes }, { name: 'wallet', commands: [walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition], guidance: walletGuidance, + codes: walletCodes, }, - { name: 'contract', commands: [inspectCostDefinition, contractDefinition], guidance: contractGuidance }, + { name: 'contract', commands: [inspectCostDefinition, contractDefinition], guidance: contractGuidance, codes: contractCodes }, { name: 'connect', commands: [serveDefinition], guidance: connectGuidance }, { name: 'swap', commands: [swapDefinition], guidance: swapGuidance }, - { name: 'dev', commands: [testDefinition, devDefinition, localnetDefinition], guidance: devGuidance }, - { name: 'grant', commands: [grantDefinition], guidance: grantGuidance }, + { name: 'dev', commands: [testDefinition, devDefinition, localnetDefinition], guidance: devGuidance, codes: devCodes }, + { name: 'grant', commands: [grantDefinition], guidance: grantGuidance, codes: grantCodes }, { name: 'shell', commands: [helpDefinition, manualDefinition], guidance: { pieces: [] } }, ], GLOBAL_FLAGS, GLOBAL_FLAGS_HELP); diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 432f0472..93a8cc57 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -203,7 +203,7 @@ async function executeTool(name: string, params: Record, call: function errorResponse(thrown: Error, call: CommandRun) { // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. const error = withServerAdvice(withNodeReason(thrown), call.host.paths().stateRoot); - const { errorCode } = classifyError(error); + const { errorCode } = classifyError(error, installedCommands); return { content: [{ type: 'text' as const, diff --git a/src/wallet.ts b/src/wallet.ts index c780e1c3..fade0f4e 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -10,7 +10,7 @@ import { withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { installedCommands } from './lib/installed-commands.ts'; import { commandNeedsWalletSdk, dispatchCommand, processOutput } from './lib/command-dispatch.ts'; import type { CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { classifyError, humanizeNetworkError, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError, humanizeNetworkError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { writeJsonError } from '@kuiralabs/midnight-cli-core/lib/json-output'; import { PKG_VERSION } from './lib/pkg.ts'; @@ -117,26 +117,21 @@ run().then((outcome) => { }).catch((thrown: Error) => { // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. const err = withNodeReason(thrown); - // Usage errors (missing/unknown subcommand, bad args) render in yellow - // with a softer "Usage" framing. They are the user's prompt to fix and - // retry, not a system failure. Exit code 2 (INVALID_ARGS). + // The code and exit code come from the error's code, as the MCP server's do: + // a usage error carries INVALID_ARGS unless its class names another + // (PASSPHRASE_REQUIRED). Usage errors (missing/unknown subcommand, bad args) + // render in yellow with a softer "Usage" framing: the user's prompt to fix + // and retry, not a system failure. + const { exitCode, errorCode } = classifyError(err, installedCommands); const message = humanizeNetworkError(err.message); - if (isUsageError(err)) { - if (jsonMode) { - writeJsonError(err, 'INVALID_ARGS', EXIT_INVALID_ARGS); - } else { - process.stderr.write('\n' + usageMessage(message, 'Run "midnight manual" for the full reference, or "midnight help " for one command.') + '\n\n'); - } - process.exit(EXIT_INVALID_ARGS); - } else if (jsonMode) { - const { exitCode, errorCode } = classifyError(err); + if (jsonMode) { writeJsonError(err, errorCode, exitCode); - process.exit(exitCode); + } else if (isUsageError(err)) { + process.stderr.write('\n' + usageMessage(message, 'Run "midnight manual" for the full reference, or "midnight help " for one command.') + '\n\n'); } else { process.stderr.write('\n' + errorMessage(message, 'Run "midnight help" for usage information.') + '\n\n'); - const { exitCode } = classifyError(err); - process.exit(exitCode); } + process.exit(exitCode); }); } From d1f1741ac38039c905a5ad5691bafdf533edb30a Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 09:15:45 -0800 Subject: [PATCH 63/88] Typed errors where failures are known: mn and chain (3C, 3-4 of 8) Each failure a message rule used to classify now carries its code from where it is thrown: WalletNotFoundError, InsufficientBalanceError and DustRequiredError (the engines throw the balance one too), and in chain SyncTimeoutError from the readiness probes and NetworkError or IndexerUnreachableError when a node or indexer can't be reached. A timed-out program keeps NETWORK_ERROR through its code. Approved changes: thirteen bad-argument sites throw UsageError (Y52), shown as yellow "Usage"; a wallet with no NIGHT reports INSUFFICIENT_BALANCE, an unreachable indexer or node NETWORK_ERROR whatever its text, and a failed test-run prep step keeps its step's code (Y53). Each site has a parity row checked by code alone. Snapshot unchanged against baseline-3c2; suite 2657, beta 172. --- packages/chain/api-report.md | 10 +- .../chain/src/lib/balance-subscription.ts | 4 +- .../chain/src/lib/graphql-ws-subscription.ts | 4 +- packages/chain/src/lib/indexer-graphql.ts | 17 ++- packages/chain/src/lib/indexer-ready.ts | 4 +- packages/chain/src/lib/node-ready.ts | 4 +- packages/chain/src/lib/node-rpc.ts | 5 +- packages/chain/src/lib/proof-server-ready.ts | 4 +- packages/cli-core/api-report.md | 23 +++- packages/cli-core/src/lib/argv.ts | 2 +- packages/cli-core/src/lib/dust-wait.ts | 5 +- packages/cli-core/src/lib/engine.ts | 2 +- packages/cli-core/src/lib/errors.ts | 44 ++++++ packages/cli-core/src/lib/exec-program.ts | 4 +- packages/cli-core/src/lib/exit-codes.ts | 19 ++- packages/engine-beta/src/wallet.ts | 4 +- packages/engine-rc/src/wallet.ts | 4 +- src/__tests__/error-code-parity.test.ts | 125 ++++++++++++++++-- src/commands/address.ts | 3 +- src/commands/airdrop.ts | 4 +- src/commands/balance.ts | 5 +- src/commands/generate.ts | 6 +- src/commands/wallet.ts | 8 +- src/lib/test/prep-runner.ts | 23 +++- src/lib/transfer-request.ts | 2 +- src/lib/wallet-can-pay.ts | 6 +- src/lib/wallet-config.ts | 17 ++- src/lib/wallet-create.ts | 3 +- 28 files changed, 297 insertions(+), 64 deletions(-) diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md index 5e34d170..eec2c1a4 100644 --- a/packages/chain/api-report.md +++ b/packages/chain/api-report.md @@ -130,7 +130,15 @@ export declare function subscribeGraphqlWs(wsUrl: string, sub: GraphqlW ```ts export declare class IndexerQueryError extends Error { - constructor(reason: string); + constructor(reason: string, options?: { + cause?: unknown; + }); +} +export declare class IndexerUnreachableError extends IndexerQueryError { + readonly code = "NETWORK_ERROR"; + constructor(reason: string, options?: { + cause?: unknown; + }); } export declare function queryIndexer(indexerHttpUrl: string, query: string, variables: Record | undefined, timeoutMs: number, signal?: AbortSignal): Promise; ``` diff --git a/packages/chain/src/lib/balance-subscription.ts b/packages/chain/src/lib/balance-subscription.ts index b054704a..df30263b 100644 --- a/packages/chain/src/lib/balance-subscription.ts +++ b/packages/chain/src/lib/balance-subscription.ts @@ -1,7 +1,7 @@ import WebSocket from 'ws'; import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { NATIVE_TOKEN_TYPE, BALANCE_CHECK_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; export type { BalanceSummary } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { BalanceSummary } from '@kuiralabs/midnight-cli-core/lib/engine'; @@ -207,7 +207,7 @@ export function checkBalance( const reason = error.message?.trim() ? error.message : `unable to reach ${indexerWS} (connection refused, DNS, or TLS error). Is the indexer running?`; - reject(endpointRefusalFromWsError(indexerWS, error) ?? new Error(`WebSocket connection failed: ${reason}`)); + reject(endpointRefusalFromWsError(indexerWS, error) ?? new NetworkError(`WebSocket connection failed: ${reason}`, { cause: error })); } }); diff --git a/packages/chain/src/lib/graphql-ws-subscription.ts b/packages/chain/src/lib/graphql-ws-subscription.ts index 2d0022ad..94e47c7d 100644 --- a/packages/chain/src/lib/graphql-ws-subscription.ts +++ b/packages/chain/src/lib/graphql-ws-subscription.ts @@ -19,7 +19,7 @@ // `partial=true` means "state is valid but not caught up — persist and resume". import WebSocket from 'ws'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; /** Why the subscription settled. `timeout`/`closed-early` are the partial cases. */ @@ -180,7 +180,7 @@ export function subscribeGraphqlWs( if (caughtUp) finishOk('caught-up', false); }); - ws.on('error', (err: Error) => finishErr(endpointRefusalFromWsError(wsUrl, err) ?? new Error(`WebSocket error: ${err.message}`))); + ws.on('error', (err: Error) => finishErr(endpointRefusalFromWsError(wsUrl, err) ?? new NetworkError(`WebSocket error: ${err.message}`, { cause: err }))); ws.on('close', () => { if (settled) return; diff --git a/packages/chain/src/lib/indexer-graphql.ts b/packages/chain/src/lib/indexer-graphql.ts index d07e19e4..fbd2901e 100644 --- a/packages/chain/src/lib/indexer-graphql.ts +++ b/packages/chain/src/lib/indexer-graphql.ts @@ -5,13 +5,24 @@ import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** The indexer could not answer a query: unreachable, an HTTP error, a non-JSON body, or GraphQL errors. */ export class IndexerQueryError extends Error { - constructor(reason: string) { - super(reason); + constructor(reason: string, options?: { cause?: unknown }) { + super(reason, options); this.name = 'IndexerQueryError'; Object.setPrototypeOf(this, IndexerQueryError.prototype); } } +/** The indexer could not be reached (refused, no such host, timed out): fetch's own words, and fetch's error as the cause. */ +export class IndexerUnreachableError extends IndexerQueryError { + readonly code = 'NETWORK_ERROR'; + + constructor(reason: string, options?: { cause?: unknown }) { + super(reason, options); + this.name = 'IndexerUnreachableError'; + Object.setPrototypeOf(this, IndexerUnreachableError.prototype); + } +} + /** * POST `query` to the indexer and return its `data`. Throws IndexerQueryError * when there is none to return, and CancelledError when `signal` cancels it. @@ -36,7 +47,7 @@ export async function queryIndexer( }); } catch (err) { throwIfCancelled(signal); - throw new IndexerQueryError((err as Error).message); + throw new IndexerUnreachableError((err as Error).message, { cause: err }); } if (!res.ok) throw endpointRefusal(indexerHttpUrl, res.status) ?? new IndexerQueryError(`HTTP ${res.status} ${res.statusText}`.trim()); let body: { data?: TData | null; errors?: Array<{ message: string }> }; diff --git a/packages/chain/src/lib/indexer-ready.ts b/packages/chain/src/lib/indexer-ready.ts index 68f89afc..46788f5d 100644 --- a/packages/chain/src/lib/indexer-ready.ts +++ b/packages/chain/src/lib/indexer-ready.ts @@ -6,7 +6,7 @@ // on localnet), confirming state has been ingested end-to-end. import { checkBalance } from './balance-subscription.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; export interface WaitForIndexerOptions { @@ -44,5 +44,5 @@ export async function waitForAddressFunded( await sleep(pollIntervalMs, opts.signal); } - throw new Error(`Indexer did not report funds for ${address.slice(0, 20)}… within ${timeoutMs / 1000}s`); + throw new SyncTimeoutError(`Indexer did not report funds for ${address.slice(0, 20)}… within ${timeoutMs / 1000}s`); } diff --git a/packages/chain/src/lib/node-ready.ts b/packages/chain/src/lib/node-ready.ts index ed4ef906..1198b411 100644 --- a/packages/chain/src/lib/node-ready.ts +++ b/packages/chain/src/lib/node-ready.ts @@ -5,7 +5,7 @@ // until a non-zero block number appears. import { callNodeRpc } from './node-rpc.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; export interface WaitForFirstBlockOptions { @@ -46,5 +46,5 @@ export async function waitForFirstBlock( await sleep(pollIntervalMs, opts.signal); } - throw new Error(`Node did not produce a block within ${timeoutMs / 1000}s`); + throw new SyncTimeoutError(`Node did not produce a block within ${timeoutMs / 1000}s`); } diff --git a/packages/chain/src/lib/node-rpc.ts b/packages/chain/src/lib/node-rpc.ts index 06126a08..1a5464c8 100644 --- a/packages/chain/src/lib/node-rpc.ts +++ b/packages/chain/src/lib/node-rpc.ts @@ -5,7 +5,7 @@ import WebSocket from 'ws'; import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; export interface RpcOptions { url: string; @@ -79,9 +79,10 @@ export async function callNodeRpc( }); }); + // The connection failed (refused, no such host, a dropped socket): its own words, as a network error. ws.on('error', (err) => { clearTimeout(timer); - settle(() => rejectPromise(endpointRefusalFromWsError(opts.url, err) ?? (err instanceof Error ? err : new Error(String(err))))); + settle(() => rejectPromise(endpointRefusalFromWsError(opts.url, err) ?? new NetworkError(err.message, { cause: err }))); }); }); } diff --git a/packages/chain/src/lib/proof-server-ready.ts b/packages/chain/src/lib/proof-server-ready.ts index 5d6870d3..c2aef73f 100644 --- a/packages/chain/src/lib/proof-server-ready.ts +++ b/packages/chain/src/lib/proof-server-ready.ts @@ -5,7 +5,7 @@ // polls the proof-server's `/` status endpoint until it returns a 2xx with // `{"status":"ok",...}` before `mn localnet up` claims readiness. -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; export interface WaitForProofServerOptions { @@ -57,5 +57,5 @@ export async function waitForProofServerReady( await sleep(pollIntervalMs, opts.signal); } - throw new Error(`Proof server at ${probeUrl} did not respond within ${timeoutMs / 1000}s`); + throw new SyncTimeoutError(`Proof server at ${probeUrl} did not respond within ${timeoutMs / 1000}s`); } diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 1031fc9f..932cb8e3 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -803,6 +803,7 @@ export declare class DustFeeNotGeneratedError extends Error { ```ts import { sleep } from "./sleep.ts"; +import { DustRequiredError } from "./errors.ts"; export interface DustBalanceSource { balance(at: Date): bigint; } @@ -810,7 +811,7 @@ export declare const DUST_SHORT_WAIT_MS: number; export declare const OWN_COMMAND_DUST_WAIT_MS: number; export declare const LOOK_AHEAD_MS: number; export declare function msUntilDust(dust: DustBalanceSource, needed: bigint, now: Date, horizonMs: number): number | null; -export declare function dustShortError(have: bigint, needed: bigint, waitMs: number | null): Error; +export declare function dustShortError(have: bigint, needed: bigint, waitMs: number | null): DustRequiredError; export declare function awaitDustForFee(dust: DustBalanceSource, needed: bigint, onStatus?: (status: string) => void, signal?: AbortSignal): Promise; export interface DustWaitPlan { have: bigint; @@ -1202,6 +1203,24 @@ export declare class TransactionRefusedError extends Error { cause?: unknown; }); } +export declare class DustRequiredError extends Error { + readonly code = "DUST_REQUIRED"; + constructor(message: string); +} +export declare class InsufficientBalanceError extends Error { + readonly code = "INSUFFICIENT_BALANCE"; + constructor(message: string); +} +export declare class SyncTimeoutError extends Error { + readonly code = "SYNC_TIMEOUT"; + constructor(message: string); +} +export declare class NetworkError extends Error { + readonly code = "NETWORK_ERROR"; + constructor(message: string, options?: { + cause?: unknown; + }); +} export declare class CommandFailedError extends Error { readonly code = "COMMAND_FAILED"; readonly exitCode: number; @@ -1229,6 +1248,7 @@ export declare class ProgramFailedError extends Error { } export declare class ProgramTimedOutError extends Error { readonly command: string; + readonly code = "NETWORK_ERROR"; constructor(command: string, timeoutMs: number); } export declare const execProgram: ExecRunner; @@ -1292,6 +1312,7 @@ interface ClassifiedError { errorCode: string; } export declare function classifyError(err: Error, codes?: CodeRegistry): ClassifiedError; +export declare function classifyByCode(err: Error, codes: CodeRegistry): ClassifiedError; export declare function humanizeNetworkError(message: string): string; ``` diff --git a/packages/cli-core/src/lib/argv.ts b/packages/cli-core/src/lib/argv.ts index 45c2275e..f7ad1793 100644 --- a/packages/cli-core/src/lib/argv.ts +++ b/packages/cli-core/src/lib/argv.ts @@ -132,7 +132,7 @@ export function rejectNoCacheForWrites(args: ParsedArgs): void { export function requireFlag(args: ParsedArgs, name: string, description: string): string { const value = getFlag(args, name); if (value === undefined) { - throw new Error(`Missing required flag: --${name} <${description}>`); + throw new UsageError(`Missing required flag: --${name} <${description}>`); } return value; } diff --git a/packages/cli-core/src/lib/dust-wait.ts b/packages/cli-core/src/lib/dust-wait.ts index 3a505877..17b3a806 100644 --- a/packages/cli-core/src/lib/dust-wait.ts +++ b/packages/cli-core/src/lib/dust-wait.ts @@ -6,6 +6,7 @@ import { formatWait } from './duration.ts'; import { sleep } from './sleep.ts'; import { DUST_RETRY_DELAY_MS } from './constants.ts'; +import { DustRequiredError } from './errors.ts'; import { dustShortfallOf } from './sdk-errors.ts'; import { roughDust, toDust } from '../ui/format.ts'; @@ -42,11 +43,11 @@ export function msUntilDust(dust: DustBalanceSource, needed: bigint, now: Date, } /** Not enough Dust for the fee, with how long until there is. */ -export function dustShortError(have: bigint, needed: bigint, waitMs: number | null): Error { +export function dustShortError(have: bigint, needed: bigint, waitMs: number | null): DustRequiredError { const when = waitMs === null ? "This wallet's registered NIGHT won't generate that within a day: register more NIGHT (midnight dust register)." : `This wallet's NIGHT generates that in ${formatWait(waitMs)}; retry then.`; - return new Error(`Insufficient dust for transaction fees.\nAvailable: ${toDust(have)} DUST, need ≥${toDust(needed)} DUST.\n${when}`); + return new DustRequiredError(`Insufficient dust for transaction fees.\nAvailable: ${toDust(have)} DUST, need ≥${toDust(needed)} DUST.\n${when}`); } /** diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 1e68b394..0bc7bac9 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -373,7 +373,7 @@ export interface ShieldedTransferParams extends WalletSyncHooks { amount: bigint; /** Says each step, and the time the submit has taken. */ progress: Spinner; - /** The refusal when the wallet holds less shielded NIGHT than `amount`, given what it holds, in NIGHT. */ + /** The message of the InsufficientBalanceError thrown when the wallet holds less shielded NIGHT than `amount`, given what it holds, in NIGHT. */ insufficient: (availableNight: string) => string; /** Right after another payment the wallet's Dust can be short of this fee: wait when the rest is moments away. */ waitForDustToCover: boolean; diff --git a/packages/cli-core/src/lib/errors.ts b/packages/cli-core/src/lib/errors.ts index 9bcb33de..aa2a9797 100644 --- a/packages/cli-core/src/lib/errors.ts +++ b/packages/cli-core/src/lib/errors.ts @@ -61,6 +61,50 @@ export class TransactionRefusedError extends Error { } } +/** Not enough Dust to pay a transaction's fee: raised by mn's checks and by the engines, so its code is the engine contract's. */ +export class DustRequiredError extends Error { + readonly code = 'DUST_REQUIRED'; + + constructor(message: string) { + super(message); + this.name = 'DustRequiredError'; + Object.setPrototypeOf(this, DustRequiredError.prototype); + } +} + +/** Not enough NIGHT for the amount asked for: raised by the engines with the message the command gives them. */ +export class InsufficientBalanceError extends Error { + readonly code = 'INSUFFICIENT_BALANCE'; + + constructor(message: string) { + super(message); + this.name = 'InsufficientBalanceError'; + Object.setPrototypeOf(this, InsufficientBalanceError.prototype); + } +} + +/** A wait for the chain, the indexer or the proof server passed its deadline. */ +export class SyncTimeoutError extends Error { + readonly code = 'SYNC_TIMEOUT'; + + constructor(message: string) { + super(message); + this.name = 'SyncTimeoutError'; + Object.setPrototypeOf(this, SyncTimeoutError.prototype); + } +} + +/** A connection to the node, the indexer or the proof server failed; `cause` is the transport's own error. */ +export class NetworkError extends Error { + readonly code = 'NETWORK_ERROR'; + + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = 'NetworkError'; + Object.setPrototypeOf(this, NetworkError.prototype); + } +} + /** * A command that ended with a non-zero exit code without throwing (a test run * whose tests failed): the code, and the JSON result it wrote. A runner with no diff --git a/packages/cli-core/src/lib/exec-program.ts b/packages/cli-core/src/lib/exec-program.ts index 77619925..2ab1fcea 100644 --- a/packages/cli-core/src/lib/exec-program.ts +++ b/packages/cli-core/src/lib/exec-program.ts @@ -30,8 +30,10 @@ export class ProgramFailedError extends Error { } } -/** The program ran past its time limit and was killed. */ +/** The program ran past its time limit and was killed. Its code is NETWORK_ERROR: the programs mn runs with a limit are Docker's, which hang when its daemon or the network does. */ export class ProgramTimedOutError extends Error { + readonly code = 'NETWORK_ERROR'; + constructor(readonly command: string, timeoutMs: number) { super(`Command timed out (ETIMEDOUT) after ${timeoutMs / 1000}s: ${command}`); this.name = 'ProgramTimedOutError'; diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index c7c872fd..57d8fdf9 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -118,10 +118,23 @@ interface ClassifiedError { * the rules below, which read its message. */ export function classifyError(err: Error, codes?: CodeRegistry): ClassifiedError { + return (codes === undefined ? undefined : byCode(err, codes)) ?? legacyByMessage(err); +} + +/** + * The classification by the error's code alone: UNKNOWN for an error that + * carries no code `codes` defines, whatever its message says. Tests use it to + * check that a typed error reports its code without the message rules. + */ +export function classifyByCode(err: Error, codes: CodeRegistry): ClassifiedError { + return byCode(err, codes) ?? { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN }; +} + +/** The definition of the code `err` carries, as an exit code and code; undefined when `codes` defines none. */ +function byCode(err: Error, codes: CodeRegistry): ClassifiedError | undefined { const code = (err as { code?: unknown }).code; - const defined = typeof code === 'string' ? codes?.code(code) : undefined; - if (defined !== undefined) return { exitCode: defined.exitCode, errorCode: defined.code }; - return legacyByMessage(err); + const defined = typeof code === 'string' ? codes.code(code) : undefined; + return defined === undefined ? undefined : { exitCode: defined.exitCode, errorCode: defined.code }; } /** diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index 09d8d506..26c77c5e 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -16,7 +16,7 @@ import type { ServedWalletSession, ShieldedTransferParams, } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; @@ -48,7 +48,7 @@ async function shieldedTransfer(repo: WalletDataRepository, params: ShieldedTran const shieldedBalance = state.shielded.balances[nightToken] ?? 0n; if (shieldedBalance < amount) { - throw new Error(params.insufficient((Number(shieldedBalance) / 1_000_000).toFixed(6))); + throw new InsufficientBalanceError(params.insufficient((Number(shieldedBalance) / 1_000_000).toFixed(6))); } progress.update('Checking dust...'); diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index 356c2547..4fcaea07 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -16,7 +16,7 @@ import type { ServedWalletSession, ShieldedTransferParams, } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; @@ -48,7 +48,7 @@ async function shieldedTransfer(repo: WalletDataRepository, params: ShieldedTran const shieldedBalance = state.shielded.balances[nightToken] ?? 0n; if (shieldedBalance < amount) { - throw new Error(params.insufficient((Number(shieldedBalance) / 1_000_000).toFixed(6))); + throw new InsufficientBalanceError(params.insufficient((Number(shieldedBalance) / 1_000_000).toFixed(6))); } progress.update('Checking dust...'); diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index 714db51c..2e2d80c9 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -4,14 +4,25 @@ // the installed registry (what the shell and the MCP server report now). They // differ only where the owner approved it (Y52): NO_STATE_ROOT, NO_PAYER and // NO_NODE_RUNTIME by name instead of UNKNOWN, an escaped stale cache as -// STALE_CACHE, and a failed command run through MCP as COMMAND_FAILED. +// STALE_CACHE, and a failed command run through MCP as COMMAND_FAILED; and +// (Y53) a wallet with no NIGHT as INSUFFICIENT_BALANCE and an unreachable +// indexer as NETWORK_ERROR, whatever their messages say. A third +// classification reads the error's code alone, with no message rule: what the +// shell and the MCP server report once the rules are gone. import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { CancelledError, CommandFailedError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { parseArgs, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { dustShortError } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +import { ProgramTimedOutError } from '@kuiralabs/midnight-cli-core/lib/exec-program'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; @@ -30,9 +41,33 @@ import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; import { LocalStackUnreachableError, UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; import { ChainClockBehindError } from '@kuiralabs/midnight-chain/lib/chain-clock'; +import { waitForFirstBlock } from '@kuiralabs/midnight-chain/lib/node-ready'; +import { waitForAddressFunded } from '@kuiralabs/midnight-chain/lib/indexer-ready'; +import { waitForProofServerReady } from '@kuiralabs/midnight-chain/lib/proof-server-ready'; +import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; import { StaleCacheError } from '@kuiralabs/midnight-engine-rc/facade'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import * as ledger from '@midnightntwrk/ledger-v9'; import { readPassphrase } from '../lib/passphrase.ts'; -import { assertWalletFileExists, setActiveWallet } from '../lib/wallet-config.ts'; +import { assertWalletFileExists, assertWalletRemovable, setActiveWallet } from '../lib/wallet-config.ts'; +import { walletSecretFrom } from '../lib/wallet-create.ts'; +import { resolveTransferRequest } from '../lib/transfer-request.ts'; +import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; +import { PrepStepFailedError, runPrepSteps } from '../lib/test/prep-runner.ts'; +import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; +import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import walletCommand from '../commands/wallet.ts'; +import generateCommand from '../commands/generate.ts'; +import addressCommand from '../commands/address.ts'; +import airdropCommand from '../commands/airdrop.ts'; +import balanceCommand from '../commands/balance.ts'; +import { cliCall } from './helpers/cli-call.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { UnsupportedNodeError } from '../lib/node-version.ts'; import { LocalnetUnavailableError } from '../lib/localnet.ts'; import { scriptRuntime } from '../lib/contract/runner.ts'; @@ -42,9 +77,41 @@ import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/gra import { installedCommands } from '../lib/installed-commands.ts'; let root: string; -beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'mn-code-parity-')); }); +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'mn-code-parity-')); + saveWalletConfig({ seed: SEED.toString('hex'), addresses: ADDRESSES, createdAt: new Date(0).toISOString() }, join(root, 'wallets', 'alice.json')); +}); afterAll(() => { rmSync(root, { recursive: true, force: true }); }); +const SEED = Buffer.from('00'.repeat(31) + '11', 'hex'); +const ADDRESSES = deriveAllAddresses(SEED); +const OTHER_ADDRESSES = deriveAllAddresses(Buffer.from('00'.repeat(31) + '22', 'hex')); + +/** A host on the test's state root, never ~/.midnight, with the engines mn ships. */ +const hostOnRoot = () => createHost({ paths: { stateRoot: root, home: root }, engineLoader: loadInstalledEngine }); +/** The command run as the shell runs it, on the test's state root. */ +const run = (handler: CommandHandler, ...argv: string[]) => () => cliCall(handler, parseArgs(argv), { host: hostOnRoot() }); + +/** Nothing listens on port 9 here: a connection to it is refused. */ +const CLOSED_WS = 'ws://127.0.0.1:9'; +const CLOSED_HTTP = 'http://127.0.0.1:9'; +/** The chain and the indexer stand in at the rc engine's repository seams: alice holds `night` and no Dust. */ +const STAND_IN: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', node: 'ws://test/node', proofServer: 'http://test/proof', networkId: 'Undeployed' }; +const holding = (night: bigint) => createHost({ + paths: { stateRoot: root, home: root }, + engineLoader: async (_set, host) => createRcEngine(host, { + repository: { + fetchProtocolVersion: async () => 2001000n, + fetchTip: async () => 'tip-1', + fetchUnshielded: async () => ({ balances: new Map(night === 0n ? [] : [[NATIVE_TOKEN_TYPE, night]]), utxoCount: 1, txCount: 1, highestTxId: 1, registeredUtxos: 0, unregisteredUtxos: 1 }), + fetchDust: async () => { + const state = new ledger.DustLocalState(new ledger.DustParameters(5_000_000_000n, 8_267n, 10_800n)); + return { balance: 0n, availableCoins: 0, eventCount: 0, ownedUtxoCount: 0, syncTime: state.syncTime, state, retention: { ownedGenerationIndices: [], generationFrontier: 0 }, lastAppliedEventId: 0, partial: false }; + }, + }, + }), +}); + /** What the function throws; fails the test when it throws nothing. */ async function thrownBy(run: () => unknown): Promise { try { @@ -63,8 +130,9 @@ const TWENTY_NIGHT = { dust: { generatedNow: 337_954_960_000_000n, rate: 165_340 type Classified = { errorCode: string; exitCode: number }; const as = (errorCode: string, exitCode: number): Classified => ({ errorCode, exitCode }); -/** [where it is thrown, how to throw it, without the registry, with it]. */ -const ROWS: [string, () => unknown, Classified, Classified][] = [ +/** [where it is thrown, how to throw it, without the registry, with it, by its code alone (as with it, unless given)]. */ +type Row = [string, () => unknown, Classified, Classified, Classified?]; +const ROWS: Row[] = [ // The caller's to fix: exit 2. ['a usage error', () => { throw new UsageError('Missing required flag: --to'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], ['no passphrase to be had', () => readPassphrase(null, { env: {} }), as('PASSPHRASE_REQUIRED', 2), as('PASSPHRASE_REQUIRED', 2)], @@ -75,10 +143,25 @@ const ROWS: [string, () => unknown, Classified, Classified][] = [ ['coins an open offer holds', () => { throw new OfferCoinsInUseError(['ab'.repeat(32)]); }, as('OFFER_COINS_IN_USE', 2), as('OFFER_COINS_IN_USE', 2)], ['no such open offer (a usage error)', () => { throw new NoSuchOfferError('ab'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], ['an account unreachable on this set (a usage error)', () => { throw new UnreachableByAccountError('undeployed'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + // Arguments the message rules read as usage mistakes, now usage errors (approved: shown as "Usage"). + ['a required flag missing', () => requireFlag(parseArgs(['contract', 'call']), 'address', 'contract address'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['wallet generate with no name', run(walletCommand, 'wallet', 'generate'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['wallet generate with a seed and a mnemonic', run(walletCommand, 'wallet', 'generate', 'bob', '--seed', 'ab'.repeat(32), '--mnemonic', 'one two'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['wallet use with no name', run(walletCommand, 'wallet', 'use'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['wallet remove with no name', run(walletCommand, 'wallet', 'remove'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['a mnemonic off the wordlist', () => walletSecretFrom({ mnemonic: 'not a mnemonic' }), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['generate with a seed and a mnemonic', run(generateCommand, 'generate', '--seed', 'ab'.repeat(32), '--mnemonic', 'one two'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['generate with a mnemonic off the wordlist', run(generateCommand, 'generate', '--mnemonic', 'not a mnemonic'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['address with a negative key index', run(addressCommand, 'address', '--seed', 'ab'.repeat(32), '--index', '-1'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['airdrop with no amount', run(airdropCommand, 'airdrop'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ["balance of an address on another network than --network", run(balanceCommand, 'balance', OTHER_ADDRESSES.undeployed, '--network', 'preprod'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ["the shielded balance of someone else's address", run(balanceCommand, 'balance', OTHER_ADDRESSES.preview, '--shielded', '--network', 'preview'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['a shielded transfer where shielded is off', () => resolveTransferRequest(parseArgs(['transfer', deriveAllShieldedAddresses(SEED).preprod, '1', '--wallet', 'alice', '--shielded', '--network', 'preprod']), root, hostOnRoot()), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], // No such wallet: exit 3, by its message. ['no wallet of that name', () => setActiveWallet(root, 'nobody'), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], ['no wallet file', () => assertWalletFileExists(join(root, 'wallets', 'nobody.json')), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], + ['no wallet of that name to remove', () => assertWalletRemovable(root, 'nobody'), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], // Setup and network: exit 4. ['several local stacks', () => { throw new AmbiguousLocalStacksError({ node: [9944, 9945], indexer: [8088], proofServer: [6300] }); }, as('AMBIGUOUS_LOCAL_STACKS', 4), as('AMBIGUOUS_LOCAL_STACKS', 4)], @@ -90,12 +173,32 @@ const ROWS: [string, () => unknown, Classified, Classified][] = [ ['no stack at the endpoints', () => { throw new LocalStackUnreachableError('node', 'ws://127.0.0.1:1'); }, as('LOCAL_STACK_UNREACHABLE', 4), as('LOCAL_STACK_UNREACHABLE', 4)], ["the chain's clock behind", () => { throw new ChainClockBehindError(new Date(0), new Date(3_600_000)); }, as('CHAIN_CLOCK_BEHIND', 4), as('CHAIN_CLOCK_BEHIND', 4)], ['localnet up refused', () => { throw new LocalnetUnavailableError(); }, as('LOCALNET_UNAVAILABLE', 4), as('LOCALNET_UNAVAILABLE', 4)], + ['no block within the wait', () => waitForFirstBlock(CLOSED_WS, { timeoutMs: 1, pollIntervalMs: 1 }), as('SYNC_TIMEOUT', 4), as('SYNC_TIMEOUT', 4)], + ['no funds at the indexer within the wait', () => waitForAddressFunded(CLOSED_WS, ADDRESSES.undeployed, { timeoutMs: 1, pollIntervalMs: 1 }), as('SYNC_TIMEOUT', 4), as('SYNC_TIMEOUT', 4)], + ['no proof server within the wait', () => waitForProofServerReady(CLOSED_HTTP, { timeoutMs: 1, pollIntervalMs: 1 }), as('SYNC_TIMEOUT', 4), as('SYNC_TIMEOUT', 4)], + ['a node that refuses the connection', () => callNodeRpc({ url: CLOSED_WS }, 'chain_getHeader'), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], + ['an indexer subscription refused', () => subscribeGraphqlWs(CLOSED_WS, { query: 'subscription { x }', variables: {}, timeoutMs: 5_000, idleMs: 1_000, onNext: () => true, buildResult: () => undefined }), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], + ['a balance read refused', () => checkBalance(ADDRESSES.undeployed, CLOSED_WS), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], + ['an indexer query refused (approved: was UNKNOWN)', () => queryIndexer(`${CLOSED_HTTP}/`, '{ x }', undefined, 5_000), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], + // Approved: a program that ran past its limit keeps NETWORK_ERROR, which its message (ETIMEDOUT) gave it. + ['a program past its time limit', () => { throw new ProgramTimedOutError('docker compose ps', 10_000); }, as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], // Balance: exit 5. ['a Dust fee not generated yet', () => { throw new DustFeeNotGeneratedError(planRegistration(526_587_115_818_352n, [TWENTY_NIGHT]), new Date('2026-10-05T04:05:23.000Z')); }, as('DUST_GENERATING', 5), as('DUST_GENERATING', 5)], + ['Dust short of a fee', () => { throw dustShortError(1n, 2n, null); }, as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], + ['a paying wallet with no NIGHT (approved: was UNKNOWN)', () => assertWalletCanPay({ network: 'undeployed', root, host: holding(0n), networkConfig: STAND_IN, endpoints: {} }, 'alice', silentSpinner()), as('UNKNOWN', 1), as('INSUFFICIENT_BALANCE', 5)], + ['a paying wallet with no Dust', () => assertWalletCanPay({ network: 'undeployed', root, host: holding(5_000_000n), networkConfig: STAND_IN, endpoints: {} }, 'alice', silentSpinner()), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], + // A test run's Dust step, and an engine's shielded transfer, need a chain: their errors as those sites throw them. + ["a test run's Dust not available", () => { throw new DustRequiredError('Dust not available after 90s. The chain may be slow — try again.'); }, as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], + ["a test run's wallet with no NIGHT (approved: was UNKNOWN)", () => { throw new InsufficientBalanceError('Wallet has 0 NIGHT on preprod. Fund your wallet before running tests:\n mn airdrop 100 (if faucet available)\n Or transfer NIGHT from another wallet.'); }, as('UNKNOWN', 1), as('INSUFFICIENT_BALANCE', 5)], + // A failed prep step reports its step's code. + ['a prep step short of Dust', () => { throw new PrepStepFailedError('dust', new DustRequiredError('Dust not available after 90s. The chain may be slow — try again.')); }, as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], + ['shielded NIGHT short of a transfer', () => { throw new InsufficientBalanceError('Insufficient shielded balance: 1.000000 NIGHT available, 2 NIGHT requested.\nFund shielded balance: midnight airdrop 2 --shielded'); }, as('INSUFFICIENT_BALANCE', 5), as('INSUFFICIENT_BALANCE', 5)], + ["the genesis wallet's shielded NIGHT short of an airdrop", () => { throw new InsufficientBalanceError('Genesis wallet has insufficient shielded balance: 1.000000 NIGHT available, 2 NIGHT requested'); }, as('INSUFFICIENT_BALANCE', 5), as('INSUFFICIENT_BALANCE', 5)], // Refused transactions and stale state: exit 6. - ["the node's refusal", () => { throw new TransactionRefusedError('Invalid transaction'); }, as('TX_REJECTED', 6), as('TX_REJECTED', 6)], + // It carries no code yet: its name and the node's words in its message classify it. + ["the node's refusal", () => { throw new TransactionRefusedError('Invalid transaction'); }, as('TX_REJECTED', 6), as('TX_REJECTED', 6), as('UNKNOWN', 1)], ['a stale cache that escapes (approved: was UNKNOWN)', () => { throw new StaleCacheError('applied 120 of 80 events'); }, as('UNKNOWN', 1), as('STALE_CACHE', 6)], // Cancelled: exit 7. @@ -113,12 +216,14 @@ const ROWS: [string, () => unknown, Classified, Classified][] = [ // Without the registry its code came from its result's text: here, words that read as a network error. ['a failed command (approved: was by its text)', () => { throw new CommandFailedError('test run', 1, { overall: 'fail', error: 'network error' }); }, as('NETWORK_ERROR', 4), as('COMMAND_FAILED', 1)], ['an error no rule knows', () => { throw new Error('Something unexpected happened'); }, as('UNKNOWN', 1), as('UNKNOWN', 1)], + ['a prep step that failed with no code', () => runPrepSteps({ network: 'undeployed', prep: ['no-such-step'] } as unknown as DappTestConfig, root, createPrepContext(root, hostOnRoot(), createSdkWarningRouter().openCall().warnings, new AbortController().signal), { onStepStart: () => {}, onStepComplete: () => {}, onMessage: () => {} }), as('UNKNOWN', 1), as('UNKNOWN', 1)], ]; describe('the code and exit code of each typed error', () => { - it.each(ROWS)('%s', async (_where, run, before, now) => { - const err = await thrownBy(run); + it.each(ROWS)('%s', async (_where, throwIt, before, now, byCode = now) => { + const err = await thrownBy(throwIt); expect(classifyError(err)).toStrictEqual(before); expect(classifyError(err, installedCommands)).toStrictEqual(now); + expect(classifyByCode(err, installedCommands)).toStrictEqual(byCode); }); }); diff --git a/src/commands/address.ts b/src/commands/address.ts index ed895be4..4471e849 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -7,6 +7,7 @@ import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-net import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function addressCommand(args: ParsedArgs, ctx: CallContext): Promise { // `address` is a seed-derivation tool with no active-wallet notion → requireExplicit. @@ -16,7 +17,7 @@ export default async function addressCommand(args: ParsedArgs, ctx: CallContext) const indexStr = getFlag(args, 'index'); const keyIndex = indexStr !== undefined ? parseInt(indexStr, 10) : 0; if (isNaN(keyIndex) || keyIndex < 0 || !Number.isInteger(Number(indexStr ?? '0'))) { - throw new Error('Key index must be a non-negative integer'); + throw new UsageError('Key index must be a non-negative integer'); } const networkName = resolveNetworkName({ args, configDir: root }); diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index b0f33600..bb78250a 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -9,7 +9,7 @@ // file required, useful for funding externally-generated addresses. // A shielded address implies --shielded; the flag is optional there. -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAddress, type UnlockHost } from '../lib/wallet-config.ts'; import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; @@ -27,7 +27,7 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) rejectNoCacheForWrites(args); const amountStr = args.subcommand; if (!amountStr) { - throw new Error( + throw new UsageError( 'Missing amount.\n' + 'Usage: midnight airdrop [--wallet ]\n' + 'Example: midnight airdrop 1000\n' + diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 69e46dfb..ce9cf730 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -16,6 +16,7 @@ import { header, keyValue, divider, formatNight, formatAddress, toNight } from ' import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function balanceCommand(args: ParsedArgs, ctx: CallContext): Promise { // Positional address → unshielded only (lightweight, no facade) @@ -55,7 +56,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise const inferredNetwork = inferNetworkFromAddress(address); const explicitNetwork = getFlag(args, 'network'); if (explicitNetwork && inferredNetwork && explicitNetwork !== inferredNetwork) { - throw new Error( + throw new UsageError( `Address belongs to ${inferredNetwork} but --network is ${explicitNetwork}.\n` + `Drop --network (we'll infer from the address) or pass an address for ${explicitNetwork}.` ); @@ -81,7 +82,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise }; return walletBalance(delegated, ctx); } - throw new Error( + throw new UsageError( `Shielded balances are private — they can only be read with the wallet's secret key, ` + `not from an address alone.\n` + `This address isn't one of your wallets. Check its shielded balance from the wallet that owns it:\n` + diff --git a/src/commands/generate.ts b/src/commands/generate.ts index b918e2a5..f87ead3a 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -16,7 +16,7 @@ import { header, keyValue, divider, formatAddress } from '@kuiralabs/midnight-cl import { bold, yellow, dim, green } from '@kuiralabs/midnight-cli-core/ui/colors'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { getDefaultWalletPath } from '../lib/wallet-paths.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function generateCommand(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; @@ -32,7 +32,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext const mnemonicStr = getFlag(args, 'mnemonic'); if (seedHex !== undefined && mnemonicStr !== undefined) { - throw new Error('Cannot specify both --seed and --mnemonic. Use one or the other.'); + throw new UsageError('Cannot specify both --seed and --mnemonic. Use one or the other.'); } // Overwrite protection: check if target file already exists @@ -56,7 +56,7 @@ export default async function generateCommand(args: ParsedArgs, ctx: CallContext } else if (mnemonicStr !== undefined) { // Mode: restore from mnemonic if (!validateMnemonic(mnemonicStr, wordlist)) { - throw new Error('Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.'); + throw new UsageError('Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.'); } mnemonic = mnemonicStr; seedBuffer = Buffer.from(mnemonicToSeedSync(mnemonic)); diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index ef059176..e1f555dd 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -58,7 +58,7 @@ export default async function walletCommand(args: ParsedArgs, ctx: WalletCommand async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise { const name = args.positionals[0]; if (!name) { - throw new Error( + throw new UsageError( 'Missing wallet name.\nUsage: midnight wallet generate [--network ]' ); } @@ -71,7 +71,7 @@ async function walletGenerate(args: ParsedArgs, ctx: CallContext): Promise const mnemonicStr = getFlag(args, 'mnemonic'); if (seedHex !== undefined && mnemonicStr !== undefined) { - throw new Error('Cannot specify both --seed and --mnemonic. Use one or the other.'); + throw new UsageError('Cannot specify both --seed and --mnemonic. Use one or the other.'); } if (fs.existsSync(targetPath) && !hasFlag(args, 'force')) { @@ -216,7 +216,7 @@ async function walletList(args: ParsedArgs, ctx: CallContext): Promise { async function walletUse(args: ParsedArgs, ctx: CallContext): Promise { const name = args.positionals[0]; if (!name) { - throw new Error( + throw new UsageError( 'Missing wallet name.\nUsage: midnight wallet use ' ); } @@ -305,7 +305,7 @@ async function walletInfo(args: ParsedArgs, ctx: CallContext): Promise { async function walletRemove(args: ParsedArgs, ctx: CallContext): Promise { const name = args.positionals[0]; if (!name) { - throw new Error( + throw new UsageError( 'Missing wallet name.\nUsage: midnight wallet remove ' ); } diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index a8bd198b..6e40f34a 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -12,9 +12,22 @@ import type { DappTestConfig, PrepStepId, PrepStepResult, PrepContext, PrepCallb import { startServeOrReuse } from '../serve-manager.ts'; import { OWN_COMMAND_DUST_WAIT_MS } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; import { startBuild } from './build-manager.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { DustRequiredError, InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; +/** A prep step failed: the step's own error is its cause, and its code (DUST_REQUIRED, …) is this one's. */ +export class PrepStepFailedError extends Error { + readonly code: string | undefined; + + constructor(step: PrepStepId, cause: unknown) { + super(`Prep step "${step}" failed: ${(cause as Error).message}`, { cause }); + const code = (cause as { code?: unknown } | null)?.code; + this.code = typeof code === 'string' ? code : undefined; + this.name = 'PrepStepFailedError'; + Object.setPrototypeOf(this, PrepStepFailedError.prototype); + } +} + /** * Run all prep steps defined in the config, in order. * Accumulates long-running resources (serve, build) in the PrepContext for teardown. @@ -42,7 +55,7 @@ export async function runPrepSteps( const error = (err as Error).message; results.push({ step, status: 'fail', duration, error }); callbacks.onStepComplete(step, 'fail', duration, error); - throw new Error(`Prep step "${step}" failed: ${error}`); + throw new PrepStepFailedError(step, err); } } @@ -133,7 +146,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont // Balance is zero if (network !== 'undeployed') { - throw new Error( + throw new InsufficientBalanceError( `Wallet has 0 NIGHT on ${network}. Fund your wallet before running tests:\n` + ` mn airdrop ${amount} (if faucet available)\n` + ` Or transfer NIGHT from another wallet.` @@ -184,13 +197,13 @@ async function stepDust(config: DappTestConfig, ctx: PrepContext, callbacks: Pre // Verify dust is actually available — don't trust silent timeouts if (!dustAvailable) { if (network !== 'undeployed') { - throw new Error( + throw new DustRequiredError( `Dust not available on ${network}. Register dust and wait for it to generate:\n` + ` mn dust register\n` + ` mn dust status (check until dustAvailable: true)` ); } - throw new Error(`Dust not available after ${DUST_WAIT_TIMEOUT_MS / 1000}s. The chain may be slow — try again.`); + throw new DustRequiredError(`Dust not available after ${DUST_WAIT_TIMEOUT_MS / 1000}s. The chain may be slow — try again.`); } } finally { stopListening(); diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 593b2c17..0b594714 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -52,7 +52,7 @@ export async function resolveTransferRequest(args: ParsedArgs, root: string, hos if (shielded) { if (!shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded'))) { - throw new Error(shieldedDisabledReason(networkName)); + throw new UsageError(shieldedDisabledReason(networkName)); } } assertRecipient((await host.engines.load(sdkSetOf(networkName, root))).keys, recipientAddress, shielded, networkName); diff --git a/src/lib/wallet-can-pay.ts b/src/lib/wallet-can-pay.ts index 7622c94a..6a9b3a2b 100644 --- a/src/lib/wallet-can-pay.ts +++ b/src/lib/wallet-can-pay.ts @@ -3,7 +3,7 @@ // and no strict sync is needed. import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { DustRequiredError, InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import type { PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { resolveWalletPath, unlockWallet } from './wallet-config.ts'; @@ -33,7 +33,7 @@ export async function assertWalletCanPay({ network, root, host, networkConfig }: if (nightBalance === 0n) { progress.fail('No NIGHT balance'); - throw new Error( + throw new InsufficientBalanceError( `Wallet has 0 NIGHT on ${network}.\n\n` + ` Fund your wallet before deploying:\n` + ` Address: ${address}\n` + @@ -46,7 +46,7 @@ export async function assertWalletCanPay({ network, root, host, networkConfig }: const dustView = await repo.dustBalance(seedBuffer, networkConfig, { root, notice: host.notice, signal, onStatus: (s) => progress.update(s) }); if (dustView.balance === 0n && dustView.availableCoins === 0) { progress.fail('No dust available'); - throw new Error( + throw new DustRequiredError( `Wallet has no dust on ${network}. Dust is required to pay transaction fees.\n\n` + ` Register for dust generation:\n` + ` Run: midnight dust register --network ${network}\n` + diff --git a/src/lib/wallet-config.ts b/src/lib/wallet-config.ts index e472dc1c..2c579745 100644 --- a/src/lib/wallet-config.ts +++ b/src/lib/wallet-config.ts @@ -11,6 +11,17 @@ import { type PassphraseHost, type PassphraseSource, unlockPassphrase } from './ import { defineHostSlot, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +/** No wallet by that name, or no wallet file at that path; the message says how to list or make one. */ +export class WalletNotFoundError extends Error { + readonly code = 'WALLET_NOT_FOUND'; + + constructor(message: string) { + super(message); + this.name = 'WalletNotFoundError'; + Object.setPrototypeOf(this, WalletNotFoundError.prototype); + } +} + /** What anyone may read of a wallet: its addresses, and whether its secrets are sealed. No secret. */ export interface WalletConfig { addresses: Record; @@ -160,7 +171,7 @@ export function setActiveWallet(root: string, name: string): void { } const walletPath = path.join(getWalletsDir(root), `${name}.json`); if (!fs.existsSync(walletPath)) { - throw new Error( + throw new WalletNotFoundError( `Wallet "${name}" not found.\nRun "midnight wallet list" to see available wallets.` ); } @@ -285,7 +296,7 @@ export function assertWalletRemovable(root: string, name: string): string { const walletPath = path.join(walletsDir, `${name}.json`); if (!fs.existsSync(walletPath)) { - throw new Error( + throw new WalletNotFoundError( `Wallet "${name}" not found.\nRun "midnight wallet list" to see available wallets.` ); } @@ -316,7 +327,7 @@ export function removeWallet(root: string, name: string): void { /** Throws, with how to make one, when there is no wallet file at `resolvedPath`. */ export function assertWalletFileExists(resolvedPath: string): void { if (!fs.existsSync(resolvedPath)) { - throw new Error( + throw new WalletNotFoundError( `Wallet file not found: ${resolvedPath}\n` + `Generate a wallet first: midnight wallet generate --network ` ); diff --git a/src/lib/wallet-create.ts b/src/lib/wallet-create.ts index 9b3187db..5faf457c 100644 --- a/src/lib/wallet-create.ts +++ b/src/lib/wallet-create.ts @@ -10,6 +10,7 @@ import type { Engine } from '@kuiralabs/midnight-cli-core/lib/engine'; import { writeSealedWallet, setActiveWallet, type WalletPublic } from './wallet-config.ts'; import { isValidWalletName } from '@kuiralabs/midnight-cli-core/lib/constants'; import { getWalletsDir } from './wallet-paths.ts'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; /** A wallet's secret: the seed, and the mnemonic it came from when there is one. */ export interface WalletSecret { @@ -42,7 +43,7 @@ export function walletSecretFrom(given: { seed?: Buffer; mnemonic?: string } = { if (given.seed !== undefined) return { seed: given.seed }; if (given.mnemonic !== undefined) { if (!validateMnemonic(given.mnemonic, wordlist)) { - throw new Error('Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.'); + throw new UsageError('Invalid BIP-39 mnemonic. Expected 12 or 24 words from the English wordlist.'); } return { seed: Buffer.from(mnemonicToSeedSync(given.mnemonic)), mnemonic: given.mnemonic }; } From d9d8d1c634698ee79f751af7e1723213e10e02da Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 10:25:42 -0800 Subject: [PATCH 64/88] Codes at the engine, contract, connector and grant boundaries (3C, 5-6 of 8) The engine contract in core recognises the SDK's and the node's text in one place (toEngineError) and turns it into typed errors: proof timeout and failure, stale UTXO (refusal 115), invalid Dust proof (170), stale wallet state, Dust shortage and insufficient funds; a refused transaction carries a code chosen from the node's reason. Only the engines and core's wallet session use it. Both engines' wallet methods raise typed errors after their own retries. Across process and wire boundaries the code travels with the error: the contract script writes {message, code} on its failure line and the runner rebuilds it; the connector's RPC carries mn's code as data.mnCode beside the connector API's own code, which dApps read and which is unchanged. grant reads the error's code. Approved (Y54): a ZK proof that times out reports PROOF_TIMEOUT, and a contract script's refused transaction TX_REJECTED (or the stale-UTXO or Dust-proof code) whatever the node's wording, as in-process does. Suite 2702, beta 180; snapshot unchanged; fresh install; scratch chain final pass 84/84 in a clean runner (the rig's MCP tool count updated to 44), swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads. --- packages/cli-core/api-report.md | 56 +++++- packages/cli-core/src/lib/connector-api.ts | 9 +- packages/cli-core/src/lib/errors.ts | 97 +++++++++- packages/cli-core/src/lib/sdk-errors.ts | 165 +++++++++++++++++- packages/cli-core/src/lib/wallet-session.ts | 16 +- packages/engine-beta/src/airdrop.ts | 11 +- packages/engine-beta/src/dapp-connector.ts | 16 +- packages/engine-beta/src/facade.ts | 4 +- packages/engine-beta/src/transfer.ts | 14 +- packages/engine-beta/src/wallet.ts | 11 +- packages/engine-rc/src/airdrop.ts | 11 +- packages/engine-rc/src/dapp-connector.ts | 16 +- packages/engine-rc/src/facade.ts | 4 +- packages/engine-rc/src/transfer.ts | 14 +- packages/engine-rc/src/wallet.ts | 11 +- scripts/check-layering.mjs | 8 + src/__tests__/contract-script-errors.test.ts | 46 ++++- .../engine-beta-boundary-errors.test.ts | 27 +++ src/__tests__/engine-boundary-errors.test.ts | 18 ++ src/__tests__/error-code-parity.test.ts | 73 +++++++- src/__tests__/helpers/connector-suite.ts | 27 ++- .../helpers/engine-boundary-suite.ts | 102 +++++++++++ src/__tests__/helpers/serve-script-failure.ts | 36 ++++ src/__tests__/layering.test.ts | 10 ++ src/__tests__/sdk-errors.test.ts | 69 +++++++- src/__tests__/wallet-session.test.ts | 46 ++++- src/__tests__/ws-rpc.test.ts | 44 +++++ src/commands/grant.ts | 11 +- src/lib/contract/runner.ts | 46 ++++- src/lib/ws-rpc.ts | 20 ++- src/mcp-server.ts | 6 +- src/wallet.ts | 7 +- 32 files changed, 946 insertions(+), 105 deletions(-) create mode 100644 src/__tests__/engine-beta-boundary-errors.test.ts create mode 100644 src/__tests__/engine-boundary-errors.test.ts create mode 100644 src/__tests__/helpers/engine-boundary-suite.ts create mode 100644 src/__tests__/helpers/serve-script-failure.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 932cb8e3..c863178e 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -676,7 +676,7 @@ export interface RpcHandlerContext { metadata: Record; } export type RpcHandler = (params: Record, context: RpcHandlerContext) => Promise; -export declare function createApiError(code: ErrorCode, reason: string): APIError; +export declare function createApiError(code: ErrorCode, reason: string, mnCode?: string): APIError; export declare const OPERATOR_REJECTED_MESSAGE = "User rejected the request"; ``` @@ -1199,21 +1199,62 @@ export declare class CancelledError extends Error { } export declare class TransactionRefusedError extends Error { readonly reason: string; + readonly code: RefusalCode; constructor(reason: string, options?: { cause?: unknown; + code?: RefusalCode; + }); +} +export type RefusalCode = "TX_REJECTED" | "STALE_UTXO" | "INVALID_DUST_PROOF"; +export declare function asReported(err: Error): Error; +export declare class EngineError extends Error { + readonly code: string; + constructor(code: string, message: string, options?: { + cause?: unknown; + }); +} +export declare class ProofTimeoutError extends EngineError { + constructor(message?: string, options?: { + cause?: unknown; + }); +} +export declare class ProofFailureError extends EngineError { + constructor(message: string, options?: { + cause?: unknown; + }); +} +export declare class StaleUtxoError extends EngineError { + constructor(message: string, options?: { + cause?: unknown; + }); +} +export declare class InvalidDustProofError extends EngineError { + constructor(message: string, options?: { + cause?: unknown; + }); +} +export declare class StaleWalletStateError extends EngineError { + constructor(message: string, options?: { + cause?: unknown; }); } export declare class DustRequiredError extends Error { readonly code = "DUST_REQUIRED"; - constructor(message: string); + constructor(message: string, options?: { + cause?: unknown; + }); } export declare class InsufficientBalanceError extends Error { readonly code = "INSUFFICIENT_BALANCE"; - constructor(message: string); + constructor(message: string, options?: { + cause?: unknown; + }); } export declare class SyncTimeoutError extends Error { readonly code = "SYNC_TIMEOUT"; - constructor(message: string); + constructor(message: string, options?: { + cause?: unknown; + }); } export declare class NetworkError extends Error { readonly code = "NETWORK_ERROR"; @@ -1643,6 +1684,7 @@ export declare function resolveNetwork(ctx: NetworkResolutionContext, settings: ## `@kuiralabs/midnight-cli-core/lib/sdk-errors` ```ts +import { type RefusalCode } from "./errors.ts"; export declare function isTransactionRejectedError(err: any): boolean; export declare function isDustShortage(err: unknown): boolean; export interface DustShortfall { @@ -1656,6 +1698,12 @@ export declare function isSdkInsufficientFundsError(err: any): boolean; export declare function isColdStartRace(err: unknown): boolean; export declare function nodeRefusalOf(err: unknown): string | undefined; export declare function withNodeReason(err: Error): Error; +export declare function refusalCodeOf(reason: string): RefusalCode; +export declare function mnCodeOf(err: unknown): string | undefined; +export declare function toEngineError(err: unknown): unknown; +export declare function withEngineCode(err: unknown): unknown; +export declare function reportingEngineErrors(operations: T): T; +export declare function markingEngineCodes Promise>>(handlers: T): T; ``` ## `@kuiralabs/midnight-cli-core/lib/sdk-layout` diff --git a/packages/cli-core/src/lib/connector-api.ts b/packages/cli-core/src/lib/connector-api.ts index 8da92187..d0c1bd24 100644 --- a/packages/cli-core/src/lib/connector-api.ts +++ b/packages/cli-core/src/lib/connector-api.ts @@ -34,11 +34,18 @@ export type RpcHandler = (params: Record, context: RpcHandlerCo // ── APIError factory ── -export function createApiError(code: ErrorCode, reason: string): APIError { +/** + * An APIError with the API's code. `mnCode`, when given, is mn's own code for + * the failure (DUST_REQUIRED for a fee the wallet's Dust can't pay), kept + * beside the API's as `mnCode`, outside the specification's type; the wire + * carries it as `data.mnCode`. + */ +export function createApiError(code: ErrorCode, reason: string, mnCode?: string): APIError { const error = new Error(reason) as APIError; error.type = 'DAppConnectorAPIError'; error.code = code; error.reason = reason; + if (mnCode !== undefined) Object.assign(error, { mnCode }); return error; } diff --git a/packages/cli-core/src/lib/errors.ts b/packages/cli-core/src/lib/errors.ts index aa2a9797..a74be472 100644 --- a/packages/cli-core/src/lib/errors.ts +++ b/packages/cli-core/src/lib/errors.ts @@ -52,21 +52,102 @@ export class CancelledError extends Error { */ export class TransactionRefusedError extends Error { readonly reason: string; + /** What the node's reason makes it: a stale coin (STALE_UTXO), an invalid Dust proof (INVALID_DUST_PROOF), or any other refusal (TX_REJECTED). */ + readonly code: RefusalCode; - constructor(reason: string, options?: { cause?: unknown }) { - super(`The node refused the transaction: ${reason}`, options); + constructor(reason: string, options?: { cause?: unknown; code?: RefusalCode }) { + super(`The node refused the transaction: ${reason}`, options?.cause === undefined ? undefined : { cause: options.cause }); this.name = 'TransactionRefusedError'; this.reason = reason; + this.code = options?.code ?? 'TX_REJECTED'; Object.setPrototypeOf(this, TransactionRefusedError.prototype); } } +/** The codes a node's refusal is reported with. */ +export type RefusalCode = 'TX_REJECTED' | 'STALE_UTXO' | 'INVALID_DUST_PROOF'; + +/** + * The error as it is reported: the node's refusal when one is among its + * causes (a command that wrapped a failed submission reports what the node + * said), any other error as it is. + */ +export function asReported(err: Error): Error { + const seen = new Set(); + for (let current: unknown = err; current instanceof Error && !seen.has(current); current = current.cause) { + if (current instanceof TransactionRefusedError) return current; + seen.add(current); + } + return err; +} + +/** + * A failure of the engine contract, named by its code: what an engine reports + * an SDK or node failure as, with the SDK's own message and its error as the + * cause. Its subclasses name the codes mn tells apart. + */ +export class EngineError extends Error { + readonly code: string; + + constructor(code: string, message: string, options?: { cause?: unknown }) { + super(message, options); + this.code = code; + this.name = 'EngineError'; + Object.setPrototypeOf(this, EngineError.prototype); + } +} + +/** A ZK proof took longer than mn waits for one. */ +export class ProofTimeoutError extends EngineError { + constructor(message: string = 'ZK proof generation timed out', options?: { cause?: unknown }) { + super('PROOF_TIMEOUT', message, options); + this.name = 'ProofTimeoutError'; + Object.setPrototypeOf(this, ProofTimeoutError.prototype); + } +} + +/** The proof server failed to prove a transaction (the SDK's "Failed to prove transaction"). */ +export class ProofFailureError extends EngineError { + constructor(message: string, options?: { cause?: unknown }) { + super('PROOF_FAILURE', message, options); + this.name = 'ProofFailureError'; + Object.setPrototypeOf(this, ProofFailureError.prototype); + } +} + +/** A transaction spent coins another transaction already spent (the node's error 115). */ +export class StaleUtxoError extends EngineError { + constructor(message: string, options?: { cause?: unknown }) { + super('STALE_UTXO', message, options); + this.name = 'StaleUtxoError'; + Object.setPrototypeOf(this, StaleUtxoError.prototype); + } +} + +/** The chain refused a Dust spend proof as malformed (the node's error 170, InvalidDustSpendProof). */ +export class InvalidDustProofError extends EngineError { + constructor(message: string, options?: { cause?: unknown }) { + super('INVALID_DUST_PROOF', message, options); + this.name = 'InvalidDustProofError'; + Object.setPrototypeOf(this, InvalidDustProofError.prototype); + } +} + +/** The wallet's saved state doesn't fit the chain (a reset chain, a re-indexed indexer): the SDK refused to resume from it. */ +export class StaleWalletStateError extends EngineError { + constructor(message: string, options?: { cause?: unknown }) { + super('STALE_CACHE', message, options); + this.name = 'StaleWalletStateError'; + Object.setPrototypeOf(this, StaleWalletStateError.prototype); + } +} + /** Not enough Dust to pay a transaction's fee: raised by mn's checks and by the engines, so its code is the engine contract's. */ export class DustRequiredError extends Error { readonly code = 'DUST_REQUIRED'; - constructor(message: string) { - super(message); + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); this.name = 'DustRequiredError'; Object.setPrototypeOf(this, DustRequiredError.prototype); } @@ -76,8 +157,8 @@ export class DustRequiredError extends Error { export class InsufficientBalanceError extends Error { readonly code = 'INSUFFICIENT_BALANCE'; - constructor(message: string) { - super(message); + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); this.name = 'InsufficientBalanceError'; Object.setPrototypeOf(this, InsufficientBalanceError.prototype); } @@ -87,8 +168,8 @@ export class InsufficientBalanceError extends Error { export class SyncTimeoutError extends Error { readonly code = 'SYNC_TIMEOUT'; - constructor(message: string) { - super(message); + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); this.name = 'SyncTimeoutError'; Object.setPrototypeOf(this, SyncTimeoutError.prototype); } diff --git a/packages/cli-core/src/lib/sdk-errors.ts b/packages/cli-core/src/lib/sdk-errors.ts index fd76dcc4..433e9df6 100644 --- a/packages/cli-core/src/lib/sdk-errors.ts +++ b/packages/cli-core/src/lib/sdk-errors.ts @@ -1,9 +1,23 @@ -// SDK error classifiers — pattern-match opaque SDK / chain errors into -// categories the rest of the codebase can branch on. Pure functions, no -// side effects, no I/O. Lives in its own file so both transfer.ts and -// wallet-data-repository.ts can import without a circular dependency. +// The engine contract's reading of the SDK's and the node's errors: the one +// place mn recognises their shapes and words. An engine reports each failure +// it can name as a typed error carrying its code (toEngineError), and its DApp +// connector marks the errors it answers with by their code, keeping their +// messages (withEngineCode). Only the engines, and in core the wallet session and the Dust wait, import +// this module (scripts/check-layering.mjs holds it). Pure functions, no I/O. -import { TransactionRefusedError } from './errors.ts'; +import { + DustRequiredError, + EngineError, + InsufficientBalanceError, + InvalidDustProofError, + ProofFailureError, + ProofTimeoutError, + StaleUtxoError, + StaleWalletStateError, + SyncTimeoutError, + TransactionRefusedError, + type RefusalCode, +} from './errors.ts'; /** * The chain rejected the transaction outright. Most commonly: balance check @@ -171,5 +185,144 @@ export function nodeRefusalOf(err: unknown): string | undefined { export function withNodeReason(err: Error): Error { if (err instanceof TransactionRefusedError) return err; const reason = nodeRefusalOf(err); - return reason === undefined ? err : new TransactionRefusedError(reason, { cause: err }); + return reason === undefined ? err : new TransactionRefusedError(reason, { cause: err, code: refusalCodeOf(reason) }); +} + +// The node's words for a coin another transaction spent (substrate "Custom error: 115"), and for a malformed Dust spend proof (170). +const STALE_UTXO_WORDS: readonly string[] = ['stale utxo', 'error code 115', 'custom error: 115', 'errorcode: 115']; +const INVALID_DUST_PROOF_WORDS: readonly string[] = ['error 170', 'error: 170', 'errorcode: 170', 'invaliddustspendproof']; +// The SDK refusing to resume a wallet's state on a chain it doesn't fit; "inserted non-linearly": an indexer that numbers its events differently. +const STALE_STATE_WORDS: readonly string[] = ['stale cache', 'chain reset', 'chainid mismatch', 'applied > highest', 'inserted non-linearly']; +const SYNC_TIMEOUT_WORDS: readonly string[] = ['sync timed out', 'timed out waiting for dust']; + +const saysAny = (text: string, words: readonly string[]): boolean => words.some((word) => text.includes(word)); + +/** The code a node's refusal is reported with, from its reason. */ +export function refusalCodeOf(reason: string): RefusalCode { + const said = reason.toLowerCase(); + if (saysAny(said, STALE_UTXO_WORDS)) return 'STALE_UTXO'; + if (saysAny(said, INVALID_DUST_PROOF_WORDS)) return 'INVALID_DUST_PROOF'; + return 'TX_REJECTED'; +} + +/** + * The engine contract's code for an SDK or node failure, from its shape and + * then its words, in the order mn has always told them apart (a proof that + * timed out before a refusal's number; a Dust shortage before a shortage of + * anything else); undefined for a failure it doesn't name. + */ +function engineCodeOf(err: unknown): string | undefined { + const reason = nodeRefusalOf(err); + if (reason !== undefined) return refusalCodeOf(reason); + if (!(err instanceof Error)) return undefined; + const said = err.message.toLowerCase(); + if (said.includes('proof') && said.includes('timeout')) return 'PROOF_TIMEOUT'; + if (saysAny(said, STALE_UTXO_WORDS)) return 'STALE_UTXO'; + if (saysAny(said, INVALID_DUST_PROOF_WORDS)) return 'INVALID_DUST_PROOF'; + if (saysAny(said, STALE_STATE_WORDS)) return 'STALE_CACHE'; + // The proof server's refusal: the SDK's ClientError "Failed to prove transaction". + if (said.includes('failed to prove')) return 'PROOF_FAILURE'; + if (saysAny(said, SYNC_TIMEOUT_WORDS)) return 'SYNC_TIMEOUT'; + if (isDustShortage(err) || said.includes('no dust') || (said.includes('dust') && (said.includes('required') || said.includes('available') || said.includes('insufficient')))) return 'DUST_REQUIRED'; + if (isSdkInsufficientFundsError(err) || said.includes('insufficient') || said.includes('not enough')) return 'INSUFFICIENT_BALANCE'; + if (said.includes('rejected') || said.includes('transaction failed')) return 'TX_REJECTED'; + return undefined; +} + +/** The typed error for an engine code, with the failure's message and the failure as its cause. */ +function typedEngineError(code: string, message: string, cause: unknown): Error { + const options = { cause }; + switch (code) { + case 'PROOF_TIMEOUT': return new ProofTimeoutError(message, options); + case 'PROOF_FAILURE': return new ProofFailureError(message, options); + case 'STALE_UTXO': return new StaleUtxoError(message, options); + case 'INVALID_DUST_PROOF': return new InvalidDustProofError(message, options); + case 'STALE_CACHE': return new StaleWalletStateError(message, options); + case 'SYNC_TIMEOUT': return new SyncTimeoutError(message, options); + case 'DUST_REQUIRED': return new DustRequiredError(message, options); + case 'INSUFFICIENT_BALANCE': return new InsufficientBalanceError(message, options); + default: return new EngineError(code, message, options); + } +} + +/** Where a DApp connector's error carries mn's code beside its own: an API error's `code` is the connector API's. */ +const MN_CODE = 'mnCode'; + +/** The mn code a connector error was marked with (withEngineCode, or an API error made with one); undefined when it has none. */ +export function mnCodeOf(err: unknown): string | undefined { + const code = err !== null && typeof err === 'object' ? (err as Record)[MN_CODE] : undefined; + return typeof code === 'string' ? code : undefined; +} + +const isConnectorApiError = (err: unknown): boolean => + err !== null && typeof err === 'object' && (err as { type?: unknown }).type === 'DAppConnectorAPIError'; + +/** Whether the error already carries a code of its own (mn's typed errors do); a connector API error's code is the API's, not mn's. */ +const carriesCode = (err: unknown): boolean => + !isConnectorApiError(err) && err !== null && typeof err === 'object' && typeof (err as { code?: unknown }).code === 'string'; + +/** + * The failure as an engine reports it to mn: a node's refusal as a + * TransactionRefusedError (in the node's words, coded by its reason); an SDK + * failure mn names as the typed error for its code, with the SDK's message and + * the SDK's error as its cause; a connector error marked with mn's code as the + * typed error for that code. Anything else (an error that carries its own + * code, a failure mn doesn't name) as it is. + */ +export function toEngineError(err: unknown): unknown { + if (err instanceof TransactionRefusedError) return err; + const reason = nodeRefusalOf(err); + if (reason !== undefined) return new TransactionRefusedError(reason, { cause: err, code: refusalCodeOf(reason) }); + const marked = mnCodeOf(err); + if (marked !== undefined && err instanceof Error) return typedEngineError(marked, err.message, err); + if (isConnectorApiError(err) || carriesCode(err)) return err; + const code = engineCodeOf(err); + return code === undefined || !(err instanceof Error) ? err : typedEngineError(code, err.message, err); +} + +/** + * The failure as a DApp connector answers with it: the same error, its message + * and causes as they were (a dApp reads them), marked with mn's code when the + * engine contract names it, so the code crosses the wire beside the API's own. + */ +export function withEngineCode(err: unknown): unknown { + if (err === null || typeof err !== 'object' || isConnectorApiError(err) || carriesCode(err) || mnCodeOf(err) !== undefined) return err; + const code = engineCodeOf(err); + if (code !== undefined) Object.defineProperty(err, MN_CODE, { value: code, enumerable: false, configurable: true, writable: true }); + return err; +} + +/** + * An engine's operations, each reporting its failures as toEngineError does: + * what the engine hands the rest of mn. Every operation is asynchronous. + */ +export function reportingEngineErrors(operations: T): T { + const reporting: Record = {}; + for (const [name, operation] of Object.entries(operations)) { + reporting[name] = typeof operation !== 'function' + ? operation + : async (...args: unknown[]) => { + try { + return await (operation as (...a: unknown[]) => unknown)(...args); + } catch (err) { + throw toEngineError(err); + } + }; + } + return reporting as T; +} + +/** A DApp connector's handlers, each answering with its failures marked by mn's code (withEngineCode). */ +export function markingEngineCodes Promise>>(handlers: T): T { + const marking: Record = {}; + for (const [name, handler] of Object.entries(handlers)) { + marking[name] = async (...args: never[]) => { + try { + return await handler(...args); + } catch (err) { + throw withEngineCode(err); + } + }; + } + return marking as T; } diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index 7da022fb..8d81e08f 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -18,7 +18,7 @@ import { resolveNetwork, type NetworkSettings } from './resolve-network.ts'; import { settingsFromEnvironment } from './settings.ts'; import { shieldedSyncEnabled } from './shielded-policy.ts'; import { throwIfCancelled } from './errors.ts'; -import { isColdStartRace } from './sdk-errors.ts'; +import { isColdStartRace, toEngineError } from './sdk-errors.ts'; import type { SwapLeg } from './swap-offer.ts'; import type { OpenOffer } from './open-offers.ts'; @@ -123,10 +123,18 @@ export function sessionOver( let closed = false; // Once a transaction is built, reopening would revert it under the caller. let built = false; + // The connector answers as it answers a dApp; the session reports its failures as the engine does (a node's refusal in the node's words, each with its code). + const reported = async (work: () => Promise): Promise => { + try { + return await work(); + } catch (err) { + throw toEngineError(err); + } + }; const call = async (method: string, params: Record): Promise => { if (closed) throw new Error('The wallet session is closed'); const handler = handlerOf(current.connector, method); - return handler(params, { notify: () => {}, connectionId: SESSION_CONNECTION, requestId: ++requestId, metadata: {} }); + return reported(() => handler(params, { notify: () => {}, connectionId: SESSION_CONNECTION, requestId: ++requestId, metadata: {} })); }; /** Builds a transaction, through the cold-start race while it is the session's first. */ const build = async (making: () => Promise): Promise => { @@ -188,11 +196,11 @@ export function sessionOver( }, async takeOffer(tx) { if (closed) throw new Error('The wallet session is closed'); - return build(() => current.connector.takeOffer(SESSION_CONNECTION, tx)); + return build(() => reported(() => current.connector.takeOffer(SESSION_CONNECTION, tx))); }, async cancelOffers(offers) { if (closed) throw new Error('The wallet session is closed'); - return build(() => current.connector.cancelOffers(SESSION_CONNECTION, offers)); + return build(() => reported(() => current.connector.cancelOffers(SESSION_CONNECTION, offers))); }, async sign(data, encoding) { return (await call('signData', { data, options: { encoding, keyType: 'unshielded' } })) as SignedData; diff --git a/packages/engine-beta/src/airdrop.ts b/packages/engine-beta/src/airdrop.ts index bbf732cd..d153734e 100644 --- a/packages/engine-beta/src/airdrop.ts +++ b/packages/engine-beta/src/airdrop.ts @@ -3,6 +3,8 @@ // caller has already checked that the network is the local one. import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { EngineError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { WalletDataRepository } from './wallet-data-repository.ts'; @@ -15,11 +17,12 @@ export async function airdropNight(repo: WalletDataRepository, params: AirdropPa return await executeTransfer(repo, { ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); } catch (err) { if (err instanceof Error && err.message.toLowerCase().includes('dust')) { - throw new Error( - `${err.message}\n\n` + + const message = `${err.message}\n\n` + `On a fresh localnet, the minimum airdrop is ~1 NIGHT.\n` + - `Try: midnight airdrop 1` - ); + `Try: midnight airdrop 1`; + // The note keeps the failure's code: the one it carries, or the engine contract's for the SDK's error. + const code = (toEngineError(err) as { code?: unknown }).code; + throw typeof code === 'string' ? new EngineError(code, message, { cause: err }) : new Error(message, { cause: err }); } throw err; } diff --git a/packages/engine-beta/src/dapp-connector.ts b/packages/engine-beta/src/dapp-connector.ts index 46eaa7e8..f7ed46b2 100644 --- a/packages/engine-beta/src/dapp-connector.ts +++ b/packages/engine-beta/src/dapp-connector.ts @@ -16,7 +16,8 @@ import { createApiError, type RpcHandler, type RpcHandlerContext } from '@kuiral import { createPhaseTracker, type PhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import { isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { isDustShortage, markingEngineCodes } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { ProofTimeoutError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; import { readOffer, spentNullifiers } from './offer-reader.ts'; @@ -337,7 +338,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto finalized = await Promise.race([ finalizing, new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error('ZK proof generation timed out')), PROOF_TIMEOUT_MS); + timer = setTimeout(() => reject(new ProofTimeoutError()), PROOF_TIMEOUT_MS); }), ]); } catch (err) { @@ -404,7 +405,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto throw createApiError('Rejected', approvalOptions.approveFees ? `${OPERATOR_REJECTED_MESSAGE}: this fee wallet (--approve-fees) approves without the operator only paying the ` + 'Dust fee for an agent\'s own transaction and submitting a transaction it balanced that way on the same connection' - : OPERATOR_REJECTED_MESSAGE); + : OPERATOR_REJECTED_MESSAGE, 'TX_REJECTED'); } } @@ -760,13 +761,13 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return createApiError('InternalError', `The wallet has no Dust available that covers this transaction's fee (${extractErrorDetail(err)}), and no balanced ` + 'transaction is holding any back on this server. Dust builds up with time from the NIGHT registered for it: ' - + 'retry later, or register more NIGHT for Dust generation.'); + + 'retry later, or register more NIGHT for Dust generation.', 'DUST_REQUIRED'); } return createApiError('InternalError', `No Dust is free to pay the fee (${extractErrorDetail(err)}). Each balanced transaction reserves a whole Dust coin ` + `until it is submitted and on chain, or released when its connection closes or it expires; ${pending} ` + 'balanced transaction(s) are waiting to be submitted on this server. Retry once they settle. To pay for more ' - + 'transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.'); + + 'transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.', 'DUST_REQUIRED'); } /** The fee takes more Dust than the wallet's NIGHT generates in the time a request waits (`waitMs` null: within a day). */ @@ -775,7 +776,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto ? "Its registered NIGHT won't generate that within a day: register more NIGHT for Dust generation." : `Its registered NIGHT generates the rest in ${formatWait(waitMs)}: retry then, or register more NIGHT to get there sooner.`; return createApiError('InternalError', - `Not enough Dust available for this transaction's fee: the wallet has ${roughDust(have)} DUST and the fee takes ${roughDust(needed, true)}. ${when}`); + `Not enough Dust available for this transaction's fee: the wallet has ${roughDust(have)} DUST and the fee takes ${roughDust(needed, true)}. ${when}`, 'DUST_REQUIRED'); } /** @@ -1124,5 +1125,6 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return false; } - return { handlers, revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; + // Each handler answers with its failure marked by mn's code, its message and causes as they were. + return { handlers: markingEngineCodes(handlers), revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; } diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts index e5b9d941..ab23a73d 100644 --- a/packages/engine-beta/src/facade.ts +++ b/packages/engine-beta/src/facade.ts @@ -31,7 +31,7 @@ import { import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; import { isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; -import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust @@ -433,7 +433,7 @@ export async function startAndSyncFacade( } } catch { /* best-effort */ } } - reject(new Error('Wallet sync timed out')); + reject(new SyncTimeoutError('Wallet sync timed out')); } }, effectiveTimeout); diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index f678e2ba..d7196d92 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -2,7 +2,7 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk-address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk-facade'; import * as rx from 'rxjs'; @@ -95,7 +95,7 @@ async function submitDustRegistration( await Promise.race([ bundle.facade.dust.waitForSyncedState(), new Promise((_, reject) => setTimeout(() => - reject(new Error('Insufficient funds: dust wallet sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), + reject(new SyncTimeoutError('Insufficient funds: dust wallet sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), ]); // The registration pays its own fee from the dust these coins generate, so @@ -227,7 +227,7 @@ export async function ensureDust( // No NIGHT at all, not even in flight: there is nothing to register and no Dust will be generated. if (state.unshielded.availableCoins.length === 0 && (state.unshielded.pendingCoins?.length ?? 0) === 0) { - throw new Error( + throw new DustRequiredError( 'This wallet has no NIGHT, so it generates no Dust to pay fees. Fund it first ' + '(on undeployed: midnight airdrop ), then run: midnight dust register', ); @@ -259,7 +259,7 @@ export async function ensureDust( const pollState = await Promise.race([ bundle.facade.waitForSyncedState(), new Promise((_, reject) => setTimeout(() => - reject(new Error('Poll sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), + reject(new SyncTimeoutError('Poll sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), ]); if (pollState.dust.balance(new Date()) > 0n) { onStatus?.('Dust available'); @@ -270,7 +270,7 @@ export async function ensureDust( } await new Promise(resolve => setTimeout(resolve, 5_000)); } - throw new Error( + throw new SyncTimeoutError( 'Timed out waiting for dust tokens. ' + 'Try running: midnight dust register' ); @@ -338,7 +338,7 @@ async function buildAndSubmitTransfer( const finalizedTx = await Promise.race([ bundle.facade.finalizeRecipe(signedRecipe), new Promise((_, reject) => { - setTimeout(() => reject(new Error('ZK proof generation timed out')), PROOF_TIMEOUT_MS); + setTimeout(() => reject(new ProofTimeoutError()), PROOF_TIMEOUT_MS); }), ]); @@ -460,7 +460,7 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf log?.('transfer', `Balance: ${Number(unshieldedBalance) / TOKEN_MULTIPLIER} NIGHT, coins: ${availableCoinCount}`); if (unshieldedBalance < amount) { const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER; - throw new Error( + throw new InsufficientBalanceError( `Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + `${amountNight} NIGHT requested` ); diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index 26c77c5e..8a282161 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -17,6 +17,7 @@ import type { ShieldedTransferParams, } from '@kuiralabs/midnight-cli-core/lib/engine'; import { InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { reportingEngineErrors } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; @@ -307,9 +308,13 @@ function serveWallet(repo: WalletDataRepository, options: Parameters({ unshieldedBalance: (address, networkConfig, options) => repo.unshielded(address, networkConfig, options), async dustBalance(seed, networkConfig, options) { const { state: _state, ...balance } = await repo.dust(seed, networkConfig, options); @@ -324,5 +329,5 @@ export function createBetaWallet(repo: WalletDataRepository): EngineWallet { prepDust, openConnector: (options) => openConnector(repo, options), serveWallet: (options, serve) => serveWallet(repo, options, serve), - }; + }); } diff --git a/packages/engine-rc/src/airdrop.ts b/packages/engine-rc/src/airdrop.ts index bbf732cd..d153734e 100644 --- a/packages/engine-rc/src/airdrop.ts +++ b/packages/engine-rc/src/airdrop.ts @@ -3,6 +3,8 @@ // caller has already checked that the network is the local one. import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { EngineError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { WalletDataRepository } from './wallet-data-repository.ts'; @@ -15,11 +17,12 @@ export async function airdropNight(repo: WalletDataRepository, params: AirdropPa return await executeTransfer(repo, { ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); } catch (err) { if (err instanceof Error && err.message.toLowerCase().includes('dust')) { - throw new Error( - `${err.message}\n\n` + + const message = `${err.message}\n\n` + `On a fresh localnet, the minimum airdrop is ~1 NIGHT.\n` + - `Try: midnight airdrop 1` - ); + `Try: midnight airdrop 1`; + // The note keeps the failure's code: the one it carries, or the engine contract's for the SDK's error. + const code = (toEngineError(err) as { code?: unknown }).code; + throw typeof code === 'string' ? new EngineError(code, message, { cause: err }) : new Error(message, { cause: err }); } throw err; } diff --git a/packages/engine-rc/src/dapp-connector.ts b/packages/engine-rc/src/dapp-connector.ts index 801a277a..93047ec0 100644 --- a/packages/engine-rc/src/dapp-connector.ts +++ b/packages/engine-rc/src/dapp-connector.ts @@ -16,7 +16,8 @@ import { createApiError, type RpcHandler, type RpcHandlerContext } from '@kuiral import { createPhaseTracker, type PhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import { isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { isDustShortage, markingEngineCodes } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { ProofTimeoutError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; import { readOffer, spentNullifiers } from './offer-reader.ts'; @@ -339,7 +340,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto finalized = await Promise.race([ finalizing, new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error('ZK proof generation timed out')), PROOF_TIMEOUT_MS); + timer = setTimeout(() => reject(new ProofTimeoutError()), PROOF_TIMEOUT_MS); }), ]); } catch (err) { @@ -402,7 +403,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto throw createApiError('Rejected', approvalOptions.approveFees ? `${OPERATOR_REJECTED_MESSAGE}: this fee wallet (--approve-fees) approves without the operator only paying the ` + 'Dust fee for an agent\'s own transaction and submitting a transaction it balanced that way on the same connection' - : OPERATOR_REJECTED_MESSAGE); + : OPERATOR_REJECTED_MESSAGE, 'TX_REJECTED'); } } @@ -758,13 +759,13 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return createApiError('InternalError', `The wallet has no Dust available that covers this transaction's fee (${extractErrorDetail(err)}), and no balanced ` + 'transaction is holding any back on this server. Dust builds up with time from the NIGHT registered for it: ' - + 'retry later, or register more NIGHT for Dust generation.'); + + 'retry later, or register more NIGHT for Dust generation.', 'DUST_REQUIRED'); } return createApiError('InternalError', `No Dust is free to pay the fee (${extractErrorDetail(err)}). Each balanced transaction reserves a whole Dust coin ` + `until it is submitted and on chain, or released when its connection closes or it expires; ${pending} ` + 'balanced transaction(s) are waiting to be submitted on this server. Retry once they settle. To pay for more ' - + 'transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.'); + + 'transactions at once, the wallet needs more Dust coins: one per NIGHT UTXO registered for Dust generation.', 'DUST_REQUIRED'); } /** The fee takes more Dust than the wallet's NIGHT generates in the time a request waits (`waitMs` null: within a day). */ @@ -773,7 +774,7 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto ? "Its registered NIGHT won't generate that within a day: register more NIGHT for Dust generation." : `Its registered NIGHT generates the rest in ${formatWait(waitMs)}: retry then, or register more NIGHT to get there sooner.`; return createApiError('InternalError', - `Not enough Dust available for this transaction's fee: the wallet has ${roughDust(have)} DUST and the fee takes ${roughDust(needed, true)}. ${when}`); + `Not enough Dust available for this transaction's fee: the wallet has ${roughDust(have)} DUST and the fee takes ${roughDust(needed, true)}. ${when}`, 'DUST_REQUIRED'); } /** @@ -1122,5 +1123,6 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return false; } - return { handlers, revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; + // Each handler answers with its failure marked by mn's code, its message and causes as they were. + return { handlers: markingEngineCodes(handlers), revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; } diff --git a/packages/engine-rc/src/facade.ts b/packages/engine-rc/src/facade.ts index 5f01127c..68b2d9cd 100644 --- a/packages/engine-rc/src/facade.ts +++ b/packages/engine-rc/src/facade.ts @@ -33,7 +33,7 @@ import { import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; import { isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; -import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust @@ -464,7 +464,7 @@ export async function startAndSyncFacade( } } catch { /* best-effort */ } } - reject(new Error('Wallet sync timed out')); + reject(new SyncTimeoutError('Wallet sync timed out')); } }, effectiveTimeout); diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index f4d75d65..abe10525 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -2,7 +2,7 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; import * as rx from 'rxjs'; @@ -95,7 +95,7 @@ async function submitDustRegistration( await Promise.race([ bundle.facade.dust.waitForSyncedState(), new Promise((_, reject) => setTimeout(() => - reject(new Error('Insufficient funds: dust wallet sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), + reject(new SyncTimeoutError('Insufficient funds: dust wallet sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), ]); // The registration pays its own fee from the dust these coins generate, so @@ -227,7 +227,7 @@ export async function ensureDust( // No NIGHT at all, not even in flight: there is nothing to register and no Dust will be generated. if (state.unshielded.availableCoins.length === 0 && (state.unshielded.pendingCoins?.length ?? 0) === 0) { - throw new Error( + throw new DustRequiredError( 'This wallet has no NIGHT, so it generates no Dust to pay fees. Fund it first ' + '(on undeployed: midnight airdrop ), then run: midnight dust register', ); @@ -259,7 +259,7 @@ export async function ensureDust( const pollState = await Promise.race([ bundle.facade.waitForSyncedState(), new Promise((_, reject) => setTimeout(() => - reject(new Error('Poll sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), + reject(new SyncTimeoutError('Poll sync timed out')), SYNC_ATTEMPT_TIMEOUT_MS)), ]); if (pollState.dust.balance(new Date()) > 0n) { onStatus?.('Dust available'); @@ -270,7 +270,7 @@ export async function ensureDust( } await new Promise(resolve => setTimeout(resolve, 5_000)); } - throw new Error( + throw new SyncTimeoutError( 'Timed out waiting for dust tokens. ' + 'Try running: midnight dust register' ); @@ -337,7 +337,7 @@ async function buildAndSubmitTransfer( const finalizedTx = await Promise.race([ bundle.facade.finalizeRecipe(signedRecipe), new Promise((_, reject) => { - setTimeout(() => reject(new Error('ZK proof generation timed out')), PROOF_TIMEOUT_MS); + setTimeout(() => reject(new ProofTimeoutError()), PROOF_TIMEOUT_MS); }), ]); @@ -459,7 +459,7 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf log?.('transfer', `Balance: ${Number(unshieldedBalance) / TOKEN_MULTIPLIER} NIGHT, coins: ${availableCoinCount}`); if (unshieldedBalance < amount) { const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER; - throw new Error( + throw new InsufficientBalanceError( `Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + `${amountNight} NIGHT requested` ); diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index 4fcaea07..008da50e 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -17,6 +17,7 @@ import type { ShieldedTransferParams, } from '@kuiralabs/midnight-cli-core/lib/engine'; import { InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { reportingEngineErrors } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; @@ -306,9 +307,13 @@ function serveWallet(repo: WalletDataRepository, options: Parameters({ unshieldedBalance: (address, networkConfig, options) => repo.unshielded(address, networkConfig, options), async dustBalance(seed, networkConfig, options) { const { state: _state, ...balance } = await repo.dust(seed, networkConfig, options); @@ -323,5 +328,5 @@ export function createRcWallet(repo: WalletDataRepository): EngineWallet { prepDust, openConnector: (options) => openConnector(repo, options), serveWallet: (options, serve) => serveWallet(repo, options, serve), - }; + }); } diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 0ce00280..c19f4752 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -106,6 +106,13 @@ const ENGINE_LOADER = 'lib/installed-engines.ts'; const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; +// The engine contract's reading of the SDK's and the node's errors: an engine +// turns them into typed errors, so only the engines read them, and in core +// only the wallet session (the DApp connector in a program's process) and the +// Dust wait (what a shortage says the wallet is short by). +const SDK_ERRORS = 'lib/sdk-errors.ts'; +const SDK_ERROR_READERS = /^lib\/(sdk-errors|wallet-session|dust-wait)\.ts$/; + // import ... from 'x', export ... from 'x', import 'x', import('x'). const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; @@ -186,6 +193,7 @@ export function importRule(fromRel, toRel) { return fromRel === ENGINE_LOADER ? undefined : `${home} → engine (reach it through ${ENGINE_LOADER})`; } if (!MAY_IMPORT[home].includes(targetHome)) return `${home} → ${targetHome}`; + if (toRel === SDK_ERRORS && home !== 'engine' && !SDK_ERROR_READERS.test(fromRel)) return `${home} → the SDK's errors (only an engine reads them)`; return undefined; } diff --git a/src/__tests__/contract-script-errors.test.ts b/src/__tests__/contract-script-errors.test.ts index 1c73af76..df58a8ed 100644 --- a/src/__tests__/contract-script-errors.test.ts +++ b/src/__tests__/contract-script-errors.test.ts @@ -8,7 +8,14 @@ import { spawnSync } from 'node:child_process'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { SCRIPT_PRELUDE, scriptFailureMessage } from '../lib/contract/runner.ts'; +import { Effect } from 'effect'; +import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; +import { ContractScriptError, SCRIPT_PRELUDE, scriptFailureMessage, scriptFailureOf } from '../lib/contract/runner.ts'; +import { createApiError } from '../lib/ws-rpc.ts'; +import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; +import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { withEngineCode } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { installedCommands } from '../lib/installed-commands.ts'; function runScript(body: string): { stderr: string; status: number | null } { const dir = mkdtempSync(join(tmpdir(), 'mn-script-')); @@ -49,4 +56,41 @@ await Promise.reject(new TypeError('Expected an input string with byte length of expect(scriptFailureMessage('', 2)).toBe('Script exited with code 2'); }); + it('reports the code its failure carries beside the message', () => { + const { stderr, status } = runScript(`throw Object.assign(new Error('Dust not available'), { code: 'DUST_REQUIRED' });`); + expect(scriptFailureOf(stderr, status)).toStrictEqual({ message: 'Dust not available', code: 'DUST_REQUIRED' }); + expect(scriptFailureOf(runScript(`throw new Error('no code');`).stderr, 1)).toStrictEqual({ message: 'no code' }); + }); + + it("reads an older mn's script, which reported its message alone", () => { + expect(scriptFailureOf('__MN_ERROR__ "the message"\n', 1)).toStrictEqual({ message: 'the message' }); + }); +}); + +// The whole way a failure at mn serve takes, run for real: helpers/serve-script-failure.ts. +describe("a failure at mn serve, across the wire and the script's process", () => { + const failedRun = scriptFailureAtServe; + + it("carries the connector's Dust refusal as DUST_REQUIRED, in the connector's words", async () => { + const message = "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00."; + const err = await failedRun(() => createApiError('InternalError', message, 'DUST_REQUIRED')); + expect(err).toBeInstanceOf(ContractScriptError); + expect(err.message).toBe(message); + expect(classifyByCode(err, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + }); + + it("carries a node's refusal by its reason (approved Y54: one with no rule's words was UNKNOWN)", async () => { + const refused = async (reason: string) => { + const sdkFailure = Effect.runPromise(Effect.fail(new SubmissionError({ message: 'Transaction submission error', cause: new Error(reason) }))); + const thrown = await sdkFailure.catch((e: Error) => e); + // As the connector answers: its own words over the SDK's error, marked with mn's code. + return failedRun(() => withEngineCode(new Error(`Transaction submission failed: [SubmissionError] Transaction submission error → ${reason}`, { cause: thrown }))); + }; + const other = await refused('1010: Invalid Transaction: Custom error: 199'); + expect(other.message).toBe('Transaction submission failed: [SubmissionError] Transaction submission error → 1010: Invalid Transaction: Custom error: 199'); + expect(classifyError(other)).toStrictEqual({ errorCode: 'UNKNOWN', exitCode: 1 }); + expect(classifyByCode(other, installedCommands)).toStrictEqual({ errorCode: 'TX_REJECTED', exitCode: 6 }); + expect(classifyByCode(await refused('1010: Invalid Transaction: Custom error: 115'), installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + expect(classifyByCode(await refused('1010: Invalid Transaction: Custom error: 170'), installedCommands)).toStrictEqual({ errorCode: 'INVALID_DUST_PROOF', exitCode: 6 }); + }); }); diff --git a/src/__tests__/engine-beta-boundary-errors.test.ts b/src/__tests__/engine-beta-boundary-errors.test.ts new file mode 100644 index 00000000..83b7798a --- /dev/null +++ b/src/__tests__/engine-beta-boundary-errors.test.ts @@ -0,0 +1,27 @@ +// The beta engine's failures as it reports them: helpers/engine-boundary-suite.ts, +// with the SDK's error classes from the beta engine's own copies, as its code +// resolves them; the repository's root holds the rc set's. + +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { engineBoundarySuite } from './helpers/engine-boundary-suite.ts'; + +const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +/** A module of a package as the beta engine resolves it. */ +const fromEngine = async (name: string, entry: string) => import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, name)!, entry)).href); + +const { SubmissionError } = await fromEngine('@midnightntwrk/wallet-sdk-capabilities', 'dist/submission/index.js'); +const { ProvingError } = await fromEngine('@midnightntwrk/wallet-sdk-capabilities', 'dist/proving/index.js'); +const { InsufficientFundsError: NoCoinsCoverIt } = await fromEngine('@midnightntwrk/wallet-sdk-capabilities', 'dist/index.js'); +const { WalletError } = await fromEngine('@midnightntwrk/wallet-sdk-dust-wallet', 'dist/v1/index.js'); + +engineBoundarySuite({ + set: 'beta', + createEngine: createBetaEngine, + SubmissionError, + ProvingError, + InsufficientFundsError: WalletError.InsufficientFundsError, + couldNotBalance: (tokenType) => new NoCoinsCoverIt(tokenType).message, +}); diff --git a/src/__tests__/engine-boundary-errors.test.ts b/src/__tests__/engine-boundary-errors.test.ts new file mode 100644 index 00000000..e7c739ef --- /dev/null +++ b/src/__tests__/engine-boundary-errors.test.ts @@ -0,0 +1,18 @@ +// The rc engine's failures as it reports them: helpers/engine-boundary-suite.ts, +// with the rc SDK's own error classes. + +import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; +import { ProvingError } from '@midnightntwrk/wallet-sdk/capabilities/proving'; +import { InsufficientFundsError as NoCoinsCoverIt } from '@midnightntwrk/wallet-sdk/capabilities'; +import { WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { engineBoundarySuite } from './helpers/engine-boundary-suite.ts'; + +engineBoundarySuite({ + set: 'rc', + createEngine: createRcEngine, + SubmissionError, + ProvingError, + InsufficientFundsError: WalletError.InsufficientFundsError, + couldNotBalance: (tokenType) => new NoCoinsCoverIt(tokenType).message, +}); diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index 2e2d80c9..036263c5 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -6,7 +6,9 @@ // NO_NODE_RUNTIME by name instead of UNKNOWN, an escaped stale cache as // STALE_CACHE, and a failed command run through MCP as COMMAND_FAILED; and // (Y53) a wallet with no NIGHT as INSUFFICIENT_BALANCE and an unreachable -// indexer as NETWORK_ERROR, whatever their messages say. A third +// indexer as NETWORK_ERROR, whatever their messages say; and (Y54) a ZK proof +// that timed out as PROOF_TIMEOUT, and a contract run's transaction the node +// refused as TX_REJECTED whatever its reason's words. A third // classification reads the error's code alone, with no message rule: what the // shell and the MCP server report once the rules are gone. @@ -15,7 +17,22 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { createApiError, OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { withEngineCode } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { sessionOver } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; +import { Effect } from 'effect'; +import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; +import { ProvingError } from '@midnightntwrk/wallet-sdk/capabilities/proving'; +import { InsufficientFundsError as NoCoinsCoverIt } from '@midnightntwrk/wallet-sdk/capabilities'; +import { WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; +import { DustAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; +import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; +import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; +import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; +import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; +import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; import { parseArgs, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { dustShortError } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; import { ProgramTimedOutError } from '@kuiralabs/midnight-cli-core/lib/exec-program'; @@ -52,6 +69,7 @@ import { StaleCacheError } from '@kuiralabs/midnight-engine-rc/facade'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; import * as ledger from '@midnightntwrk/ledger-v9'; +import * as rx from 'rxjs'; import { readPassphrase } from '../lib/passphrase.ts'; import { assertWalletFileExists, assertWalletRemovable, setActiveWallet } from '../lib/wallet-config.ts'; import { walletSecretFrom } from '../lib/wallet-create.ts'; @@ -112,6 +130,36 @@ const holding = (night: bigint) => createHost({ }), }); +/** The SDK's promise rejection for a failed Effect: a FiberFailure holding the error. */ +function sdkRejection(error: Error): Promise { + const failure = Effect.runPromise(Effect.fail(error)); + failure.catch(() => {}); + return failure as Promise; +} +const nodeRefusal = (reason: string) => () => sdkRejection(new SubmissionError({ message: 'Transaction submission error', cause: new Error(reason) })); +/** The rc engine's wallet reading a balance when the SDK fails with `failure` under it, at its repository's indexer seam. */ +const throughRcEngine = (failure: () => Promise) => () => createRcEngine(createHost({ paths: { stateRoot: root, home: root } }), { + repository: { fetchUnshielded: failure, fetchTip: async () => 'tip-1' }, +}).wallet.unshieldedBalance(ADDRESSES.undeployed, STAND_IN, { forceFresh: true }); +/** A program's wallet session over the rc engine's connector, its facade stubbed at the SDK boundary, submitting what the node refuses with `reason`. */ +const { createBundleStub, mockState } = connectorStub({ createDAppConnector, deriveShieldedAddress, DustAddress, UnshieldedAddress, ledger9ProtocolVersion: FORK_SCHEDULE.v9 }); +const throughSession = (reason: string) => async () => { + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({})), submitTransaction: nodeRefusal(reason) }); + (bundle.facade as unknown as { revert: () => Promise }).revert = async () => {}; + const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); + const session = sessionOver('undeployed', { connector, stop: async () => { connector.dispose(); } }, () => []); + try { + await session.submit(await session.balanceTransaction(Buffer.from(await unsealedBytes(agentPaysMerchant())).toString('hex'))); + } finally { + await session.close(); + } +}; +/** The connector's answer to a submission the node refused with `reason`: its own words over the SDK's error, marked with mn's code. */ +const connectorRefusal = async (reason: string) => { + const thrown = await nodeRefusal(reason)().catch((e: Error) => e); + return withEngineCode(new Error(`Transaction submission failed: [SubmissionError] Transaction submission error → ${reason}`, { cause: thrown })); +}; + /** What the function throws; fails the test when it throws nothing. */ async function thrownBy(run: () => unknown): Promise { try { @@ -189,6 +237,9 @@ const ROWS: Row[] = [ ['a paying wallet with no NIGHT (approved: was UNKNOWN)', () => assertWalletCanPay({ network: 'undeployed', root, host: holding(0n), networkConfig: STAND_IN, endpoints: {} }, 'alice', silentSpinner()), as('UNKNOWN', 1), as('INSUFFICIENT_BALANCE', 5)], ['a paying wallet with no Dust', () => assertWalletCanPay({ network: 'undeployed', root, host: holding(5_000_000n), networkConfig: STAND_IN, endpoints: {} }, 'alice', silentSpinner()), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], // A test run's Dust step, and an engine's shielded transfer, need a chain: their errors as those sites throw them. + ['the SDK short of Dust, through the engine', throughRcEngine(() => sdkRejection(new WalletError.InsufficientFundsError({ message: new NoCoinsCoverIt('dust').message, tokenType: 'dust' }))), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], + ['the SDK short of NIGHT, through the engine', throughRcEngine(() => sdkRejection(new WalletError.InsufficientFundsError({ message: new NoCoinsCoverIt(NATIVE_TOKEN_TYPE).message, tokenType: NATIVE_TOKEN_TYPE }))), as('INSUFFICIENT_BALANCE', 5), as('INSUFFICIENT_BALANCE', 5)], + ['a contract run short of Dust at mn serve', () => scriptFailureAtServe(() => createApiError('InternalError', "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00.", 'DUST_REQUIRED')).then((err) => { throw err; }), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], ["a test run's Dust not available", () => { throw new DustRequiredError('Dust not available after 90s. The chain may be slow — try again.'); }, as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], ["a test run's wallet with no NIGHT (approved: was UNKNOWN)", () => { throw new InsufficientBalanceError('Wallet has 0 NIGHT on preprod. Fund your wallet before running tests:\n mn airdrop 100 (if faucet available)\n Or transfer NIGHT from another wallet.'); }, as('UNKNOWN', 1), as('INSUFFICIENT_BALANCE', 5)], // A failed prep step reports its step's code. @@ -197,8 +248,22 @@ const ROWS: Row[] = [ ["the genesis wallet's shielded NIGHT short of an airdrop", () => { throw new InsufficientBalanceError('Genesis wallet has insufficient shielded balance: 1.000000 NIGHT available, 2 NIGHT requested'); }, as('INSUFFICIENT_BALANCE', 5), as('INSUFFICIENT_BALANCE', 5)], // Refused transactions and stale state: exit 6. - // It carries no code yet: its name and the node's words in its message classify it. - ["the node's refusal", () => { throw new TransactionRefusedError('Invalid transaction'); }, as('TX_REJECTED', 6), as('TX_REJECTED', 6), as('UNKNOWN', 1)], + ["the node's refusal", () => { throw new TransactionRefusedError('Invalid transaction'); }, as('TX_REJECTED', 6), as('TX_REJECTED', 6)], + // The engine's boundary: the SDK's own errors, reported by the rc engine's wallet. + ['the node refusing a spent coin, through the engine', throughRcEngine(nodeRefusal('1010: Invalid Transaction: Custom error: 115')), as('STALE_UTXO', 6), as('STALE_UTXO', 6)], + ['the node refusing a Dust proof, through the engine', throughRcEngine(nodeRefusal('1010: Invalid Transaction: Custom error: 170')), as('INVALID_DUST_PROOF', 6), as('INVALID_DUST_PROOF', 6)], + ['the node refusing for another reason, through the engine', throughRcEngine(nodeRefusal('1010: Invalid Transaction: Custom error: 199')), as('TX_REJECTED', 6), as('TX_REJECTED', 6)], + ['the proof server failing, through the engine', throughRcEngine(() => sdkRejection(new ProvingError({ message: 'Failed to prove transaction', cause: new Error('connect ECONNREFUSED 127.0.0.1:6300') }))), as('PROOF_FAILURE', 6), as('PROOF_FAILURE', 6)], + ["a saved state the indexer's events don't fit, through the engine", throughRcEngine(() => Promise.reject(new Error('Failed applying dust events: commitment inserted non-linearly'))), as('STALE_CACHE', 6), as('STALE_CACHE', 6)], + ['a wallet sync past its deadline, in the engine', () => { throw new SyncTimeoutError('Wallet sync timed out'); }, as('SYNC_TIMEOUT', 4), as('SYNC_TIMEOUT', 4)], + ['a ZK proof that timed out, in the engine (approved Y54: was UNKNOWN)', () => { throw new ProofTimeoutError(); }, as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], + // A program's wallet session: the connector in this process, reporting as the engine does. + ["the node refusing a spent coin, through a program's wallet session", throughSession('1010: Invalid Transaction: Custom error: 115'), as('STALE_UTXO', 6), as('STALE_UTXO', 6)], + // A contract run: the connector at mn serve, the wire, and the script's process. + ['a contract run the node refused at mn serve (approved Y54: was UNKNOWN)', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 199'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('UNKNOWN', 1), as('TX_REJECTED', 6)], + ['a contract run refused a spent coin at mn serve', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 115'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('STALE_UTXO', 6), as('STALE_UTXO', 6)], + ['a contract run whose proof timed out at mn serve (approved Y54: was UNKNOWN)', () => scriptFailureAtServe(() => new ProofTimeoutError()).then((err) => { throw err; }), as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], + ['a contract run the operator refused at mn serve', () => scriptFailureAtServe(() => createApiError('Rejected', OPERATOR_REJECTED_MESSAGE, 'TX_REJECTED')).then((err) => { throw err; }), as('TX_REJECTED', 6), as('TX_REJECTED', 6)], ['a stale cache that escapes (approved: was UNKNOWN)', () => { throw new StaleCacheError('applied 120 of 80 events'); }, as('UNKNOWN', 1), as('STALE_CACHE', 6)], // Cancelled: exit 7. diff --git a/src/__tests__/helpers/connector-suite.ts b/src/__tests__/helpers/connector-suite.ts index 32ae2f71..3efd56fe 100644 --- a/src/__tests__/helpers/connector-suite.ts +++ b/src/__tests__/helpers/connector-suite.ts @@ -517,7 +517,7 @@ export function connectorSuite(engine: ConnectorEngine): void { await expect(connector.handlers.signData({ data: 'deadbeef', options: { encoding: 'hex', keyType: 'unshielded' }, - }, ctx())).rejects.toThrow('User rejected the request'); + }, ctx())).rejects.toMatchObject({ code: 'Rejected', message: 'User rejected the request', mnCode: 'TX_REJECTED' }); } finally { Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); } @@ -853,6 +853,24 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toContain('Transaction submission error'); expect(err.message).toContain('1010: Invalid Transaction: Custom error: 139'); + // Marked with mn's code for any refusal, its message and causes as the dApp reads them. + expect(err.mnCode).toBe('TX_REJECTED'); + expect(err.code).toBeUndefined(); + }); + + it.each([ + ['1010: Invalid Transaction: Custom error: 115', 'STALE_UTXO'], + ['1010: Invalid Transaction: Custom error: 170', 'INVALID_DUST_PROOF'], + ])("marks the node's refusal \"%s\" with mn's code %s", async (reason, mnCode) => { + const sdkFailure = Effect.runPromise(Effect.fail(new engine.SubmissionError({ message: 'Transaction submission error', cause: new Error(reason) }))); + sdkFailure.catch(() => {}); + const bundle = createBundleStub({ submitTransaction: () => sdkFailure }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); + + const err: any = await connector.handlers.submitTransaction({ tx: SEALED_AGENT_TX }, ctx()).catch((e: any) => e); + + expect(err.message).toContain(reason); + expect(err.mnCode).toBe(mnCode); }); it('reports bytes the wallet cannot read as InvalidRequest, naming the stage, without balancing', async () => { @@ -1115,6 +1133,7 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toContain('no balanced transaction is holding any back on this server'); expect(err.message).not.toContain('Retry once they settle'); expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(err.mnCode).toBe('DUST_REQUIRED'); expect(callCount).toBe(10); // DUST_RETRY_ATTEMPTS = 10 vi.useRealTimers(); }); @@ -1165,6 +1184,7 @@ export function connectorSuite(engine: ConnectorEngine): void { "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00. " + 'Its registered NIGHT generates the rest in about 4 minutes: retry then, or register more NIGHT to get there sooner.'); expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(err.mnCode).toBe('DUST_REQUIRED'); }); it('waits longer when the caller allows it', async () => { @@ -1408,6 +1428,7 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toContain('No Dust is free to pay the fee ([Wallet.InsufficientFunds] Insufficient Funds: could not balance dust)'); expect(err.message).toContain('1 balanced transaction(s) are waiting to be submitted on this server. Retry once they settle.'); expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(err.mnCode).toBe('DUST_REQUIRED'); } finally { process.stderr.write = stderrWrite; vi.useRealTimers(); @@ -1527,6 +1548,7 @@ export function connectorSuite(engine: ConnectorEngine): void { // The agent learns why, not just that it was refused. expect(err.message).toBe('User rejected the request: this fee wallet (--approve-fees) approves without the operator only ' + "paying the Dust fee for an agent's own transaction and submitting a transaction it balanced that way on the same connection"); + expect(err.mnCode).toBe('TX_REJECTED'); expect(submit).not.toHaveBeenCalled(); }); @@ -1990,7 +2012,8 @@ export function connectorSuite(engine: ConnectorEngine): void { connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); const call = connector.handlers.balanceUnsealedTransaction({ tx: AGENT_TX }, ctx()); - const outcome = expect(call).rejects.toThrow('ZK proof generation timed out'); + // A ProofTimeoutError, which mn reports as PROOF_TIMEOUT and the wire carries as its mn code. + const outcome = expect(call).rejects.toMatchObject({ message: 'ZK proof generation timed out', code: 'PROOF_TIMEOUT' }); await vi.advanceTimersByTimeAsync(PROOF_TIMEOUT_MS + 1); await outcome; expect(revertFn).toHaveBeenCalledWith(recipe); diff --git a/src/__tests__/helpers/engine-boundary-suite.ts b/src/__tests__/helpers/engine-boundary-suite.ts new file mode 100644 index 00000000..b8c1f3d0 --- /dev/null +++ b/src/__tests__/helpers/engine-boundary-suite.ts @@ -0,0 +1,102 @@ +// What an engine hands the rest of mn when the SDK or the node fails: the +// engine contract's typed error, carrying its code, with the SDK's message (a +// node's refusal in the node's words) and the SDK's error as its cause. The +// SDK's errors are its own classes, from the engine's own copy of the SDK, +// failing an Effect as the SDK's promises do (they reject with a FiberFailure); +// they come in where the engine reads the indexer, the seam its repository +// takes for a test standing in for the network. +// +// This file loads no engine: each test file that runs it passes one. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +// The wallet SDK's copy of Effect (both engines' SDKs share it). +import { Effect } from 'effect'; +import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { classifyByCode } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { DustRequiredError, InsufficientBalanceError, ProofFailureError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { installedCommands } from '../../lib/installed-commands.ts'; + +/** What the suite takes from an engine: how to make it with its repository's seams, and the SDK's error classes from its own copy. */ +export interface BoundaryEngine { + set: string; + createEngine(host: EngineHost, options: { repository: { fetchUnshielded: () => Promise; fetchTip: () => Promise } }): Engine; + SubmissionError: new (args: { message: string; cause?: unknown }) => Error; + ProvingError: new (args: { message: string; cause: Error }) => Error; + InsufficientFundsError: new (args: { message: string; tokenType: string }) => Error; + /** The SDK's message for a balance it could not make of a token, as its balancer words it. */ + couldNotBalance(tokenType: string): string; +} + +const NETWORK: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', node: 'ws://test/node', proofServer: 'http://test/proof', networkId: 'Undeployed' }; +const ADDRESS = 'mn_addr_undeployed1boundary'; +const NIGHT = '0'.repeat(64); + +/** The SDK's promise rejection for a failed Effect: a FiberFailure holding the error. */ +function sdkRejection(error: Error): Promise { + const failure = Effect.runPromise(Effect.fail(error)); + failure.catch(() => {}); + return failure as Promise; +} + +export function engineBoundarySuite(engine: BoundaryEngine): void { + describe(`the ${engine.set} engine's failures, as it reports them`, () => { + let root: string; + beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'mn-engine-boundary-')); }); + afterAll(() => { rmSync(root, { recursive: true, force: true }); }); + + /** What the engine's wallet rejects with when the SDK fails with `failure` under it. */ + async function reported(failure: () => Promise): Promise { + const host = createHost({ paths: { stateRoot: root, home: root } }); + const made = engine.createEngine(host, { repository: { fetchUnshielded: failure, fetchTip: async () => 'tip-1' } }); + return made.wallet.unshieldedBalance(ADDRESS, NETWORK, { forceFresh: true }).then( + () => { throw new Error('expected the engine to fail'); }, + (err: Error) => err, + ); + } + const refusal = (reason: string) => () => sdkRejection(new engine.SubmissionError({ message: 'Transaction submission error', cause: new Error(reason) })); + + it.each([ + ['1010: Invalid Transaction: Custom error: 115', 'STALE_UTXO'], + ['1010: Invalid Transaction: Custom error: 170', 'INVALID_DUST_PROOF'], + ['1010: Invalid Transaction: Custom error: 199', 'TX_REJECTED'], + ])("reports the node's refusal \"%s\" in the node's words, as %s", async (reason, code) => { + const err = await reported(refusal(reason)); + expect(err).toBeInstanceOf(TransactionRefusedError); + expect(err.message).toBe(`The node refused the transaction: ${reason}`); + expect((err as TransactionRefusedError).code).toBe(code); + expect(classifyByCode(err, installedCommands)).toStrictEqual({ errorCode: code, exitCode: 6 }); + }); + + it("reports the proof server's failure as PROOF_FAILURE, with the SDK's message", async () => { + const err = await reported(() => sdkRejection(new engine.ProvingError({ message: 'Failed to prove transaction', cause: new Error('connect ECONNREFUSED 127.0.0.1:6300') }))); + expect(err).toBeInstanceOf(ProofFailureError); + expect(err.message).toBe('Failed to prove transaction'); + expect(classifyByCode(err, installedCommands)).toStrictEqual({ errorCode: 'PROOF_FAILURE', exitCode: 6 }); + }); + + it("reports the SDK's Dust shortage as DUST_REQUIRED, and its shortage of NIGHT as INSUFFICIENT_BALANCE", async () => { + const dust = await reported(() => sdkRejection(new engine.InsufficientFundsError({ message: engine.couldNotBalance('dust'), tokenType: 'dust' }))); + expect(dust).toBeInstanceOf(DustRequiredError); + expect(dust.message).toBe(engine.couldNotBalance('dust')); + expect(classifyByCode(dust, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + + const night = await reported(() => sdkRejection(new engine.InsufficientFundsError({ message: engine.couldNotBalance(NIGHT), tokenType: NIGHT }))); + expect(night).toBeInstanceOf(InsufficientBalanceError); + expect(night.message).toBe(engine.couldNotBalance(NIGHT)); + expect(classifyByCode(night, installedCommands)).toStrictEqual({ errorCode: 'INSUFFICIENT_BALANCE', exitCode: 5 }); + }); + + it('keeps the SDK\'s error as the cause, and leaves a failure it does not name as it was', async () => { + const failure = new engine.SubmissionError({ message: 'Transaction submission error', cause: new Error('1010: Invalid Transaction: Custom error: 115') }); + const err = await reported(() => sdkRejection(failure)); + expect(err.cause).toBeInstanceOf(Error); + const unnamed = new Error('Something the SDK says that mn has no code for'); + expect(await reported(() => Promise.reject(unnamed))).toBe(unnamed); + }); + }); +} diff --git a/src/__tests__/helpers/serve-script-failure.ts b/src/__tests__/helpers/serve-script-failure.ts new file mode 100644 index 00000000..d9529bab --- /dev/null +++ b/src/__tests__/helpers/serve-script-failure.ts @@ -0,0 +1,36 @@ +// A failure at mn serve as a contract run reports it, the whole way for real: +// the error a handler answers with, the wire (mn's code as data.mnCode), the +// generated script's RPC client and its marked failure line in a child Node, +// and the error the runner rebuilds from that line. + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import type { AddressInfo } from 'node:net'; +import { SCRIPT_PRELUDE, executeScript, rpcClientCode } from '../../lib/contract/runner.ts'; +import { createRpcServer } from '../../lib/ws-rpc.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + +/** What the runner rejects with when a script's call to mn serve fails with what `failure` throws. */ +export async function scriptFailureAtServe(failure: () => unknown): Promise { + const server = createRpcServer({ host: createHost(), port: 0, refuseBrowsers: true, handlers: { balanceUnsealedTransaction: async () => { throw failure(); } } }); + const dir = mkdtempSync(join(tmpdir(), 'mn-script-wire-')); + try { + await server.ready; + const { port } = server.wss.address() as AddressInfo; + const wsModule = pathToFileURL(createRequire(import.meta.url).resolve('ws')).href; + const script = SCRIPT_PRELUDE + rpcClientCode(port, wsModule) + ` +await rpcConnect(); +await rpcCall('balanceUnsealedTransaction', { tx: 'ab' }); +`; + return await executeScript({ dir, script, overlaySdk: false, packages: { packages: [], packageFolder: () => null, set: 'rc' } }).then( + () => { throw new Error('expected the script to fail'); }, + (err: Error) => err, + ); + } finally { + await server.close(); + rmSync(dir, { recursive: true, force: true }); + } +} diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index f3a23f32..8e82c587 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -47,6 +47,16 @@ describe('the layering', () => { expect(importRule('engine/rc/index.ts', 'lib/facade.ts')).toBe('engine → wallet'); }); + it("lets only an engine, and core's wallet session and Dust wait, read the SDK's errors", () => { + expect(importRule('engine/rc/transfer.ts', 'lib/sdk-errors.ts')).toBeUndefined(); + expect(importRule('engine/beta/dapp-connector.ts', 'lib/sdk-errors.ts')).toBeUndefined(); + expect(importRule('lib/wallet-session.ts', 'lib/sdk-errors.ts')).toBeUndefined(); + expect(importRule('lib/dust-wait.ts', 'lib/sdk-errors.ts')).toBeUndefined(); + expect(importRule('wallet.ts', 'lib/sdk-errors.ts')).toBe("shell → the SDK's errors (only an engine reads them)"); + expect(importRule('lib/ws-rpc.ts', 'lib/sdk-errors.ts')).toBe("connect → the SDK's errors (only an engine reads them)"); + expect(importRule('lib/exit-codes.ts', 'lib/sdk-errors.ts')).toBe("core → the SDK's errors (only an engine reads them)"); + }); + it('lets only an engine import the SDK', () => { // findLayeringProblems above finds none elsewhere; core, chain and every package are held to it alike. expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); diff --git a/src/__tests__/sdk-errors.test.ts b/src/__tests__/sdk-errors.test.ts index 38c2064e..7a8ed581 100644 --- a/src/__tests__/sdk-errors.test.ts +++ b/src/__tests__/sdk-errors.test.ts @@ -6,9 +6,11 @@ import { describe, it, expect } from 'vitest'; import { Brand, Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { NodeClientError } from '@midnightntwrk/wallet-sdk/node-client/effect'; -import { dustShortfallOf, isColdStartRace, isDustShortage, nodeRefusalOf, withDustShortfall, withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { dustShortfallOf, isColdStartRace, isDustShortage, mnCodeOf, nodeRefusalOf, refusalCodeOf, toEngineError, withDustShortfall, withEngineCode, withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { DustRequiredError, InsufficientBalanceError, ProofTimeoutError, StaleWalletStateError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { createApiError } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +import { installedCommands } from '../lib/installed-commands.ts'; /** wallet-sdk 2.0's dust InsufficientFundsError: tagged, with the token it could not balance. */ function sdkInsufficientFunds(tokenType: string): Error { @@ -166,6 +168,7 @@ describe("the node's reason for refusing a transaction", () => { expect(reported.message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 170'); expect(reported.cause).toBe(thrown); expect(classifyError(reported)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); + expect(classifyByCode(reported, installedCommands)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); // Unexplained, the same error was UNKNOWN. expect(classifyError(thrown).errorCode).toBe('UNKNOWN'); }); @@ -191,3 +194,63 @@ describe("the node's reason for refusing a transaction", () => { expect(withNodeReason(bare)).toBe(bare); }); }); + +describe("the engine contract's reading of a failure", () => { + const FIBER_FAILURE_CAUSE = Symbol.for('effect/Runtime/FiberFailure/Cause'); + const fiberFailure = (error: object, message: string) => Object.assign(new Error(message), { [FIBER_FAILURE_CAUSE]: { _tag: 'Fail', error } }); + + it("codes a node's refusal by its reason", () => { + expect(refusalCodeOf('1010: Invalid Transaction: Custom error: 115')).toBe('STALE_UTXO'); + expect(refusalCodeOf('1010: Invalid Transaction: Custom error: 170')).toBe('INVALID_DUST_PROOF'); + expect(refusalCodeOf('InvalidDustSpendProof')).toBe('INVALID_DUST_PROOF'); + expect(refusalCodeOf('Transaction is invalid and was rejected by the node')).toBe('TX_REJECTED'); + }); + + it('reports a failure it names as the typed error for its code, with the message and the failure as its cause', () => { + const dust = fiberFailure({ _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' }, 'Insufficient Funds: could not balance dust'); + const reported = toEngineError(dust) as Error; + expect(reported).toBeInstanceOf(DustRequiredError); + expect(reported.message).toBe(dust.message); + expect(reported.cause).toBe(dust); + + const night = fiberFailure({ _tag: 'Wallet.InsufficientFunds', tokenType: '0'.repeat(64) }, 'Insufficient Funds: could not balance 0000'); + expect(toEngineError(night)).toBeInstanceOf(InsufficientBalanceError); + // The ledger's words when a saved state is resumed on an indexer that numbers its events differently. + const resumed = toEngineError(new Error('Failed applying dust events: commitment inserted non-linearly')) as Error; + expect(resumed).toBeInstanceOf(StaleWalletStateError); + expect(classifyByCode(resumed, installedCommands)).toStrictEqual({ errorCode: 'STALE_CACHE', exitCode: 6 }); + }); + + it("leaves an error that carries its own code, a refusal already reported, and one it doesn't name, as they are", () => { + const own = new ProofTimeoutError(); + expect(toEngineError(own)).toBe(own); + const refused = new TransactionRefusedError('Custom error: 115', { code: 'STALE_UTXO' }); + expect(toEngineError(refused)).toBe(refused); + const unnamed = new Error('Something unexpected happened'); + expect(toEngineError(unnamed)).toBe(unnamed); + expect(toEngineError('a string')).toBe('a string'); + }); + + it("reports a connector error marked with mn's code as the typed error for it, in its own words", () => { + const api = createApiError('InternalError', "Not enough Dust available for this transaction's fee", 'DUST_REQUIRED'); + const reported = toEngineError(api) as Error; + expect(reported).toBeInstanceOf(DustRequiredError); + expect(reported.message).toBe(api.message); + expect(reported.cause).toBe(api); + // An API error with no mn code stays the connector's. + const plain = createApiError('InvalidRequest', 'tx is required'); + expect(toEngineError(plain)).toBe(plain); + }); + + it("marks a connector's failure with mn's code, the error itself unchanged for the dApp", () => { + const dust = fiberFailure({ _tag: 'Wallet.InsufficientFunds', tokenType: 'dust' }, 'Insufficient Funds: could not balance dust'); + const marked = withEngineCode(dust) as Error; + expect(marked).toBe(dust); + expect(marked.message).toBe('Insufficient Funds: could not balance dust'); + expect(mnCodeOf(marked)).toBe('DUST_REQUIRED'); + expect(Object.keys(marked)).not.toContain('mnCode'); + const api = createApiError('Rejected', 'User rejected the request', 'TX_REJECTED'); + expect(mnCodeOf(withEngineCode(api))).toBe('TX_REJECTED'); + expect(mnCodeOf(withEngineCode(new Error('Something unexpected happened')))).toBeUndefined(); + }); +}); diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts index 647bc3bd..03f33c95 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/src/__tests__/wallet-session.test.ts @@ -12,6 +12,11 @@ import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from './helpers/conne import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; +import { Effect } from 'effect'; +import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; +import { DustRequiredError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyByCode } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; const { WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, mockState } = connectorStub({ createDAppConnector, deriveShieldedAddress, DustAddress, UnshieldedAddress, ledger9ProtocolVersion: FORK_SCHEDULE.v9, @@ -167,11 +172,11 @@ describe('wallet session', () => { expect(third.stop).toHaveBeenCalledOnce(); }); - it('gives up after five attempts with the SDK\'s refusal', async () => { + it('gives up after five attempts with the SDK\'s refusal, reported as the engine reports it', async () => { const reopen = vi.fn(async () => openedWith(() => Promise.reject(coldStart()))); const session = sessionOver('undeployed', openedWith(() => Promise.reject(coldStart())), () => [], { reopen, delayMs: 0 }); - await expect(session.swap(give, take)).rejects.toMatchObject({ _tag: 'Wallet.InsufficientFunds' }); + await expect(session.swap(give, take)).rejects.toMatchObject({ code: 'INSUFFICIENT_BALANCE', message: 'Insufficient funds', cause: { _tag: 'Wallet.InsufficientFunds' } }); expect(reopen).toHaveBeenCalledTimes(4); await session.close(); }); @@ -182,7 +187,7 @@ describe('wallet session', () => { const session = sessionOver('undeployed', openedWith(initSwap), () => [], { reopen, delayMs: 0 }); await session.swap(give, take); - await expect(session.swap(give, take)).rejects.toMatchObject({ _tag: 'Wallet.InsufficientFunds' }); + await expect(session.swap(give, take)).rejects.toMatchObject({ code: 'INSUFFICIENT_BALANCE', message: 'Insufficient funds', cause: { _tag: 'Wallet.InsufficientFunds' } }); expect(reopen).not.toHaveBeenCalled(); await session.close(); }); @@ -204,4 +209,39 @@ describe('wallet session', () => { } }); }); + + // The connector answers as it answers a dApp; the session, a program's + // wallet in this process, reports as the engine does. + describe('its failures, as the engine reports them', () => { + it("reports the node's refusal in the node's words, coded by its reason", async () => { + const sdkFailure = Effect.runPromise(Effect.fail(new SubmissionError({ message: 'Transaction submission error', cause: new Error('1010: Invalid Transaction: Custom error: 115') }))); + sdkFailure.catch(() => {}); + const { session } = openSession({ bundleOverrides: { submitTransaction: () => sdkFailure } }); + const balanced = await session.balanceTransaction(AGENT_TX); + + const err = await session.submit(balanced).catch((e: Error) => e); + + expect(err).toBeInstanceOf(TransactionRefusedError); + expect((err as Error).message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 115'); + expect(classifyByCode(err as Error, installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + await session.close(); + }); + + it("reports the connector's Dust refusal as DUST_REQUIRED, in the connector's words", async () => { + vi.useFakeTimers(); + try { + const { session } = openSession({ bundleOverrides: { balanceUnboundTransaction: () => Promise.reject(new Error('No dust tokens found in the wallet state')) } }); + const failure = session.balanceTransaction(AGENT_TX).catch((e: Error) => e); + await vi.advanceTimersByTimeAsync(10 * 3_000); + const err = await failure; + + expect(err).toBeInstanceOf(DustRequiredError); + expect((err as Error).message).toContain("The wallet has no Dust available that covers this transaction's fee (No dust tokens found in the wallet state)"); + expect(classifyByCode(err as Error, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + await session.close(); + } finally { + vi.useRealTimers(); + } + }); + }); }); diff --git a/src/__tests__/ws-rpc.test.ts b/src/__tests__/ws-rpc.test.ts index ec7260df..cb506854 100644 --- a/src/__tests__/ws-rpc.test.ts +++ b/src/__tests__/ws-rpc.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import { WebSocket } from 'ws'; import { createRpcServer, createApiError, type RpcServer } from '../lib/ws-rpc.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { DustRequiredError } from '@kuiralabs/midnight-cli-core/lib/errors'; // The host the servers run in: notices dropped. const host = createHost(); @@ -232,6 +233,49 @@ describe('ws-rpc', () => { }); }); + it("carries mn's code for an APIError beside the API's own, as an additive key", async () => { + const port = nextPort(); + server = createRpcServer({ + host, + port, + handlers: { + short: async () => { throw createApiError('InternalError', "Not enough Dust available for this transaction's fee", 'DUST_REQUIRED'); }, + }, + }); + + const ws = await connectClient(port); + clients.push(ws); + + const responsePromise = waitForMessage(ws); + sendRpc(ws, 1, 'short'); + const response = await responsePromise; + + expect(response.error.code).toBe(-32603); + expect(response.error.message).toBe("Not enough Dust available for this transaction's fee"); + expect(response.error.data).toEqual({ type: 'DAppConnectorAPIError', code: 'InternalError', mnCode: 'DUST_REQUIRED' }); + }); + + it("carries the code of mn's typed error as mnCode, beside its causes", async () => { + const port = nextPort(); + server = createRpcServer({ + host, + port, + handlers: { + short: async () => { throw new DustRequiredError('Dust not available', { cause: new Error('the wallet SDK said so') }); }, + }, + }); + + const ws = await connectClient(port); + clients.push(ws); + + const responsePromise = waitForMessage(ws); + sendRpc(ws, 1, 'short'); + const response = await responsePromise; + + expect(response.error.code).toBe(-32603); + expect(response.error.data).toEqual({ causes: ['the wallet SDK said so'], mnCode: 'DUST_REQUIRED' }); + }); + it('tracks connections', async () => { const port = nextPort(); server = createRpcServer({ diff --git a/src/commands/grant.ts b/src/commands/grant.ts index cbc8db89..b7fbb30f 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -10,8 +10,7 @@ import { existsSync } from 'node:fs'; // this process: no server, no port. import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { ERROR_CODES, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { DustRequiredError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type GrantAccount, openGrantAccount, ownerDeviceOf } from '../lib/grant/account.ts'; import { deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; import { type OwnerCommandOutput, grantRequestOf, grantsOf, issue, issuePreview, revoke, revokeAll, statusOf } from '../lib/grant/owner-commands.ts'; @@ -38,9 +37,10 @@ const SPINNER_LABEL: Record = { device: 'Working on the account\'s devices...', }; +/** Whether the failure is a shortage of Dust or NIGHT, by the code it carries. */ function isShortOfDust(err: Error): boolean { - const { errorCode } = classifyError(err); - return errorCode === ERROR_CODES.DUST_REQUIRED || errorCode === ERROR_CODES.INSUFFICIENT_BALANCE; + const { code } = err as { code?: unknown }; + return code === 'DUST_REQUIRED' || code === 'INSUFFICIENT_BALANCE'; } /** A deposit is refused before anything is built when the wallet's synced shielded NIGHT is short: the SDK's own refusal names neither the token nor the amounts. */ @@ -295,8 +295,9 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, } catch (err) { spinner.fail(`${request.subcommand} failed`); // A deploy costs far more Dust than a transfer: say how much when that is what stopped it. + // With the note, the failure is a Dust shortage: DUST_REQUIRED, as the note's words always made it. if (request.subcommand === 'deploy' && funds !== undefined && err instanceof Error && isShortOfDust(err)) { - throw new Error(`${err.message}\n\n${deployShortOfDustNote(funds.dustBalance)}`); + throw new DustRequiredError(`${err.message}\n\n${deployShortOfDustNote(funds.dustBalance)}`, { cause: err }); } throw err; } diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 56ad6d15..992bde08 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -198,7 +198,8 @@ function rpcCall(method, params = {}) { if (msg.id === id) { clearTimeout(timeout); rpcWs.removeListener('message', handler); - if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error))); + // mn serve's failure, with mn's code for it when the server gave one. + if (msg.error) reject(Object.assign(new Error(msg.error.message || JSON.stringify(msg.error)), typeof msg.error.data?.mnCode === 'string' ? { code: msg.error.data.mnCode } : {})); else resolve(msg.result); } } catch {} @@ -257,25 +258,54 @@ export const SCRIPT_ERROR_MARKER = '__MN_ERROR__'; /** * First in every generated script: report any failure (a rejected top-level - * await included) as one marked line, then exit 1. Without it Node prints the + * await included) as one marked line, its message and the code it carries (mn + * serve's code for a failure there), then exit 1. Without it Node prints the * uncaught exception with its source context, and that became mn's error. */ export const SCRIPT_PRELUDE = ` const fail = (e) => { - process.stderr.write('\\n${SCRIPT_ERROR_MARKER} ' + JSON.stringify(String(e?.message ?? e)) + '\\n'); + const failure = { message: String(e?.message ?? e), ...(typeof e?.code === 'string' ? { code: e.code } : {}) }; + process.stderr.write('\\n${SCRIPT_ERROR_MARKER} ' + JSON.stringify(failure) + '\\n'); process.exit(1); }; process.on('uncaughtException', fail); process.on('unhandledRejection', fail); `; -/** The failure a generated script reported, or its whole stderr when it reported none. */ -export function scriptFailureMessage(stderr: string, exitCode: number | null): string { +/** What a generated script reported failing with: its message, and the code the failure carried. */ +export interface ScriptFailure { + message: string; + code?: string; +} + +/** The failure a generated script reported (a script of an older mn reported its message alone), or its whole stderr when it reported none. */ +export function scriptFailureOf(stderr: string, exitCode: number | null): ScriptFailure { const marked = new RegExp(`^${SCRIPT_ERROR_MARKER} (.*)$`, 'm').exec(stderr); if (marked) { - try { return JSON.parse(marked[1]!) as string; } catch { return marked[1]!; } + let reported: unknown; + try { reported = JSON.parse(marked[1]!); } catch { return { message: marked[1]! }; } + if (typeof reported === 'string') return { message: reported }; + const { message, code } = (reported ?? {}) as { message?: unknown; code?: unknown }; + return { message: typeof message === 'string' ? message : marked[1]!, ...(typeof code === 'string' ? { code } : {}) }; + } + return { message: stderr.trim() || `Script exited with code ${exitCode}` }; +} + +/** The message of the failure a generated script reported, or its whole stderr when it reported none. */ +export function scriptFailureMessage(stderr: string, exitCode: number | null): string { + return scriptFailureOf(stderr, exitCode).message; +} + +/** A generated script failed: its message, and the code its failure carried across the process (undefined when it carried none). */ +export class ContractScriptError extends Error { + readonly code: string | undefined; + + constructor({ message, code }: ScriptFailure) { + super(message); + this.code = code; + this.name = 'ContractScriptError'; + Object.setPrototypeOf(this, ContractScriptError.prototype); } - return stderr.trim() || `Script exited with code ${exitCode}`; } /** What every SDK set's script shares, for the engine to write it with. */ @@ -579,7 +609,7 @@ export async function executeScript({ dir: dappDir, script, packages, onMessage, return; } if (code !== 0) { - reject(new Error(scriptFailureMessage(stderrRaw, code))); + reject(new ContractScriptError(scriptFailureOf(stderrRaw, code))); return; } resolve(stdout.trim()); diff --git a/src/lib/ws-rpc.ts b/src/lib/ws-rpc.ts index be7611f0..fec45b1a 100644 --- a/src/lib/ws-rpc.ts +++ b/src/lib/ws-rpc.ts @@ -69,6 +69,19 @@ function isApiError(err: unknown): err is APIError { ); } +/** + * mn's code for the failure, which the wire carries as `data.mnCode`: the one + * the connector marked it with (an API error's own `code` is the API's), or + * the code a typed error of mn's carries. Undefined when it has none. + */ +function mnCodeOf(err: unknown): string | undefined { + if (typeof err !== 'object' || err === null) return undefined; + const marked = (err as { mnCode?: unknown }).mnCode; + if (typeof marked === 'string') return marked; + const code = (err as { code?: unknown }).code; + return !isApiError(err) && typeof code === 'string' ? code : undefined; +} + /** Walk an error's cause chain and extract structured data for the JSON-RPC error response. */ function extractErrorData(err: unknown): Record | undefined { if (!(err instanceof Error) && !(typeof err === 'object' && err !== null && '_tag' in err)) { @@ -305,9 +318,10 @@ export function createRpcServer(options: RpcServerOptions): RpcServer { const durationMs = Date.now() - startTime; const rpcCode = (err as any)?.rpcCode ?? mapErrorToRpcCode(err); const message = err instanceof Error ? err.message : 'Internal error'; - const data = isApiError(err) - ? { type: err.type, code: err.code } - : extractErrorData(err); + // The API's own error data as the specification has it, with mn's code beside it (an additive key). + const mnCode = mnCodeOf(err); + const described = isApiError(err) ? { type: err.type, code: err.code } : extractErrorData(err); + const data = mnCode === undefined ? described : { ...described, mnCode }; const response: JsonRpcErrorResponse = { jsonrpc: '2.0', diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 93a8cc57..f7c34ee9 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -17,7 +17,7 @@ import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/proto import type { CommandRun } from './lib/run-command.ts'; import { servePayer } from './lib/serve-payer.ts'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { asReported } from '@kuiralabs/midnight-cli-core/lib/errors'; import { withServerAdvice } from './lib/mcp/server-advice.ts'; import { trimAgentMessage } from '@kuiralabs/midnight-cli-core/lib/error-trim'; import { PKG_VERSION } from './lib/pkg.ts'; @@ -201,8 +201,8 @@ async function executeTool(name: string, params: Record, call: } function errorResponse(thrown: Error, call: CommandRun) { - // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. - const error = withServerAdvice(withNodeReason(thrown), call.host.paths().stateRoot); + // A node's refusal is reported in the node's words, also when a command wrapped it. + const error = withServerAdvice(asReported(thrown), call.host.paths().stateRoot); const { errorCode } = classifyError(error, installedCommands); return { content: [{ diff --git a/src/wallet.ts b/src/wallet.ts index fade0f4e..e9bb3bc1 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -6,12 +6,11 @@ import { parseArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { errorMessage, usageMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { assertKnownFlags } from '@kuiralabs/midnight-cli-core/lib/command-flags'; -import { withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { installedCommands } from './lib/installed-commands.ts'; import { commandNeedsWalletSdk, dispatchCommand, processOutput } from './lib/command-dispatch.ts'; import type { CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { classifyError, humanizeNetworkError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { asReported, isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { writeJsonError } from '@kuiralabs/midnight-cli-core/lib/json-output'; import { PKG_VERSION } from './lib/pkg.ts'; import { migrateOldWallet } from './lib/wallet-paths.ts'; @@ -115,8 +114,8 @@ run().then((outcome) => { process.exit(process.exitCode ?? 0); } }).catch((thrown: Error) => { - // A node's refusal is reported with the node's words, which the wallet SDK keeps only among its causes. - const err = withNodeReason(thrown); + // A node's refusal is reported in the node's words, also when a command wrapped it. + const err = asReported(thrown); // The code and exit code come from the error's code, as the MCP server's do: // a usage error carries INVALID_ARGS unless its class names another // (PASSPHRASE_REQUIRED). Usage errors (missing/unknown subcommand, bad args) From afdfe2cad094a7d50bc3a89403bdf46e175d1a6f Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 11:48:34 -0800 Subject: [PATCH 65/88] No classification reads a message; code tables generated (3C, 7-8 of 8) The message fallback is gone: classifyError looks the error's code up in the installed packages' registry, and an error with none is UNKNOWN. What still had to be read from text is read once, at the boundary that meets it: transport failures (refused, not found, timed out, fetch failed) become NETWORK_ERROR at the engine boundary, inside a contract script and in grant. A test fails if classification reads an error's message. Every code definition carries its recovery and order, and each package's agent-manual and skill rows, the manual's exit-code list and docs/JSON_CONTRACT.md's table are generated from them. Approved: errors whose code came only from an accident of wording now report UNKNOWN (Y52); an unreachable service reached through the engine or a contract script reports NETWORK_ERROR (Y55); the code tables are generated (Y52). Suite 2732, beta 180; snapshot changes only in the three generated tables; scratch chain final pass 84/84 in a clean runner, swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads. --- docs/JSON_CONTRACT.md | 53 ++++- docs/SKILL.md | 37 ++-- packages/chain/api-report.md | 15 +- packages/chain/src/commands/chain.codes.ts | 6 +- packages/chain/src/commands/chain.guidance.ts | 35 +--- packages/cli-core/api-report.md | 148 +++++++++----- packages/cli-core/src/commands/core.codes.ts | 62 +++--- .../cli-core/src/commands/core.guidance.ts | 111 +---------- packages/cli-core/src/lib/agent-guidance.ts | 64 ++++++ packages/cli-core/src/lib/error-codes.ts | 6 +- packages/cli-core/src/lib/errors.ts | 2 +- packages/cli-core/src/lib/exit-codes.ts | 188 +----------------- packages/cli-core/src/lib/sdk-errors.ts | 14 +- .../cli-core/src/lib/transport-failure.ts | 55 +++++ scripts/check-layering.mjs | 4 +- scripts/write-readme-commands.ts | 13 +- src/__tests__/agent-guidance.test.ts | 7 +- src/__tests__/blockfrost.test.ts | 3 +- src/__tests__/chain-clock.test.ts | 3 +- .../classify-reads-no-message.test.ts | 58 ++++++ src/__tests__/command-registry.test.ts | 2 +- src/__tests__/contract-runtime-check.test.ts | 3 +- src/__tests__/contract-script-errors.test.ts | 43 +++- src/__tests__/dust-registration-plan.test.ts | 3 +- .../engine-beta-error-code-parity.test.ts | 1 - src/__tests__/error-code-docs.test.ts | 105 ++++++++++ src/__tests__/error-code-parity.test.ts | 73 +++++-- src/__tests__/exit-codes.test.ts | 56 +++--- src/__tests__/grant-deploy-cost.test.ts | 5 +- src/__tests__/helpers/closed-port.ts | 13 ++ src/__tests__/helpers/connector-suite.ts | 9 +- .../helpers/engine-boundary-suite.ts | 10 +- src/__tests__/json-output.test.ts | 126 +++--------- src/__tests__/node-version.test.ts | 3 +- src/__tests__/offer-envelope.test.ts | 3 +- src/__tests__/open-offers.test.ts | 3 +- src/__tests__/run-command.test.ts | 5 +- src/__tests__/sdk-errors.test.ts | 39 +++- src/__tests__/swap-offer.test.ts | 5 +- src/__tests__/transfer-lib.test.ts | 3 +- src/__tests__/transfer-request.test.ts | 3 +- src/__tests__/transport-failure.test.ts | 79 ++++++++ src/__tests__/wallet-session.test.ts | 6 +- src/commands/contract.codes.ts | 2 +- src/commands/contract.guidance.ts | 13 +- src/commands/dev.codes.ts | 2 +- src/commands/dev.guidance.ts | 20 +- src/commands/grant.codes.ts | 2 +- src/commands/grant.guidance.ts | 20 +- src/commands/grant.ts | 4 +- src/commands/manual.ts | 13 +- src/commands/wallet.codes.ts | 2 +- src/commands/wallet.guidance.ts | 74 +------ src/lib/agent-manual.ts | 8 - src/lib/code-tables.ts | 53 +++++ src/lib/contract/runner.ts | 22 +- src/lib/readme-commands.ts | 13 +- 57 files changed, 959 insertions(+), 771 deletions(-) create mode 100644 packages/cli-core/src/lib/transport-failure.ts create mode 100644 src/__tests__/classify-reads-no-message.test.ts create mode 100644 src/__tests__/error-code-docs.test.ts create mode 100644 src/__tests__/helpers/closed-port.ts create mode 100644 src/__tests__/transport-failure.test.ts create mode 100644 src/lib/code-tables.ts diff --git a/docs/JSON_CONTRACT.md b/docs/JSON_CONTRACT.md index f0cff8b2..7a85a9b0 100644 --- a/docs/JSON_CONTRACT.md +++ b/docs/JSON_CONTRACT.md @@ -86,17 +86,54 @@ Aliases (transparently resolved to a canonical key): | 6 | TX_REJECTED / `STALE_UTXO` / `PROOF_TIMEOUT` | | 7 | Cancelled | -The numeric codes and the error code strings are stable. Internal helpers -in `src/lib/exit-codes.ts` are the source of truth. +The numeric codes and the error code strings are stable. Each package defines its error codes (its `.codes.ts`), and the table below is generated from them. ### Error code strings -Stable identifiers used in error messages and structured error objects: - -- `DUST_REQUIRED` -- `STALE_UTXO` -- `PROOF_TIMEOUT` -- `INVALID_DUST_SPEND_PROOF` +Stable identifiers used in error messages and structured error objects, with the exit code each ends the CLI with: + + +| Code | Exit | Meaning | +|------|------|---------| +| `INVALID_ARGS` | 2 | Missing/invalid argument. | +| `WALLET_NOT_FOUND` | 3 | Named wallet doesn't exist on disk. | +| `NETWORK_ERROR` | 4 | Indexer/node/proof-server connection refused or DNS failure. | +| `SYNC_TIMEOUT` | 4 | Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync. | +| `INSUFFICIENT_BALANCE` | 5 | Wallet doesn't have enough NIGHT to cover the requested amount. | +| `TX_REJECTED` | 6 | Chain rejected the submitted transaction (catch-all when no more specific code applies). | +| `STALE_UTXO` | 6 | UTXO was already spent on-chain (substrate "error code 115"). | +| `STALE_CACHE` | 6 | Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed). | +| `PROOF_TIMEOUT` | 6 | ZK proof generation didn't finish within the deadline. | +| `PROOF_FAILURE` | 6 | Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server. | +| `INVALID_DUST_PROOF` | 6 | Chain rejected the dust spend proof as malformed (substrate "Custom error 170"). Stale commitment tree. | +| `DUST_REQUIRED` | 5 | Wallet has NIGHT but not enough DUST for the fee. | +| `DUST_GENERATING` | 5 | A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust. | +| `CHAIN_CLOCK_BEHIND` | 4 | The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold. | +| `UNSUPPORTED_LEDGER` | 4 | The network is on ledger 8; this build supports ledger 9 only. | +| `LOCALNET_UNAVAILABLE` | 4 | `mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build. | +| `LOCAL_STACK_UNREACHABLE` | 4 | No ledger-9 stack answers at the configured endpoints. | +| `AMBIGUOUS_LOCAL_STACKS` | 4 | Several local Midnight stacks are running and no endpoints are configured, so mn won't guess. | +| `UNSUPPORTED_NODE` | 1 | Node.js is older than 22 (22.18 for mn grant). | +| `NO_NODE_RUNTIME` | 1 | Contract scripts run under Node.js, and none was found on PATH. | +| `NO_ACCOUNT` | 1 | A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network. | +| `WRONG_PASSPHRASE` | 2 | `MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | +| `PASSPHRASE_REQUIRED` | 2 | A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none). | +| `BLOCKFROST_PROJECT_ID_REQUIRED` | 4 | The network (preprod) is served by Blockfrost and no project id is set. | +| `BLOCKFROST_PROJECT_ID_REJECTED` | 4 | Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network. | +| `BLOCKFROST_LIMIT_REACHED` | 4 | Blockfrost's plan limit or rate limit. | +| `ENDPOINT_SHUT_DOWN` | 4 | An endpoint set by flag or config was shut down by its operator (the old preprod indexer). | +| `OTHER_SDK_SET` | 1 | The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet). | +| `MIXED_SDK_LAYOUT` | 1 | mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger. | +| `NO_STATE_ROOT` | 1 | The host gave mn no place to keep its state (a program's `createHost` without paths). | +| `NO_PAYER` | 1 | A command that submits a transaction was called without a payer. | +| `COMMAND_FAILED` | 1 | A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result. | +| `NOT_AN_OFFER` | 2 | The bytes given as a swap offer are not one. | +| `TERMS_MISMATCH` | 2 | A swap offer's own terms differ from the agreed ones. | +| `OFFER_EXPIRED` | 2 | A swap offer is past the expiry its maker set. | +| `OFFER_COINS_IN_USE` | 2 | A spend would use coins an open swap offer of this wallet's holds, cancelling it. | +| `CANCELLED` | 7 | Operation was aborted (SIGINT, or the MCP call was cancelled). | +| `UNKNOWN` | 1 | Error didn't match any known classifier. | + Hooks and parsers may rely on substring matching against these. diff --git a/docs/SKILL.md b/docs/SKILL.md index d161bfe9..4ab4ab44 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -143,29 +143,42 @@ Every MCP tool error returns `{ error: true, code: , message: " })` then retry. | -| `STALE_CACHE` | Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed). | `midnight_cache_clear({ wallet: "" })` then retry. | +| `TX_REJECTED` | Chain rejected the submitted transaction (catch-all when no more specific code applies). | Read the message; usually a state mismatch resolved by re-sync + retry. | | `STALE_UTXO` | UTXO was already spent on-chain (substrate "error code 115"). | Re-sync (the next call will refresh state) and retry. | -| `PROOF_FAILURE` | Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server. | Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: "" })` then retry. | +| `STALE_CACHE` | Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed). | `midnight_cache_clear({ wallet: "" })` then retry. | | `PROOF_TIMEOUT` | ZK proof generation didn't finish within the deadline. | Retry — proofs can be slow under load. | -| `SYNC_TIMEOUT` | Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync. | Retry; the cache resumes from the last applied event so progress is preserved. | -| `NETWORK_ERROR` | Indexer/node/proof-server connection refused or DNS failure. | Check `midnight_localnet_status()` or the endpoints the user configured; on this build `midnight_localnet_up()` is refused, so ask the user to start their ledger-9 stack. | +| `PROOF_FAILURE` | Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server. | Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: "" })` then retry. | +| `INVALID_DUST_PROOF` | Chain rejected the dust spend proof as malformed (substrate "Custom error 170"). Stale commitment tree. | `midnight_cache_clear({ wallet: "" })` then retry. | +| `DUST_REQUIRED` | Wallet has NIGHT but not enough DUST for the fee. | Not registered (`midnight_dust_status()` shows `registered: false`): run `midnight_dust_register()`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes ("generates the rest in about 4 minutes"). Wait that long and retry, don't retry at once. | +| `DUST_GENERATING` | A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust. | The message says when: run `midnight_dust_register()` again then, or add NIGHT. | +| `CHAIN_CLOCK_BEHIND` | The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold. | Wait for it to catch up, or ask the user to restart the local chain. | | `UNSUPPORTED_LEDGER` | The network is on ledger 8; this build supports ledger 9 only. | Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry. | -| `LOCALNET_UNAVAILABLE` | `midnight_localnet_up()` can't start a ledger-9 stack on this build. | Ask the user to start their ledger-9 stack and point mn at it (endpoint config). | +| `LOCALNET_UNAVAILABLE` | `mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build. | Ask the user to start their ledger-9 stack and point mn at it (endpoint config). | | `LOCAL_STACK_UNREACHABLE` | No ledger-9 stack answers at the configured endpoints. | Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints. | | `AMBIGUOUS_LOCAL_STACKS` | Several local Midnight stacks are running and no endpoints are configured, so mn won't guess. | Ask the user which stack to use; they set its endpoints with `midnight config set`. Don't retry blindly. | -| `NO_ACCOUNT` | A `midnight_grant_*` tool was called for a wallet that has no account on this network. | Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow). | -| `PASSPHRASE_REQUIRED` | A tool needed a secret (a wallet's seed, an account's owner key) and the MCP server has no passphrase. | Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat. | +| `UNSUPPORTED_NODE` | Node.js is older than 22 (22.18 for mn grant). | Ask the user to install a current Node.js. | +| `NO_NODE_RUNTIME` | Contract scripts run under Node.js, and none was found on PATH. | Ask the user to install Node.js 22 or later, or to run mn under Node. | +| `NO_ACCOUNT` | A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network. | Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow). | | `WRONG_PASSPHRASE` | `MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed. | +| `PASSPHRASE_REQUIRED` | A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none). | Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat. | | `BLOCKFROST_PROJECT_ID_REQUIRED` | The network (preprod) is served by Blockfrost and no project id is set. | Ask the user to create a Midnight preprod project at https://blockfrost.io and run `midnight config set blockfrost-project-id ` themselves. Never ask them to paste the id into the chat. Don't retry until they have. | | `BLOCKFROST_PROJECT_ID_REJECTED` | Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network. | Ask the user to check it at blockfrost.io and set it again. Don't retry blindly. | | `BLOCKFROST_LIMIT_REACHED` | Blockfrost's plan limit or rate limit. | Wait and retry once; if it persists, tell the user it is their Blockfrost plan. | | `ENDPOINT_SHUT_DOWN` | An endpoint set by flag or config was shut down by its operator (the old preprod indexer). | `midnight_config_unset({ key: "indexer-ws" })` (and `node` if set), then retry. | -| `WALLET_NOT_FOUND` | Named wallet doesn't exist on disk. | `midnight_wallet_list()` — user may have removed it. | -| `INVALID_ARGS` | Missing/invalid argument. | Show the message to the user verbatim — it names the missing field. | -| `TX_REJECTED` | Chain rejected the submitted transaction (catch-all when no more specific code applies). | Read the message; usually a state mismatch resolved by re-sync + retry. | +| `OTHER_SDK_SET` | The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet). | Make the call in a process of its own: ask the user to start an MCP server for that network. | +| `MIXED_SDK_LAYOUT` | mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger. | Ask the user to install mn with npm. | +| `NO_STATE_ROOT` | The host gave mn no place to keep its state (a program's `createHost` without paths). | Give the host its paths (`createHost({ paths })`). | +| `NO_PAYER` | A command that submits a transaction was called without a payer. | Give the call a payer. | +| `COMMAND_FAILED` | A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result. | Read the command's result in the message. | +| `NOT_AN_OFFER` | The bytes given as a swap offer are not one. | Ask the maker for the offer again. | +| `TERMS_MISMATCH` | A swap offer's own terms differ from the agreed ones. | Don't take it; agree the terms again with the maker. | +| `OFFER_EXPIRED` | A swap offer is past the expiry its maker set. | Ask the maker for a new one. | +| `OFFER_COINS_IN_USE` | A spend would use coins an open swap offer of this wallet's holds, cancelling it. | Cancel the offer first (`mn swap cancel`), or wait until it is taken. | | `CANCELLED` | Operation was aborted (SIGINT, or the MCP call was cancelled). | A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user. | | `UNKNOWN` | Error didn't match any known classifier. | Surface the message to the user. If reproducible, a new code may be warranted. | diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md index eec2c1a4..6d362ea5 100644 --- a/packages/chain/api-report.md +++ b/packages/chain/api-report.md @@ -9,20 +9,23 @@ export declare const chainCodes: readonly [ { readonly code: "UNSUPPORTED_LEDGER"; readonly exitCode: 4; - readonly summary: "The chain is on ledger 8; this build supports ledger 9 only."; - readonly recovery: "Use midnight-wallet-cli 0.5.x for that network."; + readonly order: 150; + readonly summary: "The network is on ledger 8; this build supports ledger 9 only."; + readonly recovery: "Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry."; }, { readonly code: "LOCAL_STACK_UNREACHABLE"; readonly exitCode: 4; + readonly order: 170; readonly summary: "No ledger-9 stack answers at the configured endpoints."; - readonly recovery: "Start one, or fix the endpoints."; + readonly recovery: "Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints."; }, { readonly code: "CHAIN_CLOCK_BEHIND"; readonly exitCode: 4; - readonly summary: "The chain's clock is behind this computer's (a local chain after the machine slept), so Dust estimates don't hold."; - readonly recovery: "Wait for it to catch up, or restart the local chain."; + readonly order: 140; + readonly summary: "The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold."; + readonly recovery: "Wait for it to catch up, or ask the user to restart the local chain."; } ]; ``` @@ -30,7 +33,7 @@ export declare const chainCodes: readonly [ ## `@kuiralabs/midnight-chain/commands/chain.guidance` ```ts -import type { PackageGuidance } from "@kuiralabs/midnight-cli-core/lib/agent-guidance"; +import { type PackageGuidance } from "@kuiralabs/midnight-cli-core/lib/agent-guidance"; export declare const chainGuidance: PackageGuidance; ``` diff --git a/packages/chain/src/commands/chain.codes.ts b/packages/chain/src/commands/chain.codes.ts index 6acd9de4..b35f43af 100644 --- a/packages/chain/src/commands/chain.codes.ts +++ b/packages/chain/src/commands/chain.codes.ts @@ -5,7 +5,7 @@ import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; export const chainCodes = defineCodes([ - { code: 'UNSUPPORTED_LEDGER', exitCode: EXIT_NETWORK_ERROR, summary: 'The chain is on ledger 8; this build supports ledger 9 only.', recovery: 'Use midnight-wallet-cli 0.5.x for that network.' }, - { code: 'LOCAL_STACK_UNREACHABLE', exitCode: EXIT_NETWORK_ERROR, summary: 'No ledger-9 stack answers at the configured endpoints.', recovery: 'Start one, or fix the endpoints.' }, - { code: 'CHAIN_CLOCK_BEHIND', exitCode: EXIT_NETWORK_ERROR, summary: "The chain's clock is behind this computer's (a local chain after the machine slept), so Dust estimates don't hold.", recovery: 'Wait for it to catch up, or restart the local chain.' }, + { code: 'UNSUPPORTED_LEDGER', exitCode: EXIT_NETWORK_ERROR, order: 150, summary: 'The network is on ledger 8; this build supports ledger 9 only.', recovery: "Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry." }, + { code: 'LOCAL_STACK_UNREACHABLE', exitCode: EXIT_NETWORK_ERROR, order: 170, summary: 'No ledger-9 stack answers at the configured endpoints.', recovery: 'Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints.' }, + { code: 'CHAIN_CLOCK_BEHIND', exitCode: EXIT_NETWORK_ERROR, order: 140, summary: "The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold.", recovery: 'Wait for it to catch up, or ask the user to restart the local chain.' }, ]); diff --git a/packages/chain/src/commands/chain.guidance.ts b/packages/chain/src/commands/chain.guidance.ts index bd66114b..b20efb2a 100644 --- a/packages/chain/src/commands/chain.guidance.ts +++ b/packages/chain/src/commands/chain.guidance.ts @@ -2,40 +2,13 @@ // its pieces of `help --agent` and of the two skills, each // naming its section and its place there. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { chainCodes } from './chain.codes.ts'; export const chainGuidance: PackageGuidance = { pieces: [ - { - text: 'agent-manual', - section: 'error-codes', - order: 50, - body: ` CHAIN_CLOCK_BEHIND 4 The chain's clock lags this computer's (a local - chain after sleep); wait for it or restart it - UNSUPPORTED_LEDGER 4 The chain is on ledger 8; use mn 0.5.x for it -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 70, - body: ` LOCAL_STACK_UNREACHABLE 4 No ledger-9 stack answers at the endpoints -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 30, - body: `| \`UNSUPPORTED_LEDGER\` | The network is on ledger 8; this build supports ledger 9 only. | Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 50, - body: `| \`LOCAL_STACK_UNREACHABLE\` | No ledger-9 stack answers at the configured endpoints. | Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints. | -`, - }, + // Its error codes' rows in the manual and the full skill, from their definitions. + ...codeGuidancePieces(chainCodes), ], toolsTable: [ { tool: 'midnight_tx_status', group: 'transactions', order: 50, description: ['What became of a transaction: block, fee, result'] }, diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index c863178e..8c6a025e 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -24,184 +24,219 @@ export declare const coreCodes: readonly [ { readonly code: "INVALID_ARGS"; readonly exitCode: 2; - readonly summary: "Missing or invalid arguments."; - readonly recovery: "Fix the arguments and run it again; `midnight help ` shows them."; + readonly order: 10; + readonly summary: "Missing/invalid argument."; + readonly recovery: "Show the message to the user verbatim \u2014 it names the missing field."; }, { readonly code: "WRONG_PASSPHRASE"; readonly exitCode: 2; - readonly summary: "mn's passphrase was wrong, or a sealed secret was changed."; - readonly recovery: "Run it again with the passphrase mn was protected with."; + readonly order: 220; + readonly summary: "`MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed."; + readonly recovery: "Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed."; }, { readonly code: "PASSPHRASE_REQUIRED"; readonly exitCode: 2; - readonly summary: "A secret was needed and no passphrase could be had."; - readonly recovery: "Set MN_PASSPHRASE, or run at a terminal."; + readonly order: 230; + readonly summary: "A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none)."; + readonly recovery: "Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat."; }, { readonly code: "NETWORK_ERROR"; readonly exitCode: 4; - readonly summary: "Connection refused, timeout, DNS failure."; - readonly recovery: "Check that the node, indexer and proof server at the configured endpoints are running."; + readonly order: 30; + readonly summary: "Indexer/node/proof-server connection refused or DNS failure."; + readonly recovery: "Check `midnight_localnet_status()` or the endpoints the user configured; on this build `midnight_localnet_up()` is refused, so ask the user to start their ledger-9 stack."; }, { readonly code: "AMBIGUOUS_LOCAL_STACKS"; readonly exitCode: 4; - readonly summary: "Several local Midnight stacks run and no endpoints were given."; - readonly recovery: "Pass endpoint flags or `midnight config set` them."; + readonly order: 180; + readonly summary: "Several local Midnight stacks are running and no endpoints are configured, so mn won't guess."; + readonly recovery: "Ask the user which stack to use; they set its endpoints with `midnight config set`. Don't retry blindly."; }, { readonly code: "BLOCKFROST_PROJECT_ID_REQUIRED"; readonly exitCode: 4; - readonly summary: "The network is served by Blockfrost and no project id is set."; - readonly recovery: "`mn config set blockfrost-project-id `."; + readonly order: 240; + readonly summary: "The network (preprod) is served by Blockfrost and no project id is set."; + readonly recovery: "Ask the user to create a Midnight preprod project at https://blockfrost.io and run `midnight config set blockfrost-project-id ` themselves. Never ask them to paste the id into the chat. Don't retry until they have."; }, { readonly code: "BLOCKFROST_PROJECT_ID_REJECTED"; readonly exitCode: 4; - readonly summary: "Blockfrost refused the project id."; - readonly recovery: "Check it at blockfrost.io and set it again."; + readonly order: 250; + readonly summary: "Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network."; + readonly recovery: "Ask the user to check it at blockfrost.io and set it again. Don't retry blindly."; }, { readonly code: "BLOCKFROST_LIMIT_REACHED"; readonly exitCode: 4; - readonly summary: "Blockfrost is holding the project back (its plan's daily limit, or too many requests at once)."; - readonly recovery: "Wait, or see the project's plan."; + readonly order: 260; + readonly summary: "Blockfrost's plan limit or rate limit."; + readonly recovery: "Wait and retry once; if it persists, tell the user it is their Blockfrost plan."; }, { readonly code: "ENDPOINT_SHUT_DOWN"; readonly exitCode: 4; - readonly summary: "An endpoint set by flag or config was shut down by its operator."; - readonly recovery: "Unset it (`mn config unset indexer-ws`)."; + readonly order: 270; + readonly summary: "An endpoint set by flag or config was shut down by its operator (the old preprod indexer)."; + readonly recovery: "`midnight_config_unset({ key: \"indexer-ws\" })` (and `node` if set), then retry."; }, { readonly code: "CANCELLED"; readonly exitCode: 7; - readonly summary: "Operation cancelled (SIGINT)."; + readonly order: 370; + readonly summary: "Operation was aborted (SIGINT, or the MCP call was cancelled)."; + readonly recovery: "A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user."; }, { readonly code: "OTHER_SDK_SET"; readonly exitCode: 1; - readonly summary: "The process has loaded one SDK set's engine and the call's network runs on the other."; - readonly recovery: "Run the call in a process of its own (for MCP, a server for that network)."; + readonly order: 280; + readonly summary: "The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet)."; + readonly recovery: "Make the call in a process of its own: ask the user to start an MCP server for that network."; }, { readonly code: "MIXED_SDK_LAYOUT"; readonly exitCode: 1; - readonly summary: "An engine's SDK packages reach more than one copy of its ledger: mn was installed without its shrinkwrap (bun's installer)."; - readonly recovery: "Install mn with npm."; + readonly order: 290; + readonly summary: "mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger."; + readonly recovery: "Ask the user to install mn with npm."; }, { readonly code: "UNSUPPORTED_NODE"; readonly exitCode: 1; - readonly summary: "This Node.js is older than mn supports (22)."; - readonly recovery: "Install a current Node.js."; + readonly order: 190; + readonly summary: "Node.js is older than 22 (22.18 for mn grant)."; + readonly recovery: "Ask the user to install a current Node.js."; }, { readonly code: "NO_STATE_ROOT"; readonly exitCode: 1; - readonly summary: "The host gave mn no place to keep its state."; - readonly recovery: "Give the host its paths (createHost paths)."; + readonly order: 300; + readonly summary: "The host gave mn no place to keep its state (a program's `createHost` without paths)."; + readonly recovery: "Give the host its paths (`createHost({ paths })`)."; }, { readonly code: "NO_PAYER"; readonly exitCode: 1; + readonly order: 310; readonly summary: "A command that submits a transaction was called without a payer."; readonly recovery: "Give the call a payer."; }, { readonly code: "COMMAND_FAILED"; readonly exitCode: 1; - readonly summary: "A command ended with a non-zero exit code without throwing (a test run whose tests failed); the message carries its result."; + readonly order: 320; + readonly summary: "A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result."; readonly recovery: "Read the command's result in the message."; }, { readonly code: "UNKNOWN"; readonly exitCode: 1; - readonly summary: "Unclassified error."; + readonly order: 380; + readonly summary: "Error didn't match any known classifier."; + readonly recovery: "Surface the message to the user. If reproducible, a new code may be warranted."; }, { readonly code: "PROOF_TIMEOUT"; readonly exitCode: 6; - readonly summary: "ZK proof generation timed out."; - readonly recovery: "Retry: proofs can be slow under load."; + readonly order: 90; + readonly summary: "ZK proof generation didn't finish within the deadline."; + readonly recovery: "Retry \u2014 proofs can be slow under load."; }, { readonly code: "PROOF_FAILURE"; readonly exitCode: 6; - readonly summary: "Proof server rejected or failed to generate the ZK proof."; - readonly recovery: "Ensure the proof server is running, then retry; if persistent, `mn cache clear` to force a fresh sync."; + readonly order: 100; + readonly summary: "Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server."; + readonly recovery: "Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: \"\" })` then retry."; }, { readonly code: "INVALID_DUST_PROOF"; readonly exitCode: 6; - readonly summary: "Chain rejected the dust spend proof as malformed (substrate \"Custom error 170\")."; - readonly recovery: "`mn cache clear --wallet ` then retry."; + readonly order: 110; + readonly summary: "Chain rejected the dust spend proof as malformed (substrate \"Custom error 170\"). Stale commitment tree."; + readonly recovery: "`midnight_cache_clear({ wallet: \"\" })` then retry."; }, { readonly code: "TX_REJECTED"; readonly exitCode: 6; - readonly summary: "Transaction rejected by the node."; + readonly order: 60; + readonly summary: "Chain rejected the submitted transaction (catch-all when no more specific code applies)."; + readonly recovery: "Read the message; usually a state mismatch resolved by re-sync + retry."; }, { readonly code: "STALE_UTXO"; readonly exitCode: 6; - readonly summary: "UTXOs consumed by another transaction (substrate \"error code 115\")."; - readonly recovery: "Re-sync (the next call refreshes the state) and retry."; + readonly order: 70; + readonly summary: "UTXO was already spent on-chain (substrate \"error code 115\")."; + readonly recovery: "Re-sync (the next call will refresh state) and retry."; }, { readonly code: "STALE_CACHE"; readonly exitCode: 6; - readonly summary: "Local wallet cache disagrees with chain state (a localnet reset, a remote testnet re-index)."; - readonly recovery: "`mn cache clear --wallet ` then retry."; + readonly order: 80; + readonly summary: "Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed)."; + readonly recovery: "`midnight_cache_clear({ wallet: \"\" })` then retry."; }, { readonly code: "SYNC_TIMEOUT"; readonly exitCode: 4; - readonly summary: "Wallet sync exceeded its deadline."; - readonly recovery: "Retry: the cache resumes from the last applied event."; + readonly order: 40; + readonly summary: "Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync."; + readonly recovery: "Retry; the cache resumes from the last applied event so progress is preserved."; }, { readonly code: "DUST_REQUIRED"; readonly exitCode: 5; - readonly summary: "Not enough Dust for the fee."; - readonly recovery: "Not registered: `mn dust register`. Generating: retry when the message says, or register more NIGHT."; + readonly order: 120; + readonly summary: "Wallet has NIGHT but not enough DUST for the fee."; + readonly recovery: "Not registered (`midnight_dust_status()` shows `registered: false`): run `midnight_dust_register()`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes (\"generates the rest in about 4 minutes\"). Wait that long and retry, don't retry at once."; }, { readonly code: "DUST_GENERATING"; readonly exitCode: 5; + readonly order: 130; readonly summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust."; - readonly recovery: "Run `mn dust register` again at the time the message gives, or add NIGHT."; + readonly recovery: "The message says when: run `midnight_dust_register()` again then, or add NIGHT."; }, { readonly code: "INSUFFICIENT_BALANCE"; readonly exitCode: 5; - readonly summary: "Not enough NIGHT for the operation."; + readonly order: 50; + readonly summary: "Wallet doesn't have enough NIGHT to cover the requested amount."; + readonly recovery: "Show the user. On localnet: `midnight_airdrop({ amount: \"...\" })`. On hosted networks: tell user to fund the address."; }, { readonly code: "NOT_AN_OFFER"; readonly exitCode: 2; - readonly summary: "Bytes given as a swap offer are not one."; + readonly order: 330; + readonly summary: "The bytes given as a swap offer are not one."; readonly recovery: "Ask the maker for the offer again."; }, { readonly code: "TERMS_MISMATCH"; readonly exitCode: 2; + readonly order: 340; readonly summary: "A swap offer's own terms differ from the agreed ones."; readonly recovery: "Don't take it; agree the terms again with the maker."; }, { readonly code: "OFFER_EXPIRED"; readonly exitCode: 2; + readonly order: 350; readonly summary: "A swap offer is past the expiry its maker set."; readonly recovery: "Ask the maker for a new one."; }, { readonly code: "OFFER_COINS_IN_USE"; readonly exitCode: 2; + readonly order: 360; readonly summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it."; - readonly recovery: "Cancel the offer first (mn swap cancel), or wait until it is taken."; + readonly recovery: "Cancel the offer first (`mn swap cancel`), or wait until it is taken."; } ]; ``` @@ -209,13 +244,14 @@ export declare const coreCodes: readonly [ ## `@kuiralabs/midnight-cli-core/commands/core.guidance` ```ts -import type { PackageGuidance } from "../lib/agent-guidance.ts"; +import { type PackageGuidance } from "../lib/agent-guidance.ts"; export declare const coreGuidance: PackageGuidance; ``` ## `@kuiralabs/midnight-cli-core/lib/agent-guidance` ```ts +import type { CodeDefinition } from "./error-codes.ts"; export type GuidanceText = "agent-manual" | "skill-core" | "skill-full"; export interface GuidancePiece { readonly text: GuidanceText; @@ -247,6 +283,10 @@ export declare function unplacedPieces(text: GuidanceText, sections: readonly st export declare function sectionsWithAdded(text: GuidanceText, skeleton: readonly string[], added: readonly GuidanceSection[]): string[]; export declare function assertDistinctPlaces(pieces: readonly GuidancePiece[]): void; export declare function assembleGuidance(text: GuidanceText, sections: readonly string[], pieces: readonly GuidancePiece[]): string; +export declare function wrapWords(text: string, width: number): string[]; +export declare function manualCodeRow(definition: CodeDefinition): string; +export declare function skillCodeRow(definition: CodeDefinition): string; +export declare function codeGuidancePieces(codes: readonly CodeDefinition[]): GuidancePiece[]; ``` ## `@kuiralabs/midnight-cli-core/lib/amount` @@ -1352,7 +1392,7 @@ interface ClassifiedError { exitCode: number; errorCode: string; } -export declare function classifyError(err: Error, codes?: CodeRegistry): ClassifiedError; +export declare function classifyError(err: Error, codes: CodeRegistry): ClassifiedError; export declare function classifyByCode(err: Error, codes: CodeRegistry): ClassifiedError; export declare function humanizeNetworkError(message: string): string; ``` @@ -1837,6 +1877,14 @@ export declare function checkTerms(offered: SwapTerms, agreed: SwapTerms): void; export declare function describeLeg(leg: SwapLeg): string; ``` +## `@kuiralabs/midnight-cli-core/lib/transport-failure` + +```ts +export declare function isTransportFailure(failure: unknown): boolean; +export declare function carriesOwnCode(failure: unknown): boolean; +export declare function withTransportCode(err: unknown): unknown; +``` + ## `@kuiralabs/midnight-cli-core/lib/tx-serde` ```ts diff --git a/packages/cli-core/src/commands/core.codes.ts b/packages/cli-core/src/commands/core.codes.ts index e416ab61..fc63b95d 100644 --- a/packages/cli-core/src/commands/core.codes.ts +++ b/packages/cli-core/src/commands/core.codes.ts @@ -15,37 +15,37 @@ import { } from '../lib/exit-codes.ts'; export const coreCodes = defineCodes([ - { code: 'INVALID_ARGS', exitCode: EXIT_INVALID_ARGS, summary: 'Missing or invalid arguments.', recovery: 'Fix the arguments and run it again; `midnight help ` shows them.' }, - { code: 'WRONG_PASSPHRASE', exitCode: EXIT_INVALID_ARGS, summary: "mn's passphrase was wrong, or a sealed secret was changed.", recovery: 'Run it again with the passphrase mn was protected with.' }, - { code: 'PASSPHRASE_REQUIRED', exitCode: EXIT_INVALID_ARGS, summary: 'A secret was needed and no passphrase could be had.', recovery: 'Set MN_PASSPHRASE, or run at a terminal.' }, - { code: 'NETWORK_ERROR', exitCode: EXIT_NETWORK_ERROR, summary: 'Connection refused, timeout, DNS failure.', recovery: 'Check that the node, indexer and proof server at the configured endpoints are running.' }, - { code: 'AMBIGUOUS_LOCAL_STACKS', exitCode: EXIT_NETWORK_ERROR, summary: 'Several local Midnight stacks run and no endpoints were given.', recovery: 'Pass endpoint flags or `midnight config set` them.' }, - { code: 'BLOCKFROST_PROJECT_ID_REQUIRED', exitCode: EXIT_NETWORK_ERROR, summary: 'The network is served by Blockfrost and no project id is set.', recovery: '`mn config set blockfrost-project-id `.' }, - { code: 'BLOCKFROST_PROJECT_ID_REJECTED', exitCode: EXIT_NETWORK_ERROR, summary: 'Blockfrost refused the project id.', recovery: 'Check it at blockfrost.io and set it again.' }, - { code: 'BLOCKFROST_LIMIT_REACHED', exitCode: EXIT_NETWORK_ERROR, summary: "Blockfrost is holding the project back (its plan's daily limit, or too many requests at once).", recovery: "Wait, or see the project's plan." }, - { code: 'ENDPOINT_SHUT_DOWN', exitCode: EXIT_NETWORK_ERROR, summary: 'An endpoint set by flag or config was shut down by its operator.', recovery: 'Unset it (`mn config unset indexer-ws`).' }, - { code: 'CANCELLED', exitCode: EXIT_CANCELLED, summary: 'Operation cancelled (SIGINT).' }, - { code: 'OTHER_SDK_SET', exitCode: EXIT_GENERAL_ERROR, summary: "The process has loaded one SDK set's engine and the call's network runs on the other.", recovery: 'Run the call in a process of its own (for MCP, a server for that network).' }, - { code: 'MIXED_SDK_LAYOUT', exitCode: EXIT_GENERAL_ERROR, summary: "An engine's SDK packages reach more than one copy of its ledger: mn was installed without its shrinkwrap (bun's installer).", recovery: 'Install mn with npm.' }, - { code: 'UNSUPPORTED_NODE', exitCode: EXIT_GENERAL_ERROR, summary: 'This Node.js is older than mn supports (22).', recovery: 'Install a current Node.js.' }, - { code: 'NO_STATE_ROOT', exitCode: EXIT_GENERAL_ERROR, summary: 'The host gave mn no place to keep its state.', recovery: 'Give the host its paths (createHost paths).' }, - { code: 'NO_PAYER', exitCode: EXIT_GENERAL_ERROR, summary: 'A command that submits a transaction was called without a payer.', recovery: 'Give the call a payer.' }, - { code: 'COMMAND_FAILED', exitCode: EXIT_GENERAL_ERROR, summary: 'A command ended with a non-zero exit code without throwing (a test run whose tests failed); the message carries its result.', recovery: "Read the command's result in the message." }, - { code: 'UNKNOWN', exitCode: EXIT_GENERAL_ERROR, summary: 'Unclassified error.' }, + { code: 'INVALID_ARGS', exitCode: EXIT_INVALID_ARGS, order: 10, summary: 'Missing/invalid argument.', recovery: 'Show the message to the user verbatim — it names the missing field.' }, + { code: 'WRONG_PASSPHRASE', exitCode: EXIT_INVALID_ARGS, order: 220, summary: "`MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed.", recovery: "Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed." }, + { code: 'PASSPHRASE_REQUIRED', exitCode: EXIT_INVALID_ARGS, order: 230, summary: "A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none).", recovery: "Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat." }, + { code: 'NETWORK_ERROR', exitCode: EXIT_NETWORK_ERROR, order: 30, summary: 'Indexer/node/proof-server connection refused or DNS failure.', recovery: 'Check `midnight_localnet_status()` or the endpoints the user configured; on this build `midnight_localnet_up()` is refused, so ask the user to start their ledger-9 stack.' }, + { code: 'AMBIGUOUS_LOCAL_STACKS', exitCode: EXIT_NETWORK_ERROR, order: 180, summary: "Several local Midnight stacks are running and no endpoints are configured, so mn won't guess.", recovery: "Ask the user which stack to use; they set its endpoints with `midnight config set`. Don't retry blindly." }, + { code: 'BLOCKFROST_PROJECT_ID_REQUIRED', exitCode: EXIT_NETWORK_ERROR, order: 240, summary: 'The network (preprod) is served by Blockfrost and no project id is set.', recovery: "Ask the user to create a Midnight preprod project at https://blockfrost.io and run `midnight config set blockfrost-project-id ` themselves. Never ask them to paste the id into the chat. Don't retry until they have." }, + { code: 'BLOCKFROST_PROJECT_ID_REJECTED', exitCode: EXIT_NETWORK_ERROR, order: 250, summary: 'Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network.', recovery: "Ask the user to check it at blockfrost.io and set it again. Don't retry blindly." }, + { code: 'BLOCKFROST_LIMIT_REACHED', exitCode: EXIT_NETWORK_ERROR, order: 260, summary: "Blockfrost's plan limit or rate limit.", recovery: 'Wait and retry once; if it persists, tell the user it is their Blockfrost plan.' }, + { code: 'ENDPOINT_SHUT_DOWN', exitCode: EXIT_NETWORK_ERROR, order: 270, summary: 'An endpoint set by flag or config was shut down by its operator (the old preprod indexer).', recovery: '`midnight_config_unset({ key: "indexer-ws" })` (and `node` if set), then retry.' }, + { code: 'CANCELLED', exitCode: EXIT_CANCELLED, order: 370, summary: 'Operation was aborted (SIGINT, or the MCP call was cancelled).', recovery: "A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user." }, + { code: 'OTHER_SDK_SET', exitCode: EXIT_GENERAL_ERROR, order: 280, summary: "The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet).", recovery: 'Make the call in a process of its own: ask the user to start an MCP server for that network.' }, + { code: 'MIXED_SDK_LAYOUT', exitCode: EXIT_GENERAL_ERROR, order: 290, summary: "mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger.", recovery: 'Ask the user to install mn with npm.' }, + { code: 'UNSUPPORTED_NODE', exitCode: EXIT_GENERAL_ERROR, order: 190, summary: 'Node.js is older than 22 (22.18 for mn grant).', recovery: 'Ask the user to install a current Node.js.' }, + { code: 'NO_STATE_ROOT', exitCode: EXIT_GENERAL_ERROR, order: 300, summary: "The host gave mn no place to keep its state (a program's `createHost` without paths).", recovery: "Give the host its paths (`createHost({ paths })`)." }, + { code: 'NO_PAYER', exitCode: EXIT_GENERAL_ERROR, order: 310, summary: 'A command that submits a transaction was called without a payer.', recovery: 'Give the call a payer.' }, + { code: 'COMMAND_FAILED', exitCode: EXIT_GENERAL_ERROR, order: 320, summary: 'A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result.', recovery: "Read the command's result in the message." }, + { code: 'UNKNOWN', exitCode: EXIT_GENERAL_ERROR, order: 380, summary: "Error didn't match any known classifier.", recovery: 'Surface the message to the user. If reproducible, a new code may be warranted.' }, // The engine contract: what every engine raises. - { code: 'PROOF_TIMEOUT', exitCode: EXIT_TX_REJECTED, summary: 'ZK proof generation timed out.', recovery: 'Retry: proofs can be slow under load.' }, - { code: 'PROOF_FAILURE', exitCode: EXIT_TX_REJECTED, summary: 'Proof server rejected or failed to generate the ZK proof.', recovery: 'Ensure the proof server is running, then retry; if persistent, `mn cache clear` to force a fresh sync.' }, - { code: 'INVALID_DUST_PROOF', exitCode: EXIT_TX_REJECTED, summary: 'Chain rejected the dust spend proof as malformed (substrate "Custom error 170").', recovery: '`mn cache clear --wallet ` then retry.' }, - { code: 'TX_REJECTED', exitCode: EXIT_TX_REJECTED, summary: 'Transaction rejected by the node.' }, - { code: 'STALE_UTXO', exitCode: EXIT_TX_REJECTED, summary: 'UTXOs consumed by another transaction (substrate "error code 115").', recovery: 'Re-sync (the next call refreshes the state) and retry.' }, - { code: 'STALE_CACHE', exitCode: EXIT_TX_REJECTED, summary: 'Local wallet cache disagrees with chain state (a localnet reset, a remote testnet re-index).', recovery: '`mn cache clear --wallet ` then retry.' }, - { code: 'SYNC_TIMEOUT', exitCode: EXIT_NETWORK_ERROR, summary: 'Wallet sync exceeded its deadline.', recovery: 'Retry: the cache resumes from the last applied event.' }, - { code: 'DUST_REQUIRED', exitCode: EXIT_INSUFFICIENT_BALANCE, summary: 'Not enough Dust for the fee.', recovery: 'Not registered: `mn dust register`. Generating: retry when the message says, or register more NIGHT.' }, - { code: 'DUST_GENERATING', exitCode: EXIT_INSUFFICIENT_BALANCE, summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust.", recovery: 'Run `mn dust register` again at the time the message gives, or add NIGHT.' }, - { code: 'INSUFFICIENT_BALANCE', exitCode: EXIT_INSUFFICIENT_BALANCE, summary: 'Not enough NIGHT for the operation.' }, - { code: 'NOT_AN_OFFER', exitCode: EXIT_INVALID_ARGS, summary: 'Bytes given as a swap offer are not one.', recovery: 'Ask the maker for the offer again.' }, - { code: 'TERMS_MISMATCH', exitCode: EXIT_INVALID_ARGS, summary: "A swap offer's own terms differ from the agreed ones.", recovery: "Don't take it; agree the terms again with the maker." }, - { code: 'OFFER_EXPIRED', exitCode: EXIT_INVALID_ARGS, summary: 'A swap offer is past the expiry its maker set.', recovery: 'Ask the maker for a new one.' }, - { code: 'OFFER_COINS_IN_USE', exitCode: EXIT_INVALID_ARGS, summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it.", recovery: 'Cancel the offer first (mn swap cancel), or wait until it is taken.' }, + { code: 'PROOF_TIMEOUT', exitCode: EXIT_TX_REJECTED, order: 90, summary: "ZK proof generation didn't finish within the deadline.", recovery: 'Retry — proofs can be slow under load.' }, + { code: 'PROOF_FAILURE', exitCode: EXIT_TX_REJECTED, order: 100, summary: 'Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server.', recovery: 'Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: "" })` then retry.' }, + { code: 'INVALID_DUST_PROOF', exitCode: EXIT_TX_REJECTED, order: 110, summary: 'Chain rejected the dust spend proof as malformed (substrate "Custom error 170"). Stale commitment tree.', recovery: '`midnight_cache_clear({ wallet: "" })` then retry.' }, + { code: 'TX_REJECTED', exitCode: EXIT_TX_REJECTED, order: 60, summary: 'Chain rejected the submitted transaction (catch-all when no more specific code applies).', recovery: 'Read the message; usually a state mismatch resolved by re-sync + retry.' }, + { code: 'STALE_UTXO', exitCode: EXIT_TX_REJECTED, order: 70, summary: 'UTXO was already spent on-chain (substrate "error code 115").', recovery: 'Re-sync (the next call will refresh state) and retry.' }, + { code: 'STALE_CACHE', exitCode: EXIT_TX_REJECTED, order: 80, summary: 'Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed).', recovery: '`midnight_cache_clear({ wallet: "" })` then retry.' }, + { code: 'SYNC_TIMEOUT', exitCode: EXIT_NETWORK_ERROR, order: 40, summary: 'Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync.', recovery: 'Retry; the cache resumes from the last applied event so progress is preserved.' }, + { code: 'DUST_REQUIRED', exitCode: EXIT_INSUFFICIENT_BALANCE, order: 120, summary: 'Wallet has NIGHT but not enough DUST for the fee.', recovery: 'Not registered (`midnight_dust_status()` shows `registered: false`): run `midnight_dust_register()`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes ("generates the rest in about 4 minutes"). Wait that long and retry, don\'t retry at once.' }, + { code: 'DUST_GENERATING', exitCode: EXIT_INSUFFICIENT_BALANCE, order: 130, summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust.", recovery: 'The message says when: run `midnight_dust_register()` again then, or add NIGHT.' }, + { code: 'INSUFFICIENT_BALANCE', exitCode: EXIT_INSUFFICIENT_BALANCE, order: 50, summary: "Wallet doesn't have enough NIGHT to cover the requested amount.", recovery: 'Show the user. On localnet: `midnight_airdrop({ amount: "..." })`. On hosted networks: tell user to fund the address.' }, + { code: 'NOT_AN_OFFER', exitCode: EXIT_INVALID_ARGS, order: 330, summary: 'The bytes given as a swap offer are not one.', recovery: 'Ask the maker for the offer again.' }, + { code: 'TERMS_MISMATCH', exitCode: EXIT_INVALID_ARGS, order: 340, summary: "A swap offer's own terms differ from the agreed ones.", recovery: "Don't take it; agree the terms again with the maker." }, + { code: 'OFFER_EXPIRED', exitCode: EXIT_INVALID_ARGS, order: 350, summary: 'A swap offer is past the expiry its maker set.', recovery: 'Ask the maker for a new one.' }, + { code: 'OFFER_COINS_IN_USE', exitCode: EXIT_INVALID_ARGS, order: 360, summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it.", recovery: 'Cancel the offer first (`mn swap cancel`), or wait until it is taken.' }, ]); diff --git a/packages/cli-core/src/commands/core.guidance.ts b/packages/cli-core/src/commands/core.guidance.ts index e8763c82..510164b5 100644 --- a/packages/cli-core/src/commands/core.guidance.ts +++ b/packages/cli-core/src/commands/core.guidance.ts @@ -3,116 +3,13 @@ // each naming its section and its place there, and its tools' rows in the // manual's tools table. -import type { PackageGuidance } from '../lib/agent-guidance.ts'; +import { codeGuidancePieces, type PackageGuidance } from '../lib/agent-guidance.ts'; +import { coreCodes } from './core.codes.ts'; export const coreGuidance: PackageGuidance = { pieces: [ - { - text: 'agent-manual', - section: 'error-codes', - order: 10, - body: ` INVALID_ARGS 2 Missing or invalid arguments -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 30, - body: ` NETWORK_ERROR 4 Connection refused, timeout, DNS failure -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 80, - body: ` AMBIGUOUS_LOCAL_STACKS 4 Several local stacks run; pass endpoint flags -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 110, - body: ` WRONG_PASSPHRASE 2 mn's passphrase was wrong, or a sealed secret - was changed -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 130, - body: ` BLOCKFROST_PROJECT_ID_REQUIRED 4 - Preprod is served by Blockfrost and no project - id is set: config set blockfrost-project-id - BLOCKFROST_PROJECT_ID_REJECTED 4 - Blockfrost refused the project id (HTTP 403) - BLOCKFROST_LIMIT_REACHED 4 Blockfrost's plan or rate limit; wait and retry - ENDPOINT_SHUT_DOWN 4 An endpoint set by flag or config was shut down - by its operator; unset it - OTHER_SDK_SET 1 The process runs one SDK set's engine and the - network runs on the other (an MCP server that - served rc now asked for stagenet); start a - server for that network - MIXED_SDK_LAYOUT 1 mn was installed without its shrinkwrap (bun's - installer): install it with npm - NO_STATE_ROOT 1 The host gave mn no place to keep its state - (a program's createHost without paths) - NO_PAYER 1 A command that submits a transaction was - called without a payer - COMMAND_FAILED 1 A command ended with a non-zero exit code - (an MCP test run whose tests failed); the - message carries its result - NOT_AN_OFFER 2 The bytes given as a swap offer are not one; - ask the maker for it again - TERMS_MISMATCH 2 A swap offer's own terms differ from the agreed - ones; don't take it - OFFER_EXPIRED 2 A swap offer is past the expiry its maker set; - ask the maker for a new one - OFFER_COINS_IN_USE 2 A spend would use coins an open swap offer of - this wallet's holds; cancel the offer first - CANCELLED 7 Operation cancelled (SIGINT) - UNKNOWN 1 Unclassified error -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 20, - body: `| \`NETWORK_ERROR\` | Indexer/node/proof-server connection refused or DNS failure. | Check \`midnight_localnet_status()\` or the endpoints the user configured; on this build \`midnight_localnet_up()\` is refused, so ask the user to start their ledger-9 stack. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 60, - body: `| \`AMBIGUOUS_LOCAL_STACKS\` | Several local Midnight stacks are running and no endpoints are configured, so mn won't guess. | Ask the user which stack to use; they set its endpoints with \`midnight config set\`. Don't retry blindly. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 90, - body: `| \`WRONG_PASSPHRASE\` | \`MN_PASSPHRASE\` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | Ask the user to correct \`MN_PASSPHRASE\` in the MCP server's environment. Nothing was changed. | -| \`BLOCKFROST_PROJECT_ID_REQUIRED\` | The network (preprod) is served by Blockfrost and no project id is set. | Ask the user to create a Midnight preprod project at https://blockfrost.io and run \`midnight config set blockfrost-project-id \` themselves. Never ask them to paste the id into the chat. Don't retry until they have. | -| \`BLOCKFROST_PROJECT_ID_REJECTED\` | Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network. | Ask the user to check it at blockfrost.io and set it again. Don't retry blindly. | -| \`BLOCKFROST_LIMIT_REACHED\` | Blockfrost's plan limit or rate limit. | Wait and retry once; if it persists, tell the user it is their Blockfrost plan. | -| \`ENDPOINT_SHUT_DOWN\` | An endpoint set by flag or config was shut down by its operator (the old preprod indexer). | \`midnight_config_unset({ key: "indexer-ws" })\` (and \`node\` if set), then retry. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 110, - body: `| \`INVALID_ARGS\` | Missing/invalid argument. | Show the message to the user verbatim — it names the missing field. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 130, - body: `| \`CANCELLED\` | Operation was aborted (SIGINT, or the MCP call was cancelled). | A transaction already submitted may still have landed: read the state first (\`midnight_grant_status\`, \`midnight_balance\`). Don't retry without confirming with the user. | -| \`UNKNOWN\` | Error didn't match any known classifier. | Surface the message to the user. If reproducible, a new code may be warranted. | -`, - }, + // Its error codes' rows in the manual and the full skill, from their definitions. + ...codeGuidancePieces(coreCodes), ], toolsTable: [ { tool: 'midnight_config_get', group: 'configuration', order: 10, description: ['Read a config value'] }, diff --git a/packages/cli-core/src/lib/agent-guidance.ts b/packages/cli-core/src/lib/agent-guidance.ts index 54df86a0..b5d3e1e6 100644 --- a/packages/cli-core/src/lib/agent-guidance.ts +++ b/packages/cli-core/src/lib/agent-guidance.ts @@ -7,6 +7,10 @@ // reads in the order their places give. An error code's row sits with the // package whose code raises it; text about no one package's commands // (concepts, networks, safety, JSON, the MCP server) stays with the assembler. +// A package's error-code rows are made from its code definitions +// (codeGuidancePieces), never written by hand. + +import type { CodeDefinition } from './error-codes.ts'; /** The texts agents read: the `help --agent` manual, and the core and full skills. */ export type GuidanceText = 'agent-manual' | 'skill-core' | 'skill-full'; @@ -117,3 +121,63 @@ export function assembleGuidance(text: GuidanceText, sections: readonly string[] .map((piece) => piece.body) .join(''); } + +// The manual's table of codes: the code in a column of 24, its exit code, and +// the meaning from column 32, wrapped at 48 characters; a code too long for +// its column puts its exit code beside it and the meaning on the next line. +const CODE_COLUMN = 24; +const MEANING_COLUMN = 32; +const MEANING_WIDTH = 48; + +/** `text` in lines of at most `width` characters, broken between words (a word longer than that keeps a line of its own). */ +export function wrapWords(text: string, width: number): string[] { + const lines: string[] = []; + let line = ''; + for (const word of text.split(/\s+/).filter((w) => w !== '')) { + if (line === '') line = word; + else if (line.length + 1 + word.length <= width) line += ' ' + word; + else { + lines.push(line); + line = word; + } + } + if (line !== '') lines.push(line); + return lines; +} + +/** A code's row in the `help --agent` manual's table: code, exit code, and its summary as the meaning. */ +export function manualCodeRow(definition: CodeDefinition): string { + const [first = '', ...rest] = wrapWords(definition.summary, MEANING_WIDTH); + const indent = ' '.repeat(MEANING_COLUMN); + const head = definition.code.length < CODE_COLUMN + ? ` ${definition.code.padEnd(CODE_COLUMN)}${definition.exitCode}` + : ` ${definition.code} ${definition.exitCode}`; + const lines = head.length < MEANING_COLUMN + ? [`${head.padEnd(MEANING_COLUMN)}${first}`, ...rest.map((line) => indent + line)] + : [head, ...[first, ...rest].map((line) => indent + line)]; + return lines.join('\n') + '\n'; +} + +/** A code's row in the full skill's table of error recovery recipes: code, summary, recovery. */ +export function skillCodeRow(definition: CodeDefinition): string { + // A pipe splits a table cell, inside a code span too, unless escaped. + const cell = (text: string): string => text.replaceAll('|', '\\|'); + return `| \`${definition.code}\` | ${cell(definition.summary)} | ${cell(definition.recovery ?? '')} |\n`; +} + +/** + * A package's error-code rows, from its code definitions: each code's row in + * the manual's 'error-codes' section and in the full skill's 'error-recovery' + * table, placed by its `order`. Refuses a code with no order (its rows would + * have no place) or no recovery (its recipe would be empty). + */ +export function codeGuidancePieces(codes: readonly CodeDefinition[]): GuidancePiece[] { + return codes.flatMap((definition) => { + if (definition.order === undefined) throw new GuidanceError(`Error code "${definition.code}" has no order, so its rows have no place`); + if (definition.recovery === undefined) throw new GuidanceError(`Error code "${definition.code}" has no recovery for its recipe`); + return [ + { text: 'agent-manual', section: 'error-codes', order: definition.order, body: manualCodeRow(definition) }, + { text: 'skill-full', section: 'error-recovery', order: definition.order, body: skillCodeRow(definition) }, + ] satisfies GuidancePiece[]; + }); +} diff --git a/packages/cli-core/src/lib/error-codes.ts b/packages/cli-core/src/lib/error-codes.ts index 5e5c60c6..21e354d6 100644 --- a/packages/cli-core/src/lib/error-codes.ts +++ b/packages/cli-core/src/lib/error-codes.ts @@ -8,11 +8,11 @@ export interface CodeDefinition { readonly code: string; readonly exitCode: number; - /** What went wrong, in one line. */ + /** What went wrong: the meaning the code tables give it (the manuals', the full skill's, docs/JSON_CONTRACT.md's). */ readonly summary: string; - /** What to do about it. */ + /** What an agent does about it: the full skill's recovery recipe. */ readonly recovery?: string; - /** Its place in the manual's table of codes: rows read in ascending order. */ + /** Its place in the code tables: rows read in ascending order. A code shown to agents needs it (codeGuidancePieces). */ readonly order?: number; } diff --git a/packages/cli-core/src/lib/errors.ts b/packages/cli-core/src/lib/errors.ts index a74be472..9962e27f 100644 --- a/packages/cli-core/src/lib/errors.ts +++ b/packages/cli-core/src/lib/errors.ts @@ -31,7 +31,7 @@ export function isUsageError(err: unknown): err is UsageError { return err instanceof UsageError; } -/** What a cancelled operation fails with; exit-codes' classifyError reads it as CANCELLED. */ +/** The message a cancelled operation fails with (a CancelledError's, unless it says more). */ export const CANCELLED_MESSAGE = 'Operation cancelled'; /** A cancelled call: the cancellation error, typed with its code. */ diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index 57d8fdf9..8e69e8df 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -1,4 +1,3 @@ -import { CANCELLED_MESSAGE, isUsageError } from './errors.ts'; import type { CodeRegistry } from './error-codes.ts'; // Structured exit codes and error classification for CLI // Used by both JSON mode and non-JSON error reporting @@ -88,21 +87,6 @@ export const ERROR_CODES = { UNKNOWN: 'UNKNOWN', } as const; -/** Errors the caller fixes (mn's passphrase, an offer that isn't the agreed one), classified by their code before any usage error. */ -const CALLER_ERROR_CODES: ReadonlySet = new Set([ERROR_CODES.WRONG_PASSPHRASE, ERROR_CODES.PASSPHRASE_REQUIRED, ERROR_CODES.NOT_AN_OFFER, ERROR_CODES.TERMS_MISMATCH, ERROR_CODES.OFFER_EXPIRED, ERROR_CODES.OFFER_COINS_IN_USE]); - -/** Typed setup errors that carry their own `code`; classified by it, not by message text. */ -const SETUP_ERROR_CODES: ReadonlySet = new Set([ - ERROR_CODES.UNSUPPORTED_LEDGER, - ERROR_CODES.LOCALNET_UNAVAILABLE, - ERROR_CODES.LOCAL_STACK_UNREACHABLE, - ERROR_CODES.AMBIGUOUS_LOCAL_STACKS, - ERROR_CODES.BLOCKFROST_PROJECT_ID_REQUIRED, - ERROR_CODES.BLOCKFROST_PROJECT_ID_REJECTED, - ERROR_CODES.BLOCKFROST_LIMIT_REACHED, - ERROR_CODES.ENDPOINT_SHUT_DOWN, -]); - /** @deprecated A code is a string a package defines; see ERROR_CODES. */ export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES]; @@ -113,172 +97,22 @@ interface ClassifiedError { } /** - * The error's code and the exit code it ends the CLI with. An error that - * carries a code `codes` defines is classified by it; any other falls back to - * the rules below, which read its message. + * The error's code and the exit code it ends the CLI with: the definition of + * the code it carries, among those `codes` defines (the installed packages', + * a plugin's included); UNKNOWN (exit 1) for an error that carries none of + * them. Only its `code` is read, never its message. */ -export function classifyError(err: Error, codes?: CodeRegistry): ClassifiedError { - return (codes === undefined ? undefined : byCode(err, codes)) ?? legacyByMessage(err); -} - -/** - * The classification by the error's code alone: UNKNOWN for an error that - * carries no code `codes` defines, whatever its message says. Tests use it to - * check that a typed error reports its code without the message rules. - */ -export function classifyByCode(err: Error, codes: CodeRegistry): ClassifiedError { - return byCode(err, codes) ?? { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN }; -} - -/** The definition of the code `err` carries, as an exit code and code; undefined when `codes` defines none. */ -function byCode(err: Error, codes: CodeRegistry): ClassifiedError | undefined { +export function classifyError(err: Error, codes: CodeRegistry): ClassifiedError { const code = (err as { code?: unknown }).code; const defined = typeof code === 'string' ? codes.code(code) : undefined; - return defined === undefined ? undefined : { exitCode: defined.exitCode, errorCode: defined.code }; + return defined === undefined + ? { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN } + : { exitCode: defined.exitCode, errorCode: defined.code }; } -/** - * The classification before codes were owned per package, unchanged: the - * typed codes it knew, then patterns over the message from the CLI and the - * Midnight SDK. Order matters: more specific patterns are checked before - * broader ones. - */ -function legacyByMessage(err: Error): ClassifiedError { - // A usage error is the caller's to fix, whatever its text (the CLI and MCP agree on this). - // (Tested through `unknown`: UsageError has Error's shape, so narrowing `err` itself would leave `never`.) - const code = (err as { code?: unknown }).code; - if (typeof code === 'string' && CALLER_ERROR_CODES.has(code)) { - return { exitCode: EXIT_INVALID_ARGS, errorCode: code as ErrorCode }; - } - if (isUsageError(err as unknown)) { - return { exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }; - } - if (typeof code === 'string' && SETUP_ERROR_CODES.has(code)) { - return { exitCode: EXIT_NETWORK_ERROR, errorCode: code as ErrorCode }; - } - if (code === ERROR_CODES.UNSUPPORTED_NODE) { - return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNSUPPORTED_NODE }; - } - if (code === ERROR_CODES.MIXED_SDK_LAYOUT) { - return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.MIXED_SDK_LAYOUT }; - } - if (code === ERROR_CODES.OTHER_SDK_SET) { - return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.OTHER_SDK_SET }; - } - if (code === ERROR_CODES.NO_ACCOUNT) { - return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.NO_ACCOUNT }; - } - if (code === ERROR_CODES.DUST_GENERATING) { - return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_GENERATING }; - } - if (code === ERROR_CODES.CANCELLED) { - return { exitCode: EXIT_CANCELLED, errorCode: ERROR_CODES.CANCELLED }; - } - if (code === ERROR_CODES.CHAIN_CLOCK_BEHIND) { - return { exitCode: EXIT_NETWORK_ERROR, errorCode: ERROR_CODES.CHAIN_CLOCK_BEHIND }; - } - - const msg = (err.message ?? '').toLowerCase(); - - // Cancelled by user (SIGINT / AbortController) - if (msg.includes(CANCELLED_MESSAGE.toLowerCase()) || msg.includes('operation aborted') || msg === 'cancelled' || msg === 'aborted') { - return { exitCode: EXIT_CANCELLED, errorCode: ERROR_CODES.CANCELLED }; - } - - // Wallet file not found - if (msg.includes('wallet file not found') || (msg.includes('wallet') && msg.includes('not found'))) { - return { exitCode: EXIT_WALLET_NOT_FOUND, errorCode: ERROR_CODES.WALLET_NOT_FOUND }; - } - - // Invalid arguments / usage errors - if ( - msg.includes('missing required flag') || - msg.includes('missing amount') || - msg.includes('missing recipient') || - msg.includes('missing config key') || - msg.includes('missing or invalid subcommand') || - msg.includes('unknown command') || - msg.includes('cannot specify both') || - msg.includes('invalid bip-39') || - msg.includes('seed must be') || - msg.includes('key index must be') || - msg.includes('shielded balances are private') || - msg.includes('shielded is unavailable') || - msg.includes('belongs to') && msg.includes('--network is') || - msg.includes('usage:') - ) { - return { exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }; - } - - // Proof timeout (before general timeout/dust checks) - if (msg.includes('proof') && msg.includes('timeout')) { - return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.PROOF_TIMEOUT }; - } - - // Stale UTXO — match the specific error code from the Midnight node - if (msg.includes('stale utxo') || msg.includes('error code 115') || msg.includes('custom error: 115') || msg.includes('errorcode: 115')) { - return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.STALE_UTXO }; - } - - // Invalid dust spend proof — substrate "Custom error 170". Distinct from - // PROOF_FAILURE because the recovery is "clear cache" not "retry". - if (msg.includes('error 170') || msg.includes('error: 170') || msg.includes('errorcode: 170') || msg.includes('invaliddustspendproof')) { - return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.INVALID_DUST_PROOF }; - } - - // Stale local cache (e.g. `applied > highest`, `chainId mismatch`) - // "inserted non-linearly": state resumed against an indexer that numbers its events differently. - if (msg.includes('stale cache') || msg.includes('chain reset') || msg.includes('chainid mismatch') || msg.includes('applied > highest') || msg.includes('inserted non-linearly')) { - return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.STALE_CACHE }; - } - - // Proof server failure — SDK ClientError "Failed to prove transaction". - if (msg.includes('failed to prove')) { - return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.PROOF_FAILURE }; - } - - // Sync timeouts — wallet sync, dust waits, indexer waits. - if ( - msg.includes('wallet sync timed out') || - msg.includes('sync timed out') || - msg.includes('timed out waiting for dust') || - msg.includes('did not respond within') || - msg.includes('did not produce a block') || - msg.includes('did not report funds') - ) { - return { exitCode: EXIT_NETWORK_ERROR, errorCode: ERROR_CODES.SYNC_TIMEOUT }; - } - - // Dust required — match specific dust-related failures - if (msg.includes('no dust') || msg.includes('dust') && (msg.includes('required') || msg.includes('available') || msg.includes('insufficient'))) { - return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_REQUIRED }; - } - - // Insufficient balance - if (msg.includes('insufficient') || msg.includes('not enough')) { - return { exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.INSUFFICIENT_BALANCE }; - } - - // Transaction rejected: by the node (its words in the message, when no rule above knew them), or as the message says. - if ((err as { name?: unknown }).name === 'TransactionRefusedError' || msg.includes('rejected') || msg.includes('transaction failed')) { - return { exitCode: EXIT_TX_REJECTED, errorCode: ERROR_CODES.TX_REJECTED }; - } - - // Network / connection errors - if ( - msg.includes('econnrefused') || - msg.includes('enotfound') || - msg.includes('etimedout') || - msg.includes('websocket') || - msg.includes('connection refused') || - msg.includes('request to ') && msg.includes(' failed, reason:') || - (msg.includes('network') && msg.includes('error')) - ) { - return { exitCode: EXIT_NETWORK_ERROR, errorCode: ERROR_CODES.NETWORK_ERROR }; - } - - // Fallback - return { exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN }; +/** @deprecated The same as classifyError, now that every classification is by code alone. */ +export function classifyByCode(err: Error, codes: CodeRegistry): ClassifiedError { + return classifyError(err, codes); } /** diff --git a/packages/cli-core/src/lib/sdk-errors.ts b/packages/cli-core/src/lib/sdk-errors.ts index 433e9df6..5978b88d 100644 --- a/packages/cli-core/src/lib/sdk-errors.ts +++ b/packages/cli-core/src/lib/sdk-errors.ts @@ -1,5 +1,7 @@ // The engine contract's reading of the SDK's and the node's errors: the one -// place mn recognises their shapes and words. An engine reports each failure +// place mn recognises their shapes and words (a connection that could not be +// made it reads through transport-failure.ts, which a contract script's +// process shares). An engine reports each failure // it can name as a typed error carrying its code (toEngineError), and its DApp // connector marks the errors it answers with by their code, keeping their // messages (withEngineCode). Only the engines, and in core the wallet session and the Dust wait, import @@ -10,6 +12,7 @@ import { EngineError, InsufficientBalanceError, InvalidDustProofError, + NetworkError, ProofFailureError, ProofTimeoutError, StaleUtxoError, @@ -18,6 +21,7 @@ import { TransactionRefusedError, type RefusalCode, } from './errors.ts'; +import { carriesOwnCode, isTransportFailure } from './transport-failure.ts'; /** * The chain rejected the transaction outright. Most commonly: balance check @@ -226,6 +230,8 @@ function engineCodeOf(err: unknown): string | undefined { if (isDustShortage(err) || said.includes('no dust') || (said.includes('dust') && (said.includes('required') || said.includes('available') || said.includes('insufficient')))) return 'DUST_REQUIRED'; if (isSdkInsufficientFundsError(err) || said.includes('insufficient') || said.includes('not enough')) return 'INSUFFICIENT_BALANCE'; if (said.includes('rejected') || said.includes('transaction failed')) return 'TX_REJECTED'; + // The node, the indexer or the proof server out of reach: last, as a refusal's or a proof's words come first. + if (isTransportFailure(err)) return 'NETWORK_ERROR'; return undefined; } @@ -241,6 +247,7 @@ function typedEngineError(code: string, message: string, cause: unknown): Error case 'SYNC_TIMEOUT': return new SyncTimeoutError(message, options); case 'DUST_REQUIRED': return new DustRequiredError(message, options); case 'INSUFFICIENT_BALANCE': return new InsufficientBalanceError(message, options); + case 'NETWORK_ERROR': return new NetworkError(message, options); default: return new EngineError(code, message, options); } } @@ -257,9 +264,8 @@ export function mnCodeOf(err: unknown): string | undefined { const isConnectorApiError = (err: unknown): boolean => err !== null && typeof err === 'object' && (err as { type?: unknown }).type === 'DAppConnectorAPIError'; -/** Whether the error already carries a code of its own (mn's typed errors do); a connector API error's code is the API's, not mn's. */ -const carriesCode = (err: unknown): boolean => - !isConnectorApiError(err) && err !== null && typeof err === 'object' && typeof (err as { code?: unknown }).code === 'string'; +/** Whether the error already carries a code of its own (mn's typed errors do); a connector API error's code is the API's, and a socket's ECONNREFUSED the transport's, not mn's. */ +const carriesCode = (err: unknown): boolean => !isConnectorApiError(err) && carriesOwnCode(err); /** * The failure as an engine reports it to mn: a node's refusal as a diff --git a/packages/cli-core/src/lib/transport-failure.ts b/packages/cli-core/src/lib/transport-failure.ts new file mode 100644 index 00000000..ba983196 --- /dev/null +++ b/packages/cli-core/src/lib/transport-failure.ts @@ -0,0 +1,55 @@ +// A connection that could not be made (refused, a host not found, timed out), +// recognised where mn meets code that doesn't name its failures: the engine +// boundary (sdk-errors.ts), a contract script's process, and grant's account +// package. Classification itself reads only an error's code. + +import { NetworkError } from './errors.ts'; + +/** + * Whether the failure is a connection that could not be made: a transport's + * code for it (ECONNREFUSED, ENOTFOUND, ETIMEDOUT) on the failure or among its + * causes, an ErrorEvent's error or an AggregateError's members (where fetch + * keeps them); or the words the SDK and its transports say it with in the + * failure's own message ("fetch failed", a WebSocket error, node-fetch's + * "request to … failed, reason:"). Self-contained, with nothing from outside + * its body: a contract script's prelude carries it as its source text. + */ +export function isTransportFailure(failure: unknown): boolean { + const TRANSPORT_CODES = ['ECONNREFUSED', 'ENOTFOUND', 'ETIMEDOUT']; + const TRANSPORT_WORDS = ['econnrefused', 'enotfound', 'etimedout', 'websocket', 'connection refused', 'fetch failed']; + const seen = new Set(); + const pending: unknown[] = [failure]; + while (pending.length > 0) { + const current = pending.shift(); + if (current === null || typeof current !== 'object' || seen.has(current)) continue; + seen.add(current); + const e = current as { code?: unknown; cause?: unknown; error?: unknown; errors?: unknown }; + if (typeof e.code === 'string' && TRANSPORT_CODES.includes(e.code)) return true; + pending.push(e.cause, e.error, ...(Array.isArray(e.errors) ? e.errors : [])); + } + let message = ''; + try { + const said = (failure as { message?: unknown } | null)?.message; + message = typeof said === 'string' ? said.toLowerCase() : ''; + } catch { /* a message that can't be read says nothing */ } + return TRANSPORT_WORDS.some((word) => message.includes(word)) + || /request to \S+ failed, reason:/.test(message) + || (message.includes('network') && message.includes('error')); +} + +/** Whether the failure carries a code of its own: a string `code` that is not a transport's (ECONNREFUSED is the socket's, not mn's). */ +export function carriesOwnCode(failure: unknown): boolean { + const code = failure !== null && typeof failure === 'object' ? (failure as { code?: unknown }).code : undefined; + return typeof code === 'string' && !isTransportFailure({ code }); +} + +/** + * The failure as reported at a boundary with no engine (grant's account + * package): a transport failure that carries no code of its own as a + * NetworkError, with its message and the failure as its cause; anything else + * as it is. + */ +export function withTransportCode(err: unknown): unknown { + if (!(err instanceof Error) || carriesOwnCode(err) || !isTransportFailure(err)) return err; + return new NetworkError(err.message, { cause: err }); +} diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index c19f4752..e9140505 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -29,7 +29,7 @@ const HOMES = [ ['shell', /^wallet\.ts$/], // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], - ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands)\.ts$/], + ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|code-tables)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], @@ -42,7 +42,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], diff --git a/scripts/write-readme-commands.ts b/scripts/write-readme-commands.ts index e00bbe17..0197ef28 100644 --- a/scripts/write-readme-commands.ts +++ b/scripts/write-readme-commands.ts @@ -1,5 +1,7 @@ -// Writes the README's table of commands from the installed commands' -// definitions, between its markers. A test fails when the README differs. +// Writes the generated tables of the README and docs/JSON_CONTRACT.md between +// their markers: the README's table of commands, from the installed commands' +// definitions, and the contract's table of error codes, from the installed +// packages' code definitions. A test fails when either file differs. // // Usage: npm run readme-commands @@ -8,8 +10,13 @@ import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { installedCommands } from '../src/lib/installed-commands.ts'; import { readmeCommandTable, withReadmeCommandTable } from '../src/lib/readme-commands.ts'; +import { jsonContractCodeTable, withJsonContractCodeTable } from '../src/lib/code-tables.ts'; -const README = join(resolve(dirname(fileURLToPath(import.meta.url)), '..'), 'README.md'); +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const README = join(ROOT, 'README.md'); +const JSON_CONTRACT = join(ROOT, 'docs', 'JSON_CONTRACT.md'); writeFileSync(README, withReadmeCommandTable(readFileSync(README, 'utf8'), readmeCommandTable(installedCommands))); process.stdout.write('wrote README.md\n'); +writeFileSync(JSON_CONTRACT, withJsonContractCodeTable(readFileSync(JSON_CONTRACT, 'utf8'), jsonContractCodeTable(installedCommands))); +process.stdout.write('wrote docs/JSON_CONTRACT.md\n'); diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index df32bdf9..af68f29f 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -15,7 +15,8 @@ import { type CommandPackage, type CommandRegistry, } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { GuidanceError, assembleGuidance, manualCodeRow, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { chainCodes } from '@kuiralabs/midnight-chain/commands/chain.codes'; import { AGENT_MANUAL_SECTIONS, TOOL_GROUPS, agentManual } from '../lib/agent-manual.ts'; import { SKILL_CORE_SECTIONS, SKILL_FULL_SECTIONS, skillCore, skillFull } from '../lib/mcp/skills.ts'; import { listedTools } from '../lib/mcp/registry-tools.ts'; @@ -247,7 +248,9 @@ describe('the texts, assembled from the installed packages', () => { const manual = agentManual(withoutPackage('dev')); const codes = manual.split('ERROR CODES')[1]!.split('MCP SERVER')[0]!; expect(codes).not.toContain('LOCALNET_UNAVAILABLE'); - expect(codes).toContain('UNSUPPORTED_LEDGER 4 The chain is on ledger 8; use mn 0.5.x for it\n LOCAL_STACK_UNREACHABLE 4'); + // dev's code (order 160) is gone from between chain's two (150 and 170). + const ledger = chainCodes.find((definition) => definition.code === 'UNSUPPORTED_LEDGER')!; + expect(codes).toContain(`${manualCodeRow(ledger)} LOCAL_STACK_UNREACHABLE 4`); expect(manual).not.toContain('E2E TESTING'); }); }); diff --git a/src/__tests__/blockfrost.test.ts b/src/__tests__/blockfrost.test.ts index 21c0a9d0..8d659d18 100644 --- a/src/__tests__/blockfrost.test.ts +++ b/src/__tests__/blockfrost.test.ts @@ -11,6 +11,7 @@ import { } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { ERROR_CODES, EXIT_NETWORK_ERROR, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const WITH_ID = blockfrostEndpoints('preprod', ID); @@ -144,7 +145,7 @@ describe('the errors\' codes', () => { [new EndpointShutDownError('https://indexer.preprod.midnight.network/api/v4/graphql'), ERROR_CODES.ENDPOINT_SHUT_DOWN], ]; for (const [error, errorCode] of cases) { - expect(classifyError(error)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode }); + expect(classifyError(error, installedCommands)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode }); } }); }); diff --git a/src/__tests__/chain-clock.test.ts b/src/__tests__/chain-clock.test.ts index 70aae538..f50c2375 100644 --- a/src/__tests__/chain-clock.test.ts +++ b/src/__tests__/chain-clock.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { ChainClockBehindError, CHAIN_CLOCK_TOLERANCE_MS, assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; import { classifyError, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; const LAGGING_BLOCK = 1_791_116_964_002; // 2026-10-04T12:29:24.002Z @@ -36,7 +37,7 @@ describe('assertChainClockCurrent', () => { + '2026-10-04T12:29:24.002Z). Dust is generated in chain time, so a registration now would be refused for an unpaid fee. ' + 'A local chain falls behind like this after the machine sleeps and catches up as it produces blocks: run midnight dust ' + 'register again once it has, or restart the local chain.'); - expect(classifyError(err)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode: 'CHAIN_CLOCK_BEHIND' }); + expect(classifyError(err, installedCommands)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode: 'CHAIN_CLOCK_BEHIND' }); }); it('accepts a chain within the tolerance, or ahead', () => { diff --git a/src/__tests__/classify-reads-no-message.test.ts b/src/__tests__/classify-reads-no-message.test.ts new file mode 100644 index 00000000..6a775381 --- /dev/null +++ b/src/__tests__/classify-reads-no-message.test.ts @@ -0,0 +1,58 @@ +// Classification reads an error's code and nothing else: an error whose +// message can't even be read is classified, and the modules that classify +// (exit-codes.ts, error-codes.ts) never read a message, which the source +// itself shows. + +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { DustRequiredError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { installedCommands } from '../lib/installed-commands.ts'; + +/** `error` with a message getter that throws, as an object from a broken bridge can have. */ +function unreadable(error: E): E { + return Object.defineProperty(error, 'message', { get() { throw new Error('the message cannot be read'); } }); +} + +describe('classifying an error whose message cannot be read', () => { + it('classifies it by its code', () => { + const err = unreadable(new DustRequiredError('Dust not available')); + expect(() => err.message).toThrow('the message cannot be read'); + expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + }); + + it('classifies one with no code as UNKNOWN', () => { + expect(classifyError(unreadable(new Error('Wallet file not found')), installedCommands)).toStrictEqual({ errorCode: 'UNKNOWN', exitCode: 1 }); + }); +}); + +const CORE_LIB = join(resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'), 'packages', 'cli-core', 'src', 'lib'); + +/** Each place the source reads a property named `message`: `x.message`, `x?.message`, `x['message']`, or `{ message } = x`. */ +function messageReads(file: string): string[] { + const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true); + const found: string[] = []; + const visit = (node: ts.Node): void => { + const reads = (ts.isPropertyAccessExpression(node) && node.name.text === 'message') + || (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) && node.argumentExpression.text === 'message') + || (ts.isBindingElement(node) && (node.propertyName ?? node.name).getText(source) === 'message'); + if (reads) found.push(`${file}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1}: ${node.getText(source)}`); + ts.forEachChild(node, visit); + }; + visit(source); + return found; +} + +describe('the modules that classify', () => { + it.each(['exit-codes.ts', 'error-codes.ts'])('%s reads no message', (name) => { + expect(messageReads(join(CORE_LIB, name))).toStrictEqual([]); + }); + + it('would find a message read', () => { + // The check itself, on a module that does read messages (the engine boundary). + expect(messageReads(join(CORE_LIB, 'sdk-errors.ts')).length).toBeGreaterThan(0); + }); +}); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index af2e6c0b..64418409 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -157,7 +157,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => cancelled.abort(); const err = await run('plain', { ...provisions, signal: cancelled.signal }).catch((e: unknown) => e); expect(err).toBeInstanceOf(CancelledError); - expect(classifyError(err as Error)).toStrictEqual({ exitCode: EXIT_CANCELLED, errorCode: 'CANCELLED' }); + expect(classifyError(err as Error, installedCommands)).toStrictEqual({ exitCode: EXIT_CANCELLED, errorCode: 'CANCELLED' }); expect(received).toStrictEqual([]); expect(results).toStrictEqual([]); }); diff --git a/src/__tests__/contract-runtime-check.test.ts b/src/__tests__/contract-runtime-check.test.ts index cf06cc0a..50dcf194 100644 --- a/src/__tests__/contract-runtime-check.test.ts +++ b/src/__tests__/contract-runtime-check.test.ts @@ -7,6 +7,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; @@ -42,7 +43,7 @@ describe('a contract for another compact runtime', () => { expect((refused as Error).message).toBe( 'counter was compiled by compactc 0.30.0 for compact-runtime 0.16.0, but undeployed runs contracts on compact-runtime 0.20.0.\nRecompile it with compactc 0.35.', ); - expect(classifyError(refused as Error).errorCode).toBe('INVALID_ARGS'); + expect(classifyError(refused as Error, installedCommands).errorCode).toBe('INVALID_ARGS'); }); it('lets through one compiled for the engine\'s runtime, and one whose compiler recorded none', async () => { diff --git a/src/__tests__/contract-script-errors.test.ts b/src/__tests__/contract-script-errors.test.ts index df58a8ed..2498560e 100644 --- a/src/__tests__/contract-script-errors.test.ts +++ b/src/__tests__/contract-script-errors.test.ts @@ -8,12 +8,15 @@ import { spawnSync } from 'node:child_process'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { closedPort } from './helpers/closed-port.ts'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; -import { ContractScriptError, SCRIPT_PRELUDE, scriptFailureMessage, scriptFailureOf } from '../lib/contract/runner.ts'; +import { ContractScriptError, SCRIPT_PRELUDE, executeScript, rpcClientCode, scriptFailureMessage, scriptFailureOf } from '../lib/contract/runner.ts'; import { createApiError } from '../lib/ws-rpc.ts'; import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; -import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { withEngineCode } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { installedCommands } from '../lib/installed-commands.ts'; @@ -62,6 +65,33 @@ await Promise.reject(new TypeError('Expected an input string with byte length of expect(scriptFailureOf(runScript(`throw new Error('no code');`).stderr, 1)).toStrictEqual({ message: 'no code' }); }); + it('reports a connection it could not make as NETWORK_ERROR, and a code it carries before that', async () => { + const refused = runScript(`throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:6300'), { code: 'ECONNREFUSED' });`); + expect(scriptFailureOf(refused.stderr, refused.status)).toStrictEqual({ message: 'connect ECONNREFUSED 127.0.0.1:6300', code: 'NETWORK_ERROR' }); + // fetch says only "fetch failed"; its cause is the socket's ECONNREFUSED. + const fetched = runScript(`await fetch('http://127.0.0.1:${await closedPort()}/');`); + expect(scriptFailureOf(fetched.stderr, fetched.status)).toStrictEqual({ message: 'fetch failed', code: 'NETWORK_ERROR' }); + const served = runScript(`throw Object.assign(new Error('the WebSocket said a network error'), { code: 'DUST_REQUIRED' });`); + expect(scriptFailureOf(served.stderr, served.status)).toStrictEqual({ message: 'the WebSocket said a network error', code: 'DUST_REQUIRED' }); + }); + + it("reports mn serve out of reach as NETWORK_ERROR, from the script's own RPC client", async () => { + const dir = mkdtempSync(join(tmpdir(), 'mn-script-unserved-')); + try { + const wsModule = pathToFileURL(createRequire(import.meta.url).resolve('ws')).href; + const script = SCRIPT_PRELUDE + rpcClientCode(await closedPort(), wsModule) + 'await rpcConnect();\n'; + const err = await executeScript({ dir, script, overlaySdk: false, packages: { packages: [], packageFolder: () => null, set: 'rc' } }).then( + () => { throw new Error('expected the script to fail'); }, + (e: Error) => e, + ); + expect(err).toBeInstanceOf(ContractScriptError); + expect(err.message).toMatch(/^Cannot connect to mn serve at ws:\/\/127\.0\.0\.1:\d+: connect ECONNREFUSED/); + expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it("reads an older mn's script, which reported its message alone", () => { expect(scriptFailureOf('__MN_ERROR__ "the message"\n', 1)).toStrictEqual({ message: 'the message' }); }); @@ -76,7 +106,7 @@ describe("a failure at mn serve, across the wire and the script's process", () = const err = await failedRun(() => createApiError('InternalError', message, 'DUST_REQUIRED')); expect(err).toBeInstanceOf(ContractScriptError); expect(err.message).toBe(message); - expect(classifyByCode(err, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); }); it("carries a node's refusal by its reason (approved Y54: one with no rule's words was UNKNOWN)", async () => { @@ -88,9 +118,8 @@ describe("a failure at mn serve, across the wire and the script's process", () = }; const other = await refused('1010: Invalid Transaction: Custom error: 199'); expect(other.message).toBe('Transaction submission failed: [SubmissionError] Transaction submission error → 1010: Invalid Transaction: Custom error: 199'); - expect(classifyError(other)).toStrictEqual({ errorCode: 'UNKNOWN', exitCode: 1 }); - expect(classifyByCode(other, installedCommands)).toStrictEqual({ errorCode: 'TX_REJECTED', exitCode: 6 }); - expect(classifyByCode(await refused('1010: Invalid Transaction: Custom error: 115'), installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); - expect(classifyByCode(await refused('1010: Invalid Transaction: Custom error: 170'), installedCommands)).toStrictEqual({ errorCode: 'INVALID_DUST_PROOF', exitCode: 6 }); + expect(classifyError(other, installedCommands)).toStrictEqual({ errorCode: 'TX_REJECTED', exitCode: 6 }); + expect(classifyError(await refused('1010: Invalid Transaction: Custom error: 115'), installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + expect(classifyError(await refused('1010: Invalid Transaction: Custom error: 170'), installedCommands)).toStrictEqual({ errorCode: 'INVALID_DUST_PROOF', exitCode: 6 }); }); }); diff --git a/src/__tests__/dust-registration-plan.test.ts b/src/__tests__/dust-registration-plan.test.ts index 953a167f..55375232 100644 --- a/src/__tests__/dust-registration-plan.test.ts +++ b/src/__tests__/dust-registration-plan.test.ts @@ -6,6 +6,7 @@ import { describe, it, expect } from 'vitest'; import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; import { classifyError, EXIT_INSUFFICIENT_BALANCE } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; const FEE = 526_587_115_818_352n; const TWENTY_NIGHT = { dust: { generatedNow: 337_954_960_000_000n, rate: 165_340_000_000n, maxCap: 100_000_000_000_000_000n } }; @@ -61,7 +62,7 @@ describe('DustFeeNotGeneratedError', () => { }); it('exits as an insufficient balance, with its own error code', () => { - expect(classifyError(new DustFeeNotGeneratedError(planRegistration(FEE, [TWENTY_NIGHT]), now))) + expect(classifyError(new DustFeeNotGeneratedError(planRegistration(FEE, [TWENTY_NIGHT]), now), installedCommands)) .toEqual({ exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: 'DUST_GENERATING' }); }); }); diff --git a/src/__tests__/engine-beta-error-code-parity.test.ts b/src/__tests__/engine-beta-error-code-parity.test.ts index f1a84ecd..4f44a0c4 100644 --- a/src/__tests__/engine-beta-error-code-parity.test.ts +++ b/src/__tests__/engine-beta-error-code-parity.test.ts @@ -10,7 +10,6 @@ import { installedCommands } from '../lib/installed-commands.ts'; describe("the beta engine's stale cache", () => { it('reports STALE_CACHE (exit 6) through the installed codes, where the message alone gave UNKNOWN', () => { const err = new StaleCacheError('applied 120 of 80 events'); - expect(classifyError(err)).toStrictEqual({ exitCode: 1, errorCode: 'UNKNOWN' }); expect(classifyError(err, installedCommands)).toStrictEqual({ exitCode: 6, errorCode: 'STALE_CACHE' }); }); }); diff --git a/src/__tests__/error-code-docs.test.ts b/src/__tests__/error-code-docs.test.ts new file mode 100644 index 00000000..d684b817 --- /dev/null +++ b/src/__tests__/error-code-docs.test.ts @@ -0,0 +1,105 @@ +// The code tables are generated from the installed packages' code +// definitions: `help --agent`'s ERROR CODES, the full skill's error recovery +// recipes, `mn manual`'s EXIT CODES block and docs/JSON_CONTRACT.md's table. +// Each has one row for every registered code, in the codes' order, with its +// exit code, and no row for a code no package defines. + +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { codeGuidancePieces, GuidanceError, manualCodeRow, skillCodeRow, wrapWords } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import type { CodeDefinition } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { agentManual } from '../lib/agent-manual.ts'; +import { skillFull } from '../lib/mcp/skills.ts'; +import { buildManual } from '../commands/manual.ts'; +import { JSON_CONTRACT_CODES_END, JSON_CONTRACT_CODES_START, installedCodes, jsonContractCodeTable, withJsonContractCodeTable } from '../lib/code-tables.ts'; + +const JSON_CONTRACT = join(fileURLToPath(new URL('../..', import.meta.url)), 'docs', 'JSON_CONTRACT.md'); + +/** The text between `from` and the next `to` in `text`. */ +function between(text: string, from: string, to: string): string { + const start = text.indexOf(from); + expect(start).toBeGreaterThanOrEqual(0); + const end = text.indexOf(to, start + from.length); + expect(end).toBeGreaterThan(start); + return text.slice(start + from.length, end); +} + +/** Each row's code and exit code, as `pattern` (with the code and the exit code as its groups) finds them. */ +function rowsOf(table: string, pattern: RegExp): Array<[string, number]> { + return [...table.matchAll(pattern)].map((match) => [match[1]!, Number(match[2])]); +} + +const registered = installedCodes(installedCommands); +const expected: Array<[string, number]> = registered.map(({ code, exitCode }) => [code, exitCode]); + +describe('the code tables', () => { + it('know the codes every installed package defines, each with its order and recovery', () => { + expect(registered.length).toBeGreaterThan(30); + for (const definition of registered) { + expect(definition.order, definition.code).toBeTypeOf('number'); + expect(definition.recovery, definition.code).toBeTypeOf('string'); + } + expect(new Set(registered.map((definition) => definition.order)).size).toBe(registered.length); + }); + + it("help --agent's ERROR CODES: a row for every registered code and no other", () => { + const table = between(agentManual(installedCommands), 'ERROR CODES', 'MCP SERVER'); + // A code too long for its column has its exit code beside it and its meaning on the next line. + expect(rowsOf(table, /^ {2}([A-Z][A-Z0-9_]+) +(\d)\b/gm)).toStrictEqual(expected); + }); + + it("the full skill's error recovery recipes: a row for every registered code and no other", () => { + const table = between(skillFull(installedCommands), '## Error recovery recipes', '\n## '); + const rows = [...table.matchAll(/^\| `([A-Z0-9_]+)` \| (.*) \| (.*) \|$/gm)]; + expect(rows.map((row) => row[1])).toStrictEqual(registered.map(({ code }) => code)); + for (const [, code, summary, recovery] of rows) { + const definition = registered.find((d) => d.code === code)!; + expect([summary, recovery]).toStrictEqual([definition.summary, definition.recovery]); + } + }); + + it("mn manual's EXIT CODES: a line for every registered code and no other", () => { + // Without its colours. + const manual = buildManual().replace(/\x1b\[[0-9;]*m/g, ''); + const block = between(manual, 'EXIT CODES', 'TROUBLESHOOTING'); + expect(rowsOf(block, /^ {4}([A-Z][A-Z0-9_]+) +(\d) {2}/gm)).toStrictEqual(expected); + }); + + it("docs/JSON_CONTRACT.md's table: the generated one, byte for byte (npm run readme-commands writes it)", () => { + const doc = readFileSync(JSON_CONTRACT, 'utf8'); + expect(doc).toBe(withJsonContractCodeTable(doc, jsonContractCodeTable(installedCommands))); + expect(rowsOf(between(doc, JSON_CONTRACT_CODES_START, JSON_CONTRACT_CODES_END), /^\| `([A-Z0-9_]+)` \| (\d) \|/gm)).toStrictEqual(expected); + }); +}); + +describe('a code row', () => { + const ORACLE: CodeDefinition = { code: 'PLUGIN_ORACLE_DOWN', exitCode: 4, order: 500, summary: "The plugin's price oracle did not answer within the time it is given, which a busy oracle can take.", recovery: 'Retry later | or not.' }; + + it('wraps the meaning at 48 characters from column 32', () => { + expect(manualCodeRow(ORACLE)).toBe( + ' PLUGIN_ORACLE_DOWN 4 The plugin\'s price oracle did not answer within\n' + + ' the time it is given, which a busy oracle can\n' + + ' take.\n'); + expect(wrapWords('a b c', 3)).toStrictEqual(['a b', 'c']); + }); + + it('puts the exit code beside a long code and the meaning under it', () => { + expect(manualCodeRow({ ...ORACLE, code: 'PLUGIN_PRICE_ORACLE_UNREACHABLE', summary: 'No answer.' })) + .toBe(' PLUGIN_PRICE_ORACLE_UNREACHABLE 4\n No answer.\n'); + expect(manualCodeRow({ ...ORACLE, code: 'PLUGIN_ORACLE_UNREACHABLE', summary: 'No answer.' })) + .toBe(' PLUGIN_ORACLE_UNREACHABLE 4 No answer.\n'); + }); + + it("is the skill's recipe, a pipe escaped", () => { + expect(skillCodeRow(ORACLE)).toBe("| `PLUGIN_ORACLE_DOWN` | The plugin's price oracle did not answer within the time it is given, which a busy oracle can take. | Retry later \\| or not. |\n"); + }); + + it('is placed by its order in both texts, and refused without an order or a recovery', () => { + expect(codeGuidancePieces([ORACLE]).map(({ text, section, order }) => [text, section, order])).toStrictEqual([['agent-manual', 'error-codes', 500], ['skill-full', 'error-recovery', 500]]); + expect(() => codeGuidancePieces([{ ...ORACLE, order: undefined }])).toThrow(GuidanceError); + expect(() => codeGuidancePieces([{ ...ORACLE, recovery: undefined }])).toThrow(/no recovery/); + }); +}); diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index 036263c5..52db6311 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -1,22 +1,22 @@ // What each typed error, thrown where mn throws it, reports: its code and the -// exit code it ends the CLI with. Each row records the classification without -// the registry (what mn reported before codes were owned per package) and with -// the installed registry (what the shell and the MCP server report now). They -// differ only where the owner approved it (Y52): NO_STATE_ROOT, NO_PAYER and -// NO_NODE_RUNTIME by name instead of UNKNOWN, an escaped stale cache as -// STALE_CACHE, and a failed command run through MCP as COMMAND_FAILED; and -// (Y53) a wallet with no NIGHT as INSUFFICIENT_BALANCE and an unreachable -// indexer as NETWORK_ERROR, whatever their messages say; and (Y54) a ZK proof -// that timed out as PROOF_TIMEOUT, and a contract run's transaction the node -// refused as TX_REJECTED whatever its reason's words. A third -// classification reads the error's code alone, with no message rule: what the -// shell and the MCP server report once the rules are gone. +// exit code it ends the CLI with, classified by its code through the installed +// registry, as the shell and the MCP server classify it. Each row also records +// what mn reported before codes were owned per package, when the message rules +// still read an error's words (removed since; the record is kept, not +// computed). The two differ only on rows marked approved: (Y52) NO_STATE_ROOT, +// NO_PAYER and NO_NODE_RUNTIME by name instead of UNKNOWN, an escaped stale +// cache as STALE_CACHE, and a failed command run through MCP as +// COMMAND_FAILED; (Y53) a wallet with no NIGHT as INSUFFICIENT_BALANCE and an +// unreachable indexer, node or proof server as NETWORK_ERROR, whatever their +// messages say; and (Y54) a ZK proof that timed out as PROOF_TIMEOUT, and a +// contract run's transaction the node refused as TX_REJECTED whatever its +// reason's words. A test checks that every row that changed says so. import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { createApiError, OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; import { withEngineCode } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; @@ -33,6 +33,12 @@ import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; +import { closedPort } from './helpers/closed-port.ts'; +import { SCRIPT_PRELUDE, executeScript, rpcClientCode } from '../lib/contract/runner.ts'; +import { withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { WebSocket } from 'ws'; import { parseArgs, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { dustShortError } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; import { ProgramTimedOutError } from '@kuiralabs/midnight-cli-core/lib/exec-program'; @@ -160,6 +166,24 @@ const connectorRefusal = async (reason: string) => { return withEngineCode(new Error(`Transaction submission failed: [SubmissionError] Transaction submission error → ${reason}`, { cause: thrown })); }; +/** A socket's refusal: what a WebSocket to a closed port fails with (ECONNREFUSED its code). */ +async function refusedSocket(): Promise { + const port = await closedPort(); + return new Promise((resolve) => { new WebSocket(`ws://127.0.0.1:${port}`).on('error', resolve); }); +} +/** What the runner rejects with when a generated script, its prelude first, runs `body` and fails. */ +async function scriptFailing(body: (port: number) => string): Promise { + const dir = mkdtempSync(join(tmpdir(), 'mn-code-parity-script-')); + try { + const wsModule = pathToFileURL(createRequire(import.meta.url).resolve('ws')).href; + const port = await closedPort(); + await executeScript({ dir, script: SCRIPT_PRELUDE + rpcClientCode(port, wsModule) + body(port), overlaySdk: false, packages: { packages: [], packageFolder: () => null, set: 'rc' } }); + throw new Error('expected the script to fail'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + /** What the function throws; fails the test when it throws nothing. */ async function thrownBy(run: () => unknown): Promise { try { @@ -178,8 +202,8 @@ const TWENTY_NIGHT = { dust: { generatedNow: 337_954_960_000_000n, rate: 165_340 type Classified = { errorCode: string; exitCode: number }; const as = (errorCode: string, exitCode: number): Classified => ({ errorCode, exitCode }); -/** [where it is thrown, how to throw it, without the registry, with it, by its code alone (as with it, unless given)]. */ -type Row = [string, () => unknown, Classified, Classified, Classified?]; +/** [where it is thrown, how to throw it, what mn reported before codes were owned per package (a record), what it reports]. */ +type Row = [string, () => unknown, Classified, Classified]; const ROWS: Row[] = [ // The caller's to fix: exit 2. ['a usage error', () => { throw new UsageError('Missing required flag: --to'); }, as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], @@ -228,6 +252,12 @@ const ROWS: Row[] = [ ['an indexer subscription refused', () => subscribeGraphqlWs(CLOSED_WS, { query: 'subscription { x }', variables: {}, timeoutMs: 5_000, idleMs: 1_000, onNext: () => true, buildResult: () => undefined }), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], ['a balance read refused', () => checkBalance(ADDRESSES.undeployed, CLOSED_WS), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], ['an indexer query refused (approved: was UNKNOWN)', () => queryIndexer(`${CLOSED_HTTP}/`, '{ x }', undefined, 5_000), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], + // Connections the SDK, a contract script or the account package could not make, named where they are met. + ["a socket's refusal, through the engine", throughRcEngine(async () => { throw await refusedSocket(); }), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], + ['fetch failing, through the engine (approved Y53: was UNKNOWN)', throughRcEngine(async () => { await fetch(`http://127.0.0.1:${await closedPort()}/`); throw new Error('expected fetch to fail'); }), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], + ['a contract script that cannot reach mn serve', () => scriptFailing(() => 'await rpcConnect();\n'), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], + ["a contract script's fetch failing (approved Y53: was UNKNOWN)", () => scriptFailing((port) => `await fetch('http://127.0.0.1:${port}/');\n`), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], + ["the account package's refused connection, at grant's boundary", async () => { throw withTransportCode(await refusedSocket()); }, as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], // Approved: a program that ran past its limit keeps NETWORK_ERROR, which its message (ETIMEDOUT) gave it. ['a program past its time limit', () => { throw new ProgramTimedOutError('docker compose ps', 10_000); }, as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], @@ -285,10 +315,13 @@ const ROWS: Row[] = [ ]; describe('the code and exit code of each typed error', () => { - it.each(ROWS)('%s', async (_where, throwIt, before, now, byCode = now) => { - const err = await thrownBy(throwIt); - expect(classifyError(err)).toStrictEqual(before); - expect(classifyError(err, installedCommands)).toStrictEqual(now); - expect(classifyByCode(err, installedCommands)).toStrictEqual(byCode); + it.each(ROWS)('%s', async (_where, throwIt, _before, now) => { + expect(classifyError(await thrownBy(throwIt), installedCommands)).toStrictEqual(now); + }); + + it('marks every row whose code changed as approved', () => { + const changed = ROWS.filter(([, , before, now]) => before.errorCode !== now.errorCode || before.exitCode !== now.exitCode); + expect(changed.length).toBeGreaterThan(0); + for (const [where] of changed) expect(where).toMatch(/\(approved\b/); }); }); diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index ceae91cb..4a60c5ac 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -6,6 +6,9 @@ import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore' import { NoPassphraseError } from '../lib/passphrase.ts'; import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; import { MixedSdkLayoutError } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { installedCommands } from '../lib/installed-commands.ts'; describe('humanizeNetworkError', () => { it('rewrites the empty-reason node-fetch tail with URL + cause hint', () => { @@ -29,31 +32,25 @@ describe('humanizeNetworkError', () => { }); describe('classifyError network coverage', () => { - it('classifies the empty-reason node-fetch error as NETWORK_ERROR', () => { - const err = new Error('request to http://localhost:8088/api/v4/graphql failed, reason:'); - const { exitCode, errorCode } = classifyError(err); + it('classifies the empty-reason node-fetch error, read at the engine boundary, as NETWORK_ERROR', () => { + const err = toEngineError(new Error('request to http://localhost:8088/api/v4/graphql failed, reason:')) as Error; + const { exitCode, errorCode } = classifyError(err, installedCommands); expect(exitCode).toBe(EXIT_NETWORK_ERROR); expect(errorCode).toBe(ERROR_CODES.NETWORK_ERROR); }); }); describe('classifyError usage errors (positional-address balance)', () => { - it('classifies the "shielded balances are private" error as INVALID_ARGS', () => { - const err = new Error( - 'Shielded balances are private — they can only be read with the wallet\'s secret key, not from an address alone.\n' + - 'This address isn\'t one of your wallets. Check its shielded balance from the wallet that owns it:\n' + - ' midnight balance --wallet --shielded --network undeployed', - ); - const { exitCode, errorCode } = classifyError(err); - expect(exitCode).toBe(EXIT_INVALID_ARGS); - expect(errorCode).toBe(ERROR_CODES.INVALID_ARGS); - }); + // The balance command throws these as UsageErrors (error-code-parity.test.ts + // runs it); approved (Y52), their words alone no longer give INVALID_ARGS. + const PRIVATE = 'Shielded balances are private — they can only be read with the wallet\'s secret key, not from an address alone.\n' + + 'This address isn\'t one of your wallets. Check its shielded balance from the wallet that owns it:\n' + + ' midnight balance --wallet --shielded --network undeployed'; + const MISMATCH = 'Address belongs to undeployed but --network is preprod.\nDrop --network or pass an address for preprod.'; - it('classifies the address-HRP / --network mismatch as INVALID_ARGS', () => { - const err = new Error('Address belongs to undeployed but --network is preprod.\nDrop --network or pass an address for preprod.'); - const { exitCode, errorCode } = classifyError(err); - expect(exitCode).toBe(EXIT_INVALID_ARGS); - expect(errorCode).toBe(ERROR_CODES.INVALID_ARGS); + it.each([['the "shielded balances are private" error', PRIVATE], ['the address-HRP / --network mismatch', MISMATCH]])('classifies %s by its class: INVALID_ARGS as a UsageError, UNKNOWN as a plain error', (_what, said) => { + expect(classifyError(new UsageError(said), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); + expect(classifyError(new Error(said), installedCommands)).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN }); }); }); @@ -65,7 +62,7 @@ describe('classifyError: typed setup errors keep their own code', () => { ['LOCALNET_UNAVAILABLE', async () => new (await import('../lib/localnet.ts')).LocalnetUnavailableError()], ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('@kuiralabs/midnight-cli-core/lib/network')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], ])('%s', async (code, make) => { - const result = classifyError(await make()); + const result = classifyError(await make(), installedCommands); expect(result.errorCode).toBe(code); expect(result.errorCode).toBe(ERROR_CODES[code as keyof typeof ERROR_CODES]); expect(result.exitCode).toBe(EXIT_NETWORK_ERROR); @@ -73,40 +70,39 @@ describe('classifyError: typed setup errors keep their own code', () => { it('ignores a code that is not a known setup code', () => { const err = Object.assign(new Error('something odd'), { code: 'ENOENT' }); - expect(classifyError(err).errorCode).toBe(ERROR_CODES.UNKNOWN); + expect(classifyError(err, installedCommands).errorCode).toBe(ERROR_CODES.UNKNOWN); }); }); describe('classifyError: mn grant', () => { it('gives a wallet with no account its own code, so a caller can deploy one', () => { - expect(classifyError(new NoAccountError('alice', 'undeployed'))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.NO_ACCOUNT }); + expect(classifyError(new NoAccountError('alice', 'undeployed'), installedCommands)).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.NO_ACCOUNT }); }); it('counts a network the account package can\'t reach as the caller\'s to fix', () => { - expect(classifyError(new UnreachableByAccountError('PreProd'))).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); + expect(classifyError(new UnreachableByAccountError('PreProd'), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); }); it('names a call on the other SDK set\'s network, and an install that mixes an engine\'s SDK copies', () => { - expect(classifyError(new OtherSdkSetError('rc', 'beta'))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.OTHER_SDK_SET }); - expect(classifyError(new MixedSdkLayoutError("mn's beta engine", '@midnightntwrk/ledger-v9', ['/a', '/b']))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.MIXED_SDK_LAYOUT }); + expect(classifyError(new OtherSdkSetError('rc', 'beta'), installedCommands)).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.OTHER_SDK_SET }); + expect(classifyError(new MixedSdkLayoutError("mn's beta engine", '@midnightntwrk/ledger-v9', ['/a', '/b']), installedCommands)).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.MIXED_SDK_LAYOUT }); }); it('says a Node.js too old for the account package is an unsupported Node.js', () => { - expect(classifyError(new NodeTooOldForAccountError('22.10.0'))).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNSUPPORTED_NODE }); + expect(classifyError(new NodeTooOldForAccountError('22.10.0'), installedCommands)).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNSUPPORTED_NODE }); }); it("names a wrong passphrase, and a missing one, as the caller's to fix", () => { - expect(classifyError(new WrongPassphraseError())).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.WRONG_PASSPHRASE }); - expect(classifyError(new NoPassphraseError())).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.PASSPHRASE_REQUIRED }); + expect(classifyError(new WrongPassphraseError(), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.WRONG_PASSPHRASE }); + expect(classifyError(new NoPassphraseError(), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.PASSPHRASE_REQUIRED }); }); }); describe('classifyError: usage errors', () => { it('classifies any UsageError as INVALID_ARGS (exit 2), whatever its text, so MCP agents get INVALID_ARGS too', async () => { - const { UsageError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); - expect(classifyError(new UsageError('A contract address is 64 hex characters (32 bytes); got "deadbeef" (8 characters).'))) + expect(classifyError(new UsageError('A contract address is 64 hex characters (32 bytes); got "deadbeef" (8 characters).'), installedCommands)) .toEqual({ exitCode: 2, errorCode: 'INVALID_ARGS' }); - expect(classifyError(new UsageError('increment takes 0 arguments; --args gave 3.'))) + expect(classifyError(new UsageError('increment takes 0 arguments; --args gave 3.'), installedCommands)) .toEqual({ exitCode: 2, errorCode: 'INVALID_ARGS' }); }); }); diff --git a/src/__tests__/grant-deploy-cost.test.ts b/src/__tests__/grant-deploy-cost.test.ts index 0a4adfae..cd4b0eeb 100644 --- a/src/__tests__/grant-deploy-cost.test.ts +++ b/src/__tests__/grant-deploy-cost.test.ts @@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest'; import { ERROR_CODES, EXIT_INSUFFICIENT_BALANCE, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { MEASURED_ACCOUNT_DEPLOY, deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; +import { DustRequiredError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { installedCommands } from '../lib/installed-commands.ts'; describe('deployShortOfDustNote', () => { it('says what a deploy takes, what the wallet had, and that running again carries on', () => { @@ -30,7 +32,8 @@ describe('deployShortOfDustNote', () => { it('leaves the error it is added to a Dust shortage, with the same exit code', () => { const fromServe = 'The wallet has no Dust available that covers this transaction\'s fee (Insufficient Funds: could not balance dust), and no balanced transaction is holding any back on this server.'; - expect(classifyError(new Error(`${fromServe}\n\n${deployShortOfDustNote(0n)}`))) + // As grant deploy throws it: the shortage, with the note. + expect(classifyError(new DustRequiredError(`${fromServe}\n\n${deployShortOfDustNote(0n)}`), installedCommands)) .toEqual({ exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_REQUIRED }); }); }); diff --git a/src/__tests__/helpers/closed-port.ts b/src/__tests__/helpers/closed-port.ts new file mode 100644 index 00000000..a0ba23bd --- /dev/null +++ b/src/__tests__/helpers/closed-port.ts @@ -0,0 +1,13 @@ +// A port on 127.0.0.1 that nothing listens on: one the system just gave out and +// took back, so a connection to it is refused. (fetch refuses port 9 itself, as +// a "bad port", without connecting.) + +import { createServer, type AddressInfo } from 'node:net'; + +export async function closedPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + await new Promise((resolve) => server.close(() => resolve())); + return port; +} diff --git a/src/__tests__/helpers/connector-suite.ts b/src/__tests__/helpers/connector-suite.ts index 3efd56fe..5ae5bbac 100644 --- a/src/__tests__/helpers/connector-suite.ts +++ b/src/__tests__/helpers/connector-suite.ts @@ -24,8 +24,9 @@ import type { SignatureVerifyingKey } from '@midnightntwrk/ledger-v9'; import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { toEngineError, withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../../lib/installed-commands.ts'; import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; @@ -1132,7 +1133,7 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toContain('The wallet has no Dust available that covers this transaction\'s fee (No dust tokens found in the wallet state)'); expect(err.message).toContain('no balanced transaction is holding any back on this server'); expect(err.message).not.toContain('Retry once they settle'); - expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(classifyError(toEngineError(err) as Error, installedCommands).errorCode).toBe('DUST_REQUIRED'); expect(err.mnCode).toBe('DUST_REQUIRED'); expect(callCount).toBe(10); // DUST_RETRY_ATTEMPTS = 10 vi.useRealTimers(); @@ -1183,7 +1184,7 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toBe( "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00. " + 'Its registered NIGHT generates the rest in about 4 minutes: retry then, or register more NIGHT to get there sooner.'); - expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(classifyError(toEngineError(err) as Error, installedCommands).errorCode).toBe('DUST_REQUIRED'); expect(err.mnCode).toBe('DUST_REQUIRED'); }); @@ -1427,7 +1428,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const err: any = await failure; expect(err.message).toContain('No Dust is free to pay the fee ([Wallet.InsufficientFunds] Insufficient Funds: could not balance dust)'); expect(err.message).toContain('1 balanced transaction(s) are waiting to be submitted on this server. Retry once they settle.'); - expect(classifyError(err).errorCode).toBe('DUST_REQUIRED'); + expect(classifyError(toEngineError(err) as Error, installedCommands).errorCode).toBe('DUST_REQUIRED'); expect(err.mnCode).toBe('DUST_REQUIRED'); } finally { process.stderr.write = stderrWrite; diff --git a/src/__tests__/helpers/engine-boundary-suite.ts b/src/__tests__/helpers/engine-boundary-suite.ts index b8c1f3d0..e946e295 100644 --- a/src/__tests__/helpers/engine-boundary-suite.ts +++ b/src/__tests__/helpers/engine-boundary-suite.ts @@ -17,7 +17,7 @@ import { Effect } from 'effect'; import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { classifyByCode } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { DustRequiredError, InsufficientBalanceError, ProofFailureError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { installedCommands } from '../../lib/installed-commands.ts'; @@ -69,26 +69,26 @@ export function engineBoundarySuite(engine: BoundaryEngine): void { expect(err).toBeInstanceOf(TransactionRefusedError); expect(err.message).toBe(`The node refused the transaction: ${reason}`); expect((err as TransactionRefusedError).code).toBe(code); - expect(classifyByCode(err, installedCommands)).toStrictEqual({ errorCode: code, exitCode: 6 }); + expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: code, exitCode: 6 }); }); it("reports the proof server's failure as PROOF_FAILURE, with the SDK's message", async () => { const err = await reported(() => sdkRejection(new engine.ProvingError({ message: 'Failed to prove transaction', cause: new Error('connect ECONNREFUSED 127.0.0.1:6300') }))); expect(err).toBeInstanceOf(ProofFailureError); expect(err.message).toBe('Failed to prove transaction'); - expect(classifyByCode(err, installedCommands)).toStrictEqual({ errorCode: 'PROOF_FAILURE', exitCode: 6 }); + expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: 'PROOF_FAILURE', exitCode: 6 }); }); it("reports the SDK's Dust shortage as DUST_REQUIRED, and its shortage of NIGHT as INSUFFICIENT_BALANCE", async () => { const dust = await reported(() => sdkRejection(new engine.InsufficientFundsError({ message: engine.couldNotBalance('dust'), tokenType: 'dust' }))); expect(dust).toBeInstanceOf(DustRequiredError); expect(dust.message).toBe(engine.couldNotBalance('dust')); - expect(classifyByCode(dust, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + expect(classifyError(dust, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); const night = await reported(() => sdkRejection(new engine.InsufficientFundsError({ message: engine.couldNotBalance(NIGHT), tokenType: NIGHT }))); expect(night).toBeInstanceOf(InsufficientBalanceError); expect(night.message).toBe(engine.couldNotBalance(NIGHT)); - expect(classifyByCode(night, installedCommands)).toStrictEqual({ errorCode: 'INSUFFICIENT_BALANCE', exitCode: 5 }); + expect(classifyError(night, installedCommands)).toStrictEqual({ errorCode: 'INSUFFICIENT_BALANCE', exitCode: 5 }); }); it('keeps the SDK\'s error as the cause, and leaves a failure it does not name as it was', async () => { diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index 20129fa3..bbdab2ef 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -1,7 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; -import { classifyError, EXIT_WALLET_NOT_FOUND, EXIT_INVALID_ARGS, EXIT_CANCELLED, EXIT_NETWORK_ERROR, EXIT_INSUFFICIENT_BALANCE, EXIT_TX_REJECTED, EXIT_GENERAL_ERROR, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError, EXIT_NETWORK_ERROR, EXIT_INSUFFICIENT_BALANCE, EXIT_TX_REJECTED, EXIT_GENERAL_ERROR, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { installedCommands } from '../lib/installed-commands.ts'; import { writeJsonResult, writeJsonError } from '@kuiralabs/midnight-cli-core/lib/json-output'; import * as fs from 'fs'; import * as path from 'path'; @@ -60,101 +62,35 @@ function parseJsonOutput(): Record { } // ── classifyError ───────────────────────────────────────── +// Only an error's code is read. The SDK's words for its failures are read once, +// at the engine boundary (toEngineError), which gives them their codes. describe('classifyError', () => { - it('classifies wallet not found', () => { - const { exitCode, errorCode } = classifyError(new Error('Wallet file not found: /foo/bar')); - expect(exitCode).toBe(EXIT_WALLET_NOT_FOUND); - expect(errorCode).toBe(ERROR_CODES.WALLET_NOT_FOUND); - }); - - it('classifies missing required flag as invalid args', () => { - const { exitCode, errorCode } = classifyError(new Error('Missing required flag: --seed')); - expect(exitCode).toBe(EXIT_INVALID_ARGS); - expect(errorCode).toBe(ERROR_CODES.INVALID_ARGS); - }); - - it('classifies unknown command as invalid args', () => { - const { exitCode, errorCode } = classifyError(new Error('Unknown command: "bogus"')); - expect(exitCode).toBe(EXIT_INVALID_ARGS); - expect(errorCode).toBe(ERROR_CODES.INVALID_ARGS); - }); - - it('classifies cancelled operations', () => { - const { exitCode, errorCode } = classifyError(new Error('Operation cancelled')); - expect(exitCode).toBe(EXIT_CANCELLED); - expect(errorCode).toBe(ERROR_CODES.CANCELLED); - }); - - it('classifies connection errors', () => { - const { exitCode, errorCode } = classifyError(new Error('ECONNREFUSED 127.0.0.1:9944')); - expect(exitCode).toBe(EXIT_NETWORK_ERROR); - expect(errorCode).toBe(ERROR_CODES.NETWORK_ERROR); - }); - - it('classifies insufficient balance', () => { - const { exitCode, errorCode } = classifyError(new Error('Insufficient balance for transfer')); - expect(exitCode).toBe(EXIT_INSUFFICIENT_BALANCE); - expect(errorCode).toBe(ERROR_CODES.INSUFFICIENT_BALANCE); - }); - - it('classifies transaction rejected', () => { - const { exitCode, errorCode } = classifyError(new Error('Transaction rejected by the node')); - expect(exitCode).toBe(EXIT_TX_REJECTED); - expect(errorCode).toBe(ERROR_CODES.TX_REJECTED); - }); - - it('classifies stale UTXO', () => { - const { exitCode, errorCode } = classifyError(new Error('Stale UTXO detected')); - expect(exitCode).toBe(EXIT_TX_REJECTED); - expect(errorCode).toBe(ERROR_CODES.STALE_UTXO); - }); - - it('classifies dust errors', () => { - const { exitCode, errorCode } = classifyError(new Error('No dust available for fee payment')); - expect(exitCode).toBe(EXIT_INSUFFICIENT_BALANCE); - expect(errorCode).toBe(ERROR_CODES.DUST_REQUIRED); - }); - - it('returns unknown for unrecognized errors', () => { - const { exitCode, errorCode } = classifyError(new Error('Something unexpected happened')); - expect(exitCode).toBe(EXIT_GENERAL_ERROR); - expect(errorCode).toBe(ERROR_CODES.UNKNOWN); - }); - - it('classifies "Failed to prove transaction" as PROOF_FAILURE', () => { - const { exitCode, errorCode } = classifyError(new Error('Failed to prove transaction')); - expect(exitCode).toBe(EXIT_TX_REJECTED); - expect(errorCode).toBe(ERROR_CODES.PROOF_FAILURE); - }); - - it('classifies "Custom error 170" as INVALID_DUST_PROOF', () => { - const { exitCode, errorCode } = classifyError(new Error('Transaction failed: error 170 InvalidDustSpendProof')); - expect(exitCode).toBe(EXIT_TX_REJECTED); - expect(errorCode).toBe(ERROR_CODES.INVALID_DUST_PROOF); - }); - - it('classifies stale-cache messages as STALE_CACHE', () => { - const { exitCode, errorCode } = classifyError(new Error('Stale cache: applied > highest')); - expect(exitCode).toBe(EXIT_TX_REJECTED); - expect(errorCode).toBe(ERROR_CODES.STALE_CACHE); - }); - - it('classifies "Wallet sync timed out" as SYNC_TIMEOUT', () => { - const { exitCode, errorCode } = classifyError(new Error('Wallet sync timed out')); - expect(exitCode).toBe(EXIT_NETWORK_ERROR); - expect(errorCode).toBe(ERROR_CODES.SYNC_TIMEOUT); - }); - - it('classifies "Timed out waiting for dust tokens" as SYNC_TIMEOUT', () => { - const { exitCode, errorCode } = classifyError(new Error('Timed out waiting for dust tokens')); - expect(exitCode).toBe(EXIT_NETWORK_ERROR); - expect(errorCode).toBe(ERROR_CODES.SYNC_TIMEOUT); - }); - - it('classifies "did not respond within 30s" (proof-server gate) as SYNC_TIMEOUT', () => { - const { exitCode, errorCode } = classifyError(new Error('Proof server at http://localhost:6300/ did not respond within 30s')); - expect(exitCode).toBe(EXIT_NETWORK_ERROR); - expect(errorCode).toBe(ERROR_CODES.SYNC_TIMEOUT); + it.each([ + ['ECONNREFUSED 127.0.0.1:9944', ERROR_CODES.NETWORK_ERROR, EXIT_NETWORK_ERROR], + ['Insufficient balance for transfer', ERROR_CODES.INSUFFICIENT_BALANCE, EXIT_INSUFFICIENT_BALANCE], + ['Transaction rejected by the node', ERROR_CODES.TX_REJECTED, EXIT_TX_REJECTED], + ['Stale UTXO detected', ERROR_CODES.STALE_UTXO, EXIT_TX_REJECTED], + ['No dust available for fee payment', ERROR_CODES.DUST_REQUIRED, EXIT_INSUFFICIENT_BALANCE], + ['Failed to prove transaction', ERROR_CODES.PROOF_FAILURE, EXIT_TX_REJECTED], + ['Transaction failed: error 170 InvalidDustSpendProof', ERROR_CODES.INVALID_DUST_PROOF, EXIT_TX_REJECTED], + ['Stale cache: applied > highest', ERROR_CODES.STALE_CACHE, EXIT_TX_REJECTED], + ['Wallet sync timed out', ERROR_CODES.SYNC_TIMEOUT, EXIT_NETWORK_ERROR], + ['Timed out waiting for dust tokens', ERROR_CODES.SYNC_TIMEOUT, EXIT_NETWORK_ERROR], + ])('classifies the SDK saying "%s", read at the engine boundary, as %s', (said, errorCode, exitCode) => { + expect(classifyError(toEngineError(new Error(said)) as Error, installedCommands)).toStrictEqual({ exitCode, errorCode }); + }); + + // Approved (Y52): words alone no longer give a code. mn throws each of these + // as its typed error (error-code-parity.test.ts has every site). + it.each([ + 'Wallet file not found: /foo/bar', + 'Missing required flag: --seed', + 'Unknown command: "bogus"', + 'Operation cancelled', + 'Proof server at http://localhost:6300/ did not respond within 30s', + 'Something unexpected happened', + ])('returns UNKNOWN (exit 1) for a plain error saying "%s"', (said) => { + expect(classifyError(new Error(said), installedCommands)).toStrictEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.UNKNOWN }); }); }); diff --git a/src/__tests__/node-version.test.ts b/src/__tests__/node-version.test.ts index 5676fa48..c4185a9d 100644 --- a/src/__tests__/node-version.test.ts +++ b/src/__tests__/node-version.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { MIN_NODE_MAJOR, UnsupportedNodeError, assertNodeSupported } from '../lib/node-version.ts'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; describe('assertNodeSupported', () => { it('accepts Node.js 22 and newer', () => { @@ -27,7 +28,7 @@ describe('assertNodeSupported', () => { }); it('is UNSUPPORTED_NODE, exit code 1, for --json and MCP callers', () => { - expect(classifyError(new UnsupportedNodeError('20.10.0'))).toEqual({ exitCode: 1, errorCode: 'UNSUPPORTED_NODE' }); + expect(classifyError(new UnsupportedNodeError('20.10.0'), installedCommands)).toEqual({ exitCode: 1, errorCode: 'UNSUPPORTED_NODE' }); }); it('accepts the Node.js these tests run on', () => { diff --git a/src/__tests__/offer-envelope.test.ts b/src/__tests__/offer-envelope.test.ts index f6c8e2d6..903778a1 100644 --- a/src/__tests__/offer-envelope.test.ts +++ b/src/__tests__/offer-envelope.test.ts @@ -5,6 +5,7 @@ import { describe, it, expect } from 'vitest'; import { assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, OfferExpiredError, type OfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; const A = '00'.repeat(31) + '01'; const B = '00'.repeat(31) + '02'; @@ -46,6 +47,6 @@ describe('the offer file', () => { const err = (() => { try { assertOfferUnexpired(ENVELOPE, ENVELOPE.expiresAt); } catch (e) { return e; } })() as OfferExpiredError; expect(err).toBeInstanceOf(OfferExpiredError); expect(err.message).toBe(`The offer ${'ab'.repeat(8)}… expired at 2026-11-03T12:00:00.000Z; ask the maker for a new one`); - expect(classifyError(err)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_EXPIRED }); + expect(classifyError(err, installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_EXPIRED }); }); }); diff --git a/src/__tests__/open-offers.test.ts b/src/__tests__/open-offers.test.ts index c36f538c..e9eb4c14 100644 --- a/src/__tests__/open-offers.test.ts +++ b/src/__tests__/open-offers.test.ts @@ -7,6 +7,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { assertSpendsNoOfferCoin, closeOpenOffers, OfferCoinsInUseError, openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; const WALLET = 'mn_addr_undeployed1maker'; const offer = (id: string, nullifiers: string[]): OpenOffer => ({ @@ -51,7 +52,7 @@ describe('open offers', () => { expect(err).toBeInstanceOf(OfferCoinsInUseError); expect(err.offerIds).toEqual(['a1'.repeat(16)]); expect(err.message).toBe(`This would spend coins held by an open swap offer (${'a1'.repeat(8)}…), cancelling it. Cancel it first, or wait until it is taken.`); - expect(classifyError(err)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_COINS_IN_USE }); + expect(classifyError(err, installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_COINS_IN_USE }); expect(() => assertSpendsNoOfferCoin(open, ['aa11'], ['a1'.repeat(16)])).not.toThrow(); }); }); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index b10e5c33..492ef0c4 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -3,6 +3,7 @@ import { captureCommand } from '../lib/run-command.ts'; import { SecondResultError, type CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { CancelledError, CommandFailedError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; @@ -58,7 +59,7 @@ describe('captureCommand', () => { expect(err).toBeInstanceOf(CommandFailedError); expect((err as CommandFailedError).exitCode).toBe(1); expect((err as CommandFailedError).result).toStrictEqual({ overall: 'fail' }); - expect(classifyError(err as Error).exitCode).toBe(1); + expect(classifyError(err as Error, installedCommands).exitCode).toBe(1); const passing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'pass' }); return { exitCode: 0 }; }; expect(await captureCommand(passing, parseArgs(['test', 'run']), ownCall())).toStrictEqual({ overall: 'pass' }); @@ -239,7 +240,7 @@ describe('captureCommand', () => { let ran = false; const err = await captureCommand(async () => { ran = true; }, noArgs(), ownCall({ signal: controller.signal })).catch((e: unknown) => e); expect(err).toBeInstanceOf(CancelledError); - expect(classifyError(err as Error).errorCode).toBe('CANCELLED'); + expect(classifyError(err as Error, installedCommands).errorCode).toBe('CANCELLED'); expect(ran).toBe(false); }); }); diff --git a/src/__tests__/sdk-errors.test.ts b/src/__tests__/sdk-errors.test.ts index 7a8ed581..c8f65f08 100644 --- a/src/__tests__/sdk-errors.test.ts +++ b/src/__tests__/sdk-errors.test.ts @@ -7,10 +7,12 @@ import { Brand, Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { NodeClientError } from '@midnightntwrk/wallet-sdk/node-client/effect'; import { dustShortfallOf, isColdStartRace, isDustShortage, mnCodeOf, nodeRefusalOf, refusalCodeOf, toEngineError, withDustShortfall, withEngineCode, withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { DustRequiredError, InsufficientBalanceError, ProofTimeoutError, StaleWalletStateError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyByCode, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { DustRequiredError, InsufficientBalanceError, NetworkError, ProofFailureError, ProofTimeoutError, StaleWalletStateError, SyncTimeoutError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { createApiError } from '@kuiralabs/midnight-cli-core/lib/connector-api'; import { installedCommands } from '../lib/installed-commands.ts'; +import { isTransportFailure } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; +import { closedPort } from './helpers/closed-port.ts'; /** wallet-sdk 2.0's dust InsufficientFundsError: tagged, with the token it could not balance. */ function sdkInsufficientFunds(tokenType: string): Error { @@ -167,22 +169,21 @@ describe("the node's reason for refusing a transaction", () => { expect(reported).toBeInstanceOf(TransactionRefusedError); expect(reported.message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 170'); expect(reported.cause).toBe(thrown); - expect(classifyError(reported)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); - expect(classifyByCode(reported, installedCommands)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); - // Unexplained, the same error was UNKNOWN. - expect(classifyError(thrown).errorCode).toBe('UNKNOWN'); + expect(classifyError(reported, installedCommands)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); + // Unexplained, the same error is UNKNOWN. + expect(classifyError(thrown, installedCommands).errorCode).toBe('UNKNOWN'); }); it("is the node client's own words when the node gave none", async () => { const thrown = await caught(refusal(new NodeClientError.TransactionInvalidError({ message: 'Transaction is invalid and was rejected by the node', txData: TX_DATA }))); expect(nodeRefusalOf(thrown)).toBe('Transaction is invalid and was rejected by the node'); - expect(classifyError(withNodeReason(thrown))).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); + expect(classifyError(withNodeReason(thrown), installedCommands)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); }); it('classifies a reason no rule knows as TX_REJECTED, with the reason in the message', async () => { const reported = withNodeReason(await caught(refusal(new NodeClientError.SubmissionError({ message: 'Transaction submission failed', txData: TX_DATA, cause: new Error('1010: Invalid Transaction: Custom error: 199') })))); expect(reported.message).toContain('Custom error: 199'); - expect(classifyError(reported)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); + expect(classifyError(reported, installedCommands)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); }); it('leaves any other error as it is, and a submission error with nothing under its wrapper', async () => { @@ -218,7 +219,7 @@ describe("the engine contract's reading of a failure", () => { // The ledger's words when a saved state is resumed on an indexer that numbers its events differently. const resumed = toEngineError(new Error('Failed applying dust events: commitment inserted non-linearly')) as Error; expect(resumed).toBeInstanceOf(StaleWalletStateError); - expect(classifyByCode(resumed, installedCommands)).toStrictEqual({ errorCode: 'STALE_CACHE', exitCode: 6 }); + expect(classifyError(resumed, installedCommands)).toStrictEqual({ errorCode: 'STALE_CACHE', exitCode: 6 }); }); it("leaves an error that carries its own code, a refusal already reported, and one it doesn't name, as they are", () => { @@ -231,6 +232,26 @@ describe("the engine contract's reading of a failure", () => { expect(toEngineError('a string')).toBe('a string'); }); + it('reports a connection the SDK could not make as a NetworkError, last among what it names', async () => { + // A socket's own error carries the transport's code, not mn's. + const socket = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:8088'), { code: 'ECONNREFUSED' }); + const fromSocket = toEngineError(socket) as Error; + expect(fromSocket).toBeInstanceOf(NetworkError); + expect(fromSocket.message).toBe(socket.message); + expect(fromSocket.cause).toBe(socket); + // fetch says only "fetch failed"; what failed is its cause (ECONNREFUSED). + const fetched = await fetch(`http://127.0.0.1:${await closedPort()}/`).then(() => { throw new Error('expected fetch to fail'); }, (e: Error) => e); + expect(fetched.message).toBe('fetch failed'); + expect(isTransportFailure(Object.assign(new Error('the SDK said no more'), { cause: fetched }))).toBe(true); + expect(classifyError(toEngineError(fetched) as Error, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + expect(classifyError(toEngineError(new Error('WebSocket connection to ws://127.0.0.1:8088 failed')) as Error, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + // A proof server out of reach is a failed proof, as the SDK says first. + expect(toEngineError(new Error('Failed to prove transaction', { cause: socket }))).toBeInstanceOf(ProofFailureError); + // An error with a code of its own keeps it, whatever its cause. + const own = new SyncTimeoutError('Wallet sync timed out', { cause: socket }); + expect(toEngineError(own)).toBe(own); + }); + it("reports a connector error marked with mn's code as the typed error for it, in its own words", () => { const api = createApiError('InternalError', "Not enough Dust available for this transaction's fee", 'DUST_REQUIRED'); const reported = toEngineError(api) as Error; diff --git a/src/__tests__/swap-offer.test.ts b/src/__tests__/swap-offer.test.ts index a4c13b3b..aa8c7fd7 100644 --- a/src/__tests__/swap-offer.test.ts +++ b/src/__tests__/swap-offer.test.ts @@ -4,6 +4,7 @@ import { describe, it, expect } from 'vitest'; import { checkTerms, NotAnOfferError, TermsMismatchError, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; const A = '00'.repeat(31) + '01'; const B = '00'.repeat(31) + '02'; @@ -27,7 +28,7 @@ describe('checkTerms', () => { }); it('classifies a terms mismatch and bytes that are no offer as the caller\'s to fix', () => { - expect(classifyError(new TermsMismatchError(AGREED, AGREED))).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.TERMS_MISMATCH }); - expect(classifyError(new NotAnOfferError('it is not hex'))).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.NOT_AN_OFFER }); + expect(classifyError(new TermsMismatchError(AGREED, AGREED), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.TERMS_MISMATCH }); + expect(classifyError(new NotAnOfferError('it is not hex'), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.NOT_AN_OFFER }); }); }); diff --git a/src/__tests__/transfer-lib.test.ts b/src/__tests__/transfer-lib.test.ts index a0db6ced..76ba823b 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/src/__tests__/transfer-lib.test.ts @@ -6,6 +6,7 @@ import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-ad import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; describe('nightToMicro', () => { it('converts whole NIGHT to micro-NIGHT', () => { @@ -100,7 +101,7 @@ describe('parseAmount', () => { for (const amount of ['0', '-5', 'abc', 'Infinity']) { const refused = (() => { try { parseAmount(amount); } catch (err) { return err as Error; } throw new Error(`${amount} was accepted`); })(); expect(refused).toBeInstanceOf(UsageError); - expect(classifyError(refused)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); + expect(classifyError(refused, installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); } }); }); diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index b3caecfb..db52cec9 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -13,6 +13,7 @@ import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midni import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '@kuiralabs/midnight-cli-core/lib/constants'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; @@ -93,7 +94,7 @@ describe('resolveTransferRequest', () => { let err: unknown; try { await request(...argv, '--wallet', 'sender'); } catch (e) { err = e; } expect(err).toBeInstanceOf(UsageError); - expect(classifyError(err as Error).errorCode).toBe('INVALID_ARGS'); + expect(classifyError(err as Error, installedCommands).errorCode).toBe('INVALID_ARGS'); }); it('refuses a shielded transfer where shielded is off before reading the address', async () => { diff --git a/src/__tests__/transport-failure.test.ts b/src/__tests__/transport-failure.test.ts new file mode 100644 index 00000000..f08c4947 --- /dev/null +++ b/src/__tests__/transport-failure.test.ts @@ -0,0 +1,79 @@ +// A connection that could not be made, as the engine boundary, a contract +// script and grant recognise it: by the transport's code anywhere among the +// failure's causes, or by the words the SDK says it with. + +import { describe, expect, it } from 'vitest'; +import { WebSocket } from 'ws'; +import { carriesOwnCode, isTransportFailure, withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; +import { DustRequiredError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { closedPort } from './helpers/closed-port.ts'; + +/** What a WebSocket to a closed port fails with: the socket's own error, ECONNREFUSED its code. */ +async function refusedWebSocket(): Promise { + const port = await closedPort(); + return new Promise((resolve) => { + const ws = new WebSocket(`ws://127.0.0.1:${port}`); + ws.on('error', (err) => resolve(err)); + }); +} + +describe('isTransportFailure', () => { + it("names a socket's refusal, by its code", async () => { + const refused = await refusedWebSocket(); + expect((refused as Error & { code?: string }).code).toBe('ECONNREFUSED'); + expect(isTransportFailure(refused)).toBe(true); + }); + + it("names fetch's failure, whose code is its cause's (an AggregateError's members, for a name with several addresses)", async () => { + const fetched = await fetch(`http://127.0.0.1:${await closedPort()}/`).then(() => { throw new Error('expected fetch to fail'); }, (e: Error) => e); + expect(fetched.message).toBe('fetch failed'); + expect(isTransportFailure(Object.assign(new Error('the indexer could not be asked'), { cause: fetched }))).toBe(true); + const aggregate = new AggregateError([Object.assign(new Error('connect'), { code: 'ETIMEDOUT' })], 'several addresses'); + expect(isTransportFailure(new Error('no answer', { cause: aggregate }))).toBe(true); + expect(isTransportFailure({ type: 'error', error: Object.assign(new Error('getaddrinfo'), { code: 'ENOTFOUND' }) })).toBe(true); + }); + + it("names the SDK's words for it, in the failure's own message", () => { + for (const said of ['fetch failed', 'WebSocket connection closed', 'connect ECONNREFUSED 127.0.0.1:6300', 'Connection refused', 'request to http://localhost:8088/api/v4/graphql failed, reason:', 'Network error: socket hang up']) { + expect(isTransportFailure(new Error(said))).toBe(true); + } + }); + + it('names nothing else, and survives a message that cannot be read', () => { + expect(isTransportFailure(new Error('Something unexpected happened'))).toBe(false); + expect(isTransportFailure(Object.assign(new Error('x'), { code: 'ENOENT' }))).toBe(false); + expect(isTransportFailure(undefined)).toBe(false); + expect(isTransportFailure('ECONNREFUSED')).toBe(false); + const unreadable = Object.defineProperty(new Error(), 'message', { get() { throw new Error('no message'); } }); + expect(isTransportFailure(unreadable)).toBe(false); + }); + + it('runs from its own source text, as a contract script carries it', () => { + const inlined = new Function(`return (${isTransportFailure.toString()});`)() as typeof isTransportFailure; + expect(inlined(Object.assign(new Error('x'), { code: 'ECONNREFUSED' }))).toBe(true); + expect(inlined(new Error('fetch failed'))).toBe(true); + expect(inlined(new Error('Something unexpected happened'))).toBe(false); + }); +}); + +describe('withTransportCode', () => { + it('reports a transport failure with no code of its own as a NetworkError, the failure its cause', async () => { + const refused = await refusedWebSocket(); + const reported = withTransportCode(refused) as Error; + expect(reported).toBeInstanceOf(NetworkError); + expect(reported.message).toBe(refused.message); + expect(reported.cause).toBe(refused); + expect(classifyError(reported, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + }); + + it('leaves an error with a code of its own, and any other error, as it is', () => { + const own = new DustRequiredError('Dust not available', { cause: Object.assign(new Error('x'), { code: 'ECONNREFUSED' }) }); + expect(carriesOwnCode(own)).toBe(true); + expect(withTransportCode(own)).toBe(own); + const other = new Error('Something unexpected happened'); + expect(withTransportCode(other)).toBe(other); + expect(carriesOwnCode(Object.assign(new Error('x'), { code: 'ECONNREFUSED' }))).toBe(false); + }); +}); diff --git a/src/__tests__/wallet-session.test.ts b/src/__tests__/wallet-session.test.ts index 03f33c95..16c75fd7 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/src/__tests__/wallet-session.test.ts @@ -15,7 +15,7 @@ import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { DustRequiredError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyByCode } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; import { installedCommands } from '../lib/installed-commands.ts'; const { WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, mockState } = connectorStub({ @@ -223,7 +223,7 @@ describe('wallet session', () => { expect(err).toBeInstanceOf(TransactionRefusedError); expect((err as Error).message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 115'); - expect(classifyByCode(err as Error, installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + expect(classifyError(err as Error, installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); await session.close(); }); @@ -237,7 +237,7 @@ describe('wallet session', () => { expect(err).toBeInstanceOf(DustRequiredError); expect((err as Error).message).toContain("The wallet has no Dust available that covers this transaction's fee (No dust tokens found in the wallet state)"); - expect(classifyByCode(err as Error, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + expect(classifyError(err as Error, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); await session.close(); } finally { vi.useRealTimers(); diff --git a/src/commands/contract.codes.ts b/src/commands/contract.codes.ts index 6a0a09a4..bedd69b4 100644 --- a/src/commands/contract.codes.ts +++ b/src/commands/contract.codes.ts @@ -4,5 +4,5 @@ import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; export const contractCodes = defineCodes([ - { code: 'NO_NODE_RUNTIME', exitCode: EXIT_GENERAL_ERROR, summary: 'Contract scripts run under Node.js, and none was found on PATH.', recovery: 'Install Node.js 22 or later, or run mn under Node.' }, + { code: 'NO_NODE_RUNTIME', exitCode: EXIT_GENERAL_ERROR, order: 200, summary: 'Contract scripts run under Node.js, and none was found on PATH.', recovery: 'Ask the user to install Node.js 22 or later, or to run mn under Node.' }, ]); diff --git a/src/commands/contract.guidance.ts b/src/commands/contract.guidance.ts index 12ec6df7..f1d776c7 100644 --- a/src/commands/contract.guidance.ts +++ b/src/commands/contract.guidance.ts @@ -2,18 +2,11 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { contractCodes } from './contract.codes.ts'; export const contractGuidance: PackageGuidance = { pieces: [ - { - text: 'agent-manual', - section: 'error-codes', - order: 95, - body: ` NO_NODE_RUNTIME 1 Contract scripts run under Node.js and none - is on PATH: install Node.js 22 or later -`, - }, { text: 'skill-full', section: 'what-you-can-do', @@ -116,6 +109,8 @@ Plain strings, booleans, fractional numbers, and \`null\` pass through unchanged `, }, + // Its error codes' rows in the manual and the full skill, from their definitions. + ...codeGuidancePieces(contractCodes), ], toolsTable: [ { tool: 'midnight_inspect_cost', group: 'balance-info', order: 50, description: ['Display block cost limits'] }, diff --git a/src/commands/dev.codes.ts b/src/commands/dev.codes.ts index 2cb8615c..fe8954ce 100644 --- a/src/commands/dev.codes.ts +++ b/src/commands/dev.codes.ts @@ -4,5 +4,5 @@ import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; export const devCodes = defineCodes([ - { code: 'LOCALNET_UNAVAILABLE', exitCode: EXIT_NETWORK_ERROR, summary: "`mn localnet up` can't start a ledger-9 stack on this build.", recovery: 'Run one yourself and point mn at it (endpoint flags or `midnight config set`).' }, + { code: 'LOCALNET_UNAVAILABLE', exitCode: EXIT_NETWORK_ERROR, order: 160, summary: "`mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build.", recovery: 'Ask the user to start their ledger-9 stack and point mn at it (endpoint config).' }, ]); diff --git a/src/commands/dev.guidance.ts b/src/commands/dev.guidance.ts index 14ea6b7f..487b8eba 100644 --- a/src/commands/dev.guidance.ts +++ b/src/commands/dev.guidance.ts @@ -2,7 +2,8 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { devCodes } from './dev.codes.ts'; export const devGuidance: PackageGuidance = { pieces: [ @@ -43,14 +44,6 @@ export const devGuidance: PackageGuidance = { Runs E2E tests for Midnight dApps defined in dapp.test.json. Includes contract deployment, circuit calls, and state verification. -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 60, - body: ` LOCALNET_UNAVAILABLE 4 localnet up can't start a ledger-9 stack; run - one and set its endpoints (config set) `, }, { @@ -101,13 +94,6 @@ Use \`midnight_test_create({ path, strategy })\`. Strategies: Running a suite is a CLI command, not an MCP tool: \`mn test run --suite \` (exit code 0 on PASS, 1 on FAIL; \`--json\` prints the result, \`mn test results\` shows the last one). Browser strategy supports \`browserMode: "vision"\` (screenshots — default), \`"dom"\` (accessibility tree, faster, requires \`chrome-devtools-mcp\`), \`"script"\` (direct JS, fastest, requires \`chrome-devtools-mcp\`). Pre-flight detects missing \`chrome-devtools-mcp\` and orphan automation Chromes from prior crashes. -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 40, - body: `| \`LOCALNET_UNAVAILABLE\` | \`midnight_localnet_up()\` can't start a ledger-9 stack on this build. | Ask the user to start their ledger-9 stack and point mn at it (endpoint config). | `, }, { @@ -117,6 +103,8 @@ Running a suite is a CLI command, not an MCP tool: \`mn test run --suite \ body: `- Not a contract compiler. The project's \`package.json\` should expose a \`compact\` script (Midnight convention, e.g. \`"compact": "compact compile src/foo.compact src/managed/foo"\`) or a \`compile\` script as a generic fallback. \`mn dev\` detects whichever is present; create-mn-app and midnight-starship templates ship with the \`compact\` script already wired. `, }, + // Its error codes' rows in the manual and the full skill, from their definitions. + ...codeGuidancePieces(devCodes), ], toolsTable: [ { tool: 'midnight_localnet_up', group: 'local-network', order: 10, description: ['Refused on this ledger-9 build (see OVERVIEW)'] }, diff --git a/src/commands/grant.codes.ts b/src/commands/grant.codes.ts index e8ecd135..1fb7eec4 100644 --- a/src/commands/grant.codes.ts +++ b/src/commands/grant.codes.ts @@ -4,5 +4,5 @@ import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; export const grantCodes = defineCodes([ - { code: 'NO_ACCOUNT', exitCode: EXIT_GENERAL_ERROR, summary: 'The wallet has no account on this network yet.', recovery: '`mn grant deploy`.' }, + { code: 'NO_ACCOUNT', exitCode: EXIT_GENERAL_ERROR, order: 210, summary: 'A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network.', recovery: 'Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow).' }, ]); diff --git a/src/commands/grant.guidance.ts b/src/commands/grant.guidance.ts index e029647a..bb4835dc 100644 --- a/src/commands/grant.guidance.ts +++ b/src/commands/grant.guidance.ts @@ -2,7 +2,8 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { grantCodes } from './grant.codes.ts'; export const grantGuidance: PackageGuidance = { pieces: [ @@ -122,14 +123,6 @@ ledger-9 network. Amounts are whole numbers of the token's smallest unit, as text in JSON. -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 100, - body: ` NO_ACCOUNT 1 mn grant: the wallet has no account on this - network; run grant deploy `, }, { @@ -168,13 +161,8 @@ Amounts are whole numbers of the token's smallest unit, as text. `, }, - { - text: 'skill-full', - section: 'error-recovery', - order: 70, - body: `| \`NO_ACCOUNT\` | A \`midnight_grant_*\` tool was called for a wallet that has no account on this network. | Offer \`midnight_grant_deploy()\`, after telling the user how its owner key is kept (see the allowance flow). | -`, - }, + // Its error codes' rows in the manual and the full skill, from their definitions. + ...codeGuidancePieces(grantCodes), ], toolsTable: [ { tool: 'midnight_grant_status', group: 'grants', order: 10, description: ["Show the wallet's account (holdings, grants)"] }, diff --git a/src/commands/grant.ts b/src/commands/grant.ts index b7fbb30f..aeadf319 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -23,6 +23,7 @@ import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; import { header, keyValue, formatNight } from '@kuiralabs/midnight-cli-core/ui/format'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; const SPINNER_LABEL: Record = { deploy: 'Deploying the account...', @@ -299,6 +300,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, if (request.subcommand === 'deploy' && funds !== undefined && err instanceof Error && isShortOfDust(err)) { throw new DustRequiredError(`${err.message}\n\n${deployShortOfDustNote(funds.dustBalance)}`, { cause: err }); } - throw err; + // The account package reaches the indexer and the proof server itself, past the engine: a connection it couldn't make is a network error. + throw withTransportCode(err); } } diff --git a/src/commands/manual.ts b/src/commands/manual.ts index 618286a9..e7f98c97 100644 --- a/src/commands/manual.ts +++ b/src/commands/manual.ts @@ -10,6 +10,8 @@ import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/c import { bold, dim, teal, yellow, white } from '@kuiralabs/midnight-cli-core/ui/colors'; import { helpSpecs, type CommandSpec } from './help.ts'; import { PKG_NAME, PKG_VERSION, PKG_REPOSITORY_URL } from '../lib/pkg.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { manualCodeLines } from '../lib/code-tables.ts'; const SECTION_BAR = '═'.repeat(63); const RULE = '─'.repeat(64); @@ -209,14 +211,9 @@ export function buildManual(): string { out.push(` ${dim('6')} Transaction rejected / STALE_UTXO / PROOF_TIMEOUT`); out.push(` ${dim('7')} Cancelled by user`); out.push(''); - out.push(` ${bold('Stable error code strings')} (in JSON ${yellow('--json')} error output):`); - out.push(` ${yellow('DUST_REQUIRED')} No dust available to pay fees`); - out.push(` ${yellow('STALE_UTXO')} UTXO consumed concurrently, retry`); - out.push(` ${yellow('PROOF_TIMEOUT')} Proof generation exceeded deadline`); - out.push(` ${yellow('PROOF_FAILURE')} Proof server rejected the proof`); - out.push(` ${yellow('INVALID_DUST_PROOF')} Stale commitment tree, run ${dim('mn cache clear')}`); - out.push(` ${yellow('STALE_CACHE')} Local cache out of sync, run ${dim('mn cache clear')}`); - out.push(` ${yellow('SYNC_TIMEOUT')} Wallet sync exceeded its deadline`); + out.push(` ${bold('Stable error code strings')} (in JSON ${yellow('--json')} error output), with the exit code of each:`); + // Every installed package's codes, from their definitions. + out.push(...manualCodeLines(installedCommands, yellow)); // ── Troubleshooting ─────────────────────────────────────── out.push(subhead('TROUBLESHOOTING')); diff --git a/src/commands/wallet.codes.ts b/src/commands/wallet.codes.ts index 3d900244..d73bdca6 100644 --- a/src/commands/wallet.codes.ts +++ b/src/commands/wallet.codes.ts @@ -4,5 +4,5 @@ import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { EXIT_WALLET_NOT_FOUND } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; export const walletCodes = defineCodes([ - { code: 'WALLET_NOT_FOUND', exitCode: EXIT_WALLET_NOT_FOUND, summary: 'Wallet file does not exist.', recovery: '`midnight wallet list` shows the wallets there are.' }, + { code: 'WALLET_NOT_FOUND', exitCode: EXIT_WALLET_NOT_FOUND, order: 20, summary: "Named wallet doesn't exist on disk.", recovery: '`midnight_wallet_list()` — user may have removed it.' }, ]); diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index 295a512f..ef3207d5 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -3,7 +3,8 @@ // skills, each naming its section and its place there, and its tools' rows in // the manual's tools table. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { walletCodes } from './wallet.codes.ts'; export const walletGuidance: PackageGuidance = { pieces: [ @@ -80,40 +81,6 @@ Transfer commands accept wallet names instead of full addresses: Names are resolved from ~/.midnight/wallets/.json. If the input starts with mn_addr_ or mn_shield-addr_, it's used as an address directly. -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 20, - body: ` WALLET_NOT_FOUND 3 Wallet file does not exist -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 40, - body: ` SYNC_TIMEOUT 4 Wallet sync exceeded its deadline (retry resumes) - INSUFFICIENT_BALANCE 5 Not enough NIGHT for the operation - TX_REJECTED 6 Transaction rejected by the node - STALE_UTXO 6 UTXOs consumed by another transaction - STALE_CACHE 6 Local cache disagrees with chain state - PROOF_TIMEOUT 6 ZK proof generation timed out - PROOF_FAILURE 6 Proof server failed to generate the ZK proof - INVALID_DUST_PROOF 6 Chain rejected the dust spend proof as malformed - DUST_REQUIRED 5 Not enough Dust for the fee. Not registered: - dust register. Generating: the message says - how long (retry then, or register more NIGHT) - DUST_GENERATING 5 Dust registration fee not generated yet; the - message says when (rerun then, or add NIGHT) -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 120, - body: ` PASSPHRASE_REQUIRED 2 A secret was needed and no passphrase could be - had: set MN_PASSPHRASE, or run at a terminal `, }, { @@ -240,41 +207,8 @@ At step 5 the user is ready to transact. `, }, - { - text: 'skill-full', - section: 'error-recovery', - order: 10, - body: `| \`INSUFFICIENT_BALANCE\` | Wallet doesn't have enough NIGHT to cover the requested amount. | Show the user. On localnet: \`midnight_airdrop({ amount: "..." })\`. On hosted networks: tell user to fund the address. | -| \`DUST_REQUIRED\` | Wallet has NIGHT but not enough DUST for the fee. | Not registered (\`midnight_dust_status()\` shows \`registered: false\`): run \`midnight_dust_register()\`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes ("generates the rest in about 4 minutes"). Wait that long and retry, don't retry at once. | -| \`INVALID_DUST_PROOF\` | Chain rejected the dust spend proof as malformed (substrate "Custom error 170"). Stale commitment tree. | \`midnight_cache_clear({ wallet: "" })\` then retry. | -| \`STALE_CACHE\` | Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed). | \`midnight_cache_clear({ wallet: "" })\` then retry. | -| \`STALE_UTXO\` | UTXO was already spent on-chain (substrate "error code 115"). | Re-sync (the next call will refresh state) and retry. | -| \`PROOF_FAILURE\` | Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server. | Check that the proof server is running (\`midnight_localnet_status()\`, or the endpoint the user configured); if it is, \`midnight_cache_clear({ wallet: "" })\` then retry. | -| \`PROOF_TIMEOUT\` | ZK proof generation didn't finish within the deadline. | Retry — proofs can be slow under load. | -| \`SYNC_TIMEOUT\` | Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync. | Retry; the cache resumes from the last applied event so progress is preserved. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 80, - body: `| \`PASSPHRASE_REQUIRED\` | A tool needed a secret (a wallet's seed, an account's owner key) and the MCP server has no passphrase. | Ask the user to set \`MN_PASSPHRASE\` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 100, - body: `| \`WALLET_NOT_FOUND\` | Named wallet doesn't exist on disk. | \`midnight_wallet_list()\` — user may have removed it. | -`, - }, - { - text: 'skill-full', - section: 'error-recovery', - order: 120, - body: `| \`TX_REJECTED\` | Chain rejected the submitted transaction (catch-all when no more specific code applies). | Read the message; usually a state mismatch resolved by re-sync + retry. | -`, - }, + // Its error codes' rows in the manual and the full skill, from their definitions. + ...codeGuidancePieces(walletCodes), ], toolsTable: [ { tool: 'midnight_wallet_generate', group: 'wallet-management', order: 10, description: ['Create a named wallet'] }, diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index 505f53a6..bbab1c69 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -185,14 +185,6 @@ const SHELL_PIECES: readonly GuidancePiece[] = [ ─────────── Code Exit Meaning -`, - }, - { - text: 'agent-manual', - section: 'error-codes', - order: 90, - body: ` UNSUPPORTED_NODE 1 Node.js is older than 22 (22.18 for mn grant); - install a current one `, }, { diff --git a/src/lib/code-tables.ts b/src/lib/code-tables.ts new file mode 100644 index 00000000..ba5156ae --- /dev/null +++ b/src/lib/code-tables.ts @@ -0,0 +1,53 @@ +// The tables of error codes that are not agent guidance, from the installed +// packages' code definitions: docs/JSON_CONTRACT.md's, which +// scripts/write-readme-commands.ts writes between its markers (a test fails +// when the file differs), and the lines of `mn manual`'s EXIT CODES block. +// The manual's and the skills' rows come from each package's guidance +// (codeGuidancePieces). + +import type { CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import type { CodeDefinition } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { wrapWords } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { withGeneratedBlock } from './readme-commands.ts'; + +/** The markers around the generated table in docs/JSON_CONTRACT.md. */ +export const JSON_CONTRACT_CODES_START = ''; +export const JSON_CONTRACT_CODES_END = ''; + +/** Every installed package's codes, in their order (a code with none after those that have one, as installed). */ +export function installedCodes(registry: Pick): CodeDefinition[] { + const codes = registry.packages.flatMap((pkg) => pkg.codes ?? []); + const place = (definition: CodeDefinition): number => definition.order ?? Number.POSITIVE_INFINITY; + return codes.map((definition, at) => ({ definition, at })) + .sort((a, b) => place(a.definition) - place(b.definition) || a.at - b.at) + .map(({ definition }) => definition); +} + +/** docs/JSON_CONTRACT.md's table of error codes, as markdown ending with a newline. */ +export function jsonContractCodeTable(registry: Pick): string { + // A pipe splits a table cell, inside a code span too, unless escaped. + const cell = (text: string): string => text.replaceAll('|', '\\|'); + const rows = installedCodes(registry).map(({ code, exitCode, summary }) => `| \`${code}\` | ${exitCode} | ${cell(summary)} |`); + return ['| Code | Exit | Meaning |', '|------|------|---------|', ...rows].join('\n') + '\n'; +} + +/** docs/JSON_CONTRACT.md with the table between its markers replaced by `table`. */ +export function withJsonContractCodeTable(doc: string, table: string): string { + return withGeneratedBlock(doc, 'docs/JSON_CONTRACT.md', JSON_CONTRACT_CODES_START, JSON_CONTRACT_CODES_END, table); +} + +// `mn manual`'s list: the code in a column of 31 (the longest code is 30), its +// exit code, then the meaning from column 38 of an 80-column page. +const MANUAL_CODE_INDENT = 4; +const MANUAL_CODE_COLUMN = 31; +const MANUAL_MEANING_COLUMN = 38; +const MANUAL_WIDTH = 80; + +/** One line or more per installed code for `mn manual`: code, exit code, meaning; `styleCode` colours the code. */ +export function manualCodeLines(registry: Pick, styleCode: (code: string) => string = (code) => code): string[] { + return installedCodes(registry).flatMap(({ code, exitCode, summary }) => { + const [first = '', ...rest] = wrapWords(summary, MANUAL_WIDTH - MANUAL_MEANING_COLUMN); + const head = `${' '.repeat(MANUAL_CODE_INDENT)}${styleCode(code)}${' '.repeat(Math.max(1, MANUAL_CODE_COLUMN - code.length))}${exitCode} `; + return [head + first, ...rest.map((line) => ' '.repeat(MANUAL_MEANING_COLUMN) + line)]; + }); +} diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index 992bde08..da0e4708 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -20,6 +20,7 @@ import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; import { coerceArg } from './arg-coerce.ts'; import { resolvePrivateStateSecretKey } from './private-state-secret.ts'; import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { isTransportFailure } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; // The generated deploy/call script imports SDK packages by bare specifier // (`@midnight-ntwrk/midnight-js-contracts`, `ws`, etc.); without help, Node @@ -182,7 +183,7 @@ async function rpcConnect() { return new Promise((resolve, reject) => { rpcWs = new WebSocket(RPC_URL); rpcWs.on('open', () => resolve(rpcWs)); - rpcWs.on('error', (err) => reject(new Error('Cannot connect to mn serve at ' + RPC_URL + ': ' + err.message))); + rpcWs.on('error', (err) => reject(new Error('Cannot connect to mn serve at ' + RPC_URL + ': ' + err.message, { cause: err }))); setTimeout(() => reject(new Error('Timeout connecting to mn serve at ' + RPC_URL)), 5000); }); } @@ -256,15 +257,24 @@ const PRIVATE_STATE_SECRET_FN = `\nconst resolvePrivateStateSecretKey = (${resol /** Marks the line a generated script reports its failure on, so mn can tell it from progress and warnings. */ export const SCRIPT_ERROR_MARKER = '__MN_ERROR__'; +// isTransportFailure serialized for the generated script (the same +// .toString()-inlining trick as ARG_COERCE_FN): the script names a connection +// it could not make (to mn serve, the indexer, the proof server) itself. +const TRANSPORT_FAILURE_FN = `\nconst isTransportFailure = (${isTransportFailure.toString()});\n`; + /** * First in every generated script: report any failure (a rejected top-level - * await included) as one marked line, its message and the code it carries (mn - * serve's code for a failure there), then exit 1. Without it Node prints the - * uncaught exception with its source context, and that became mn's error. + * await included) as one marked line, its message and its code, then exit 1: + * the code it carries (mn serve's code for a failure there), or NETWORK_ERROR + * for a connection that could not be made, which carries only the socket's + * (ECONNREFUSED) or none. Without it Node prints the uncaught exception with + * its source context, and that became mn's error. */ -export const SCRIPT_PRELUDE = ` +export const SCRIPT_PRELUDE = `${TRANSPORT_FAILURE_FN} const fail = (e) => { - const failure = { message: String(e?.message ?? e), ...(typeof e?.code === 'string' ? { code: e.code } : {}) }; + const carried = typeof e?.code === 'string' && !isTransportFailure({ code: e.code }) ? e.code : undefined; + const code = carried ?? (isTransportFailure(e) ? 'NETWORK_ERROR' : undefined); + const failure = { message: String(e?.message ?? e), ...(code === undefined ? {} : { code }) }; process.stderr.write('\\n${SCRIPT_ERROR_MARKER} ' + JSON.stringify(failure) + '\\n'); process.exit(1); }; diff --git a/src/lib/readme-commands.ts b/src/lib/readme-commands.ts index 330d7029..2f294e23 100644 --- a/src/lib/readme-commands.ts +++ b/src/lib/readme-commands.ts @@ -18,10 +18,15 @@ export function readmeCommandTable(registry: Pick): return ['| Command | Description |', '|---------|-------------|', ...rows].join('\n') + '\n'; } +/** `doc` (the file `name`) with what is between its markers `startMarker` and `endMarker` replaced by `content`. */ +export function withGeneratedBlock(doc: string, name: string, startMarker: string, endMarker: string, content: string): string { + const start = doc.indexOf(startMarker); + const end = doc.indexOf(endMarker); + if (start === -1 || end < start) throw new Error(`${name} has no ${startMarker} … ${endMarker} markers`); + return doc.slice(0, start + startMarker.length) + '\n' + content + doc.slice(end); +} + /** The README with the table between its markers replaced by `table`. */ export function withReadmeCommandTable(readme: string, table: string): string { - const start = readme.indexOf(README_COMMANDS_START); - const end = readme.indexOf(README_COMMANDS_END); - if (start === -1 || end < start) throw new Error(`README.md has no ${README_COMMANDS_START} … ${README_COMMANDS_END} markers`); - return readme.slice(0, start + README_COMMANDS_START.length) + '\n' + table + readme.slice(end); + return withGeneratedBlock(readme, 'README.md', README_COMMANDS_START, README_COMMANDS_END, table); } From c31c4b6d5fc1116630d77b4e98a72b443018cf7c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 12:46:39 -0800 Subject: [PATCH 66/88] Commands declare their error codes, checked against the code (3D) Each command definition declares the error codes it can end with, its own and named sets each package exports (network, wallet, engine, sync, paying, offers, chain), and outcomes it returns without an error; its exit codes follow from the registry. The registry refuses a code no installed package defines. scripts/code-reach.mjs walks each command's handler and what it imports and collects every code it can throw; declared-codes.test.ts fails when a reachable code is undeclared or a declared one can't be reached. The command-running tests also check each error a command ends with is declared. Shown (approved, Y56): mn help and the manual's command pages list the command's own codes and name its sets; help --json carries errorCodes, exitCodes and errorSets; the agent manual and the full skill list the sets once; each MCP tool's description ends with its own codes and set names (7 to 18 words). Suite 2758, beta 180; fresh install; the snapshot changes only in help, help --json, the manuals and the MCP descriptions. --- docs/SKILL.md | 12 + packages/chain/api-report.md | 1 + packages/chain/src/commands/chain.codes.ts | 8 +- .../chain/src/commands/status.definition.ts | 8 + packages/chain/src/commands/tx.definition.ts | 2 + packages/cli-core/api-report.md | 41 ++- .../src/commands/config.definition.ts | 2 + packages/cli-core/src/commands/core.codes.ts | 23 +- .../cli-core/src/lib/command-definition.ts | 102 +++++- packages/cli-core/src/lib/error-codes.ts | 12 + scripts/check-layering.d.mts | 4 + scripts/check-layering.mjs | 41 ++- scripts/check-process-safety.d.mts | 2 + scripts/check-process-safety.mjs | 4 +- scripts/code-reach.d.mts | 23 ++ scripts/code-reach.mjs | 318 ++++++++++++++++++ src/__tests__/agent-guidance.test.ts | 1 + src/__tests__/command-cancellation.test.ts | 27 +- src/__tests__/command-registry.test.ts | 3 +- src/__tests__/declared-codes.test.ts | 149 ++++++++ src/__tests__/error-code-registry.test.ts | 73 +++- .../fixtures/code-reach/fixture.definition.ts | 14 + src/__tests__/fixtures/code-reach/handler.ts | 7 + src/__tests__/fixtures/code-reach/refuses.ts | 7 + src/__tests__/help-agent.test.ts | 12 + src/__tests__/help.test.ts | 41 +++ src/__tests__/helpers/expect-declared.ts | 52 +++ src/__tests__/json-fields.test.ts | 3 +- src/__tests__/layering.test.ts | 7 + src/__tests__/manual-command.test.ts | 14 + src/__tests__/mcp-registry-tools.test.ts | 21 +- .../mcp-server-concurrent-calls.test.ts | 9 +- src/__tests__/mcp-server-confirmation.test.ts | 10 +- src/__tests__/mcp-server-progress.test.ts | 9 +- .../mcp-server-unknown-parameter.test.ts | 6 +- src/__tests__/network-cancellation.test.ts | 3 +- src/commands/address.definition.ts | 3 + src/commands/airdrop.definition.ts | 4 + src/commands/balance.definition.ts | 4 + src/commands/cache.definition.ts | 3 + src/commands/contract.definition.ts | 4 + src/commands/dev.definition.ts | 6 + src/commands/dust.definition.ts | 4 + src/commands/generate.definition.ts | 3 + src/commands/genesis-address.definition.ts | 2 + src/commands/grant.definition.ts | 4 + src/commands/help.definition.ts | 2 + src/commands/help.ts | 8 + src/commands/info.definition.ts | 3 + src/commands/inspect-cost.definition.ts | 3 + src/commands/localnet.definition.ts | 2 + src/commands/manual.definition.ts | 2 + src/commands/manual.ts | 8 +- src/commands/serve.definition.ts | 4 + src/commands/swap.definition.ts | 4 + src/commands/test.definition.ts | 9 + src/commands/transfer.definition.ts | 4 + src/commands/wallet.codes.ts | 8 +- src/commands/wallet.definition.ts | 3 + src/lib/agent-manual.ts | 11 +- src/lib/code-tables.ts | 39 ++- src/lib/mcp/registry-tools.ts | 23 +- src/lib/mcp/skills.ts | 12 +- 63 files changed, 1194 insertions(+), 59 deletions(-) create mode 100644 scripts/code-reach.d.mts create mode 100644 scripts/code-reach.mjs create mode 100644 src/__tests__/declared-codes.test.ts create mode 100644 src/__tests__/fixtures/code-reach/fixture.definition.ts create mode 100644 src/__tests__/fixtures/code-reach/handler.ts create mode 100644 src/__tests__/fixtures/code-reach/refuses.ts create mode 100644 src/__tests__/helpers/expect-declared.ts diff --git a/docs/SKILL.md b/docs/SKILL.md index 4ab4ab44..c4af1832 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -182,6 +182,18 @@ Every MCP tool error returns `{ error: true, code: , message: import('./status.ts'), mcp: { tools: [] }, }; diff --git a/packages/chain/src/commands/tx.definition.ts b/packages/chain/src/commands/tx.definition.ts index d9cbdb42..a613bb8f 100644 --- a/packages/chain/src/commands/tx.definition.ts +++ b/packages/chain/src/commands/tx.definition.ts @@ -1,6 +1,7 @@ // The `tx` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; export const txDefinition: CommandDefinition = { name: 'tx', @@ -83,6 +84,7 @@ export const txDefinition: CommandDefinition = { intro: { brief: 'What became of a transaction', order: 12.6 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, 'NETWORK_ERROR'] }, load: () => import('./tx.ts'), mcp: { tools: [ diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 8c6a025e..6242d20d 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -239,6 +239,18 @@ export declare const coreCodes: readonly [ readonly recovery: "Cancel the offer first (`mn swap cancel`), or wait until it is taken."; } ]; +export declare const EVERY_COMMAND: readonly [ + "INVALID_ARGS", + "CANCELLED", + "UNKNOWN", + "UNSUPPORTED_NODE", + "NO_STATE_ROOT" +]; +export declare const RESOLVES_NETWORK: import("../lib/error-codes.ts").CodeSet; +export declare const LOADS_ENGINE: import("../lib/error-codes.ts").CodeSet; +export declare const ENGINE_SYNC: import("../lib/error-codes.ts").CodeSet; +export declare const PAYS: import("../lib/error-codes.ts").CodeSet; +export declare const READS_OFFERS: import("../lib/error-codes.ts").CodeSet; ``` ## `@kuiralabs/midnight-cli-core/commands/core.guidance` @@ -518,7 +530,7 @@ export declare function getValidConfigKeys(): readonly string[]; ```ts import { type ParsedArgs } from "./argv.ts"; import { type PackageGuidance } from "./agent-guidance.ts"; -import type { CodeDefinition, CodeRegistry } from "./error-codes.ts"; +import type { CodeDefinition, CodeRegistry, CodeSet } from "./error-codes.ts"; import type { CallContext, CommandOutcome } from "./call-context.ts"; import type { Host } from "./host.ts"; export interface ParamSchema { @@ -617,6 +629,14 @@ export interface ToolDefinition { readonly confirmation?: ToolConfirmation; readonly order: number; } +export interface DeclaredOutcome { + readonly exitCode: number; + readonly when: string; +} +export interface CommandErrors { + readonly codes: readonly (string | CodeSet)[]; + readonly outcomes?: readonly DeclaredOutcome[]; +} export interface CommandDefinition { readonly name: string; readonly order: number; @@ -630,6 +650,7 @@ export interface CommandDefinition { }; readonly needsWalletSdk: boolean; readonly shell: ShellCall; + readonly errors: CommandErrors; readonly load: () => Promise; readonly mcp?: { readonly tools: readonly ToolDefinition[]; @@ -662,6 +683,12 @@ export declare class CommandDefinitionError extends Error { } export declare function toolInputSchema(command: CommandDefinition, tool: ToolDefinition, globalFlags: readonly FlagDefinition[]): ToolInputSchema; export declare function toolArgv(tool: RegisteredTool, params: Readonly>): ParsedArgs; +export declare function declaredCodes(command: CommandDefinition): string[]; +export declare function declaredSets(command: CommandDefinition): CodeSet[]; +export declare function declaredCodeSets(registry: Pick): CodeSet[]; +export declare function commandErrorCodes(registry: Pick, command: CommandDefinition): CodeDefinition[]; +export declare function commandOwnCodes(registry: Pick, command: CommandDefinition): CodeDefinition[]; +export declare function commandExitCodes(registry: Pick, command: CommandDefinition): number[]; export declare function createCommandRegistry(commands: readonly CommandDefinition[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; export declare function createPackageRegistry(packages: readonly CommandPackage[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; export declare function flagsSectionLines(command: CommandDefinition): string[]; @@ -672,8 +699,13 @@ export interface CommandHelpSpec { readonly flags?: readonly string[]; readonly examples?: readonly string[]; readonly jsonFields?: Readonly>; + readonly errorCodes: readonly CodeDefinition[]; + readonly ownCodes: readonly CodeDefinition[]; + readonly errorSets: readonly string[]; + readonly outcomes: readonly DeclaredOutcome[]; + readonly exitCodes: readonly number[]; } -export declare function commandHelpSpecs(registry: Pick): CommandHelpSpec[]; +export declare function commandHelpSpecs(registry: Pick): CommandHelpSpec[]; export declare function introBriefs(registry: Pick): [ name: string, brief: string @@ -1216,6 +1248,11 @@ export declare class CodeDefinitionError extends Error { constructor(message: string); } export declare function defineCodes(codes: T): T; +export interface CodeSet { + readonly name: string; + readonly codes: readonly string[]; +} +export declare function defineCodeSet(name: string, codes: readonly string[]): CodeSet; ``` ## `@kuiralabs/midnight-cli-core/lib/error-trim` diff --git a/packages/cli-core/src/commands/config.definition.ts b/packages/cli-core/src/commands/config.definition.ts index 79fdcda6..56725c20 100644 --- a/packages/cli-core/src/commands/config.definition.ts +++ b/packages/cli-core/src/commands/config.definition.ts @@ -2,6 +2,7 @@ import type { CommandDefinition } from '../lib/command-definition.ts'; import { INDEXER_GRAPHQL_WS_PATH } from '../lib/constants.ts'; +import { RESOLVES_NETWORK } from './core.codes.ts'; export const configDefinition: CommandDefinition = { name: 'config', @@ -59,6 +60,7 @@ export const configDefinition: CommandDefinition = { intro: { brief: 'Manage CLI config', order: 13 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK] }, load: () => import('./config.ts'), mcp: { tools: [ diff --git a/packages/cli-core/src/commands/core.codes.ts b/packages/cli-core/src/commands/core.codes.ts index fc63b95d..92ecc710 100644 --- a/packages/cli-core/src/commands/core.codes.ts +++ b/packages/cli-core/src/commands/core.codes.ts @@ -3,8 +3,11 @@ // SDK set and its layout, the Node.js version, the state root, the payer, a // failed command), and those of the engine contract, which every engine // raises (proofs, transactions, stale state, sync, Dust and balance, swap offers). +// Beside them, the sets of its codes a command definition declares (its +// errors.codes) by what the command does; scripts/code-reach.mjs holds each +// definition to what its modules can throw. -import { defineCodes } from '../lib/error-codes.ts'; +import { defineCodeSet, defineCodes } from '../lib/error-codes.ts'; import { EXIT_CANCELLED, EXIT_GENERAL_ERROR, @@ -49,3 +52,21 @@ export const coreCodes = defineCodes([ { code: 'OFFER_EXPIRED', exitCode: EXIT_INVALID_ARGS, order: 350, summary: 'A swap offer is past the expiry its maker set.', recovery: 'Ask the maker for a new one.' }, { code: 'OFFER_COINS_IN_USE', exitCode: EXIT_INVALID_ARGS, order: 360, summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it.", recovery: 'Cancel the offer first (`mn swap cancel`), or wait until it is taken.' }, ]); + +/** What every command can end with, which no definition declares: the shell's usage and flag checks, cancellation, an error carrying no code, the Node.js version, the state root. */ +export const EVERY_COMMAND = ['INVALID_ARGS', 'CANCELLED', 'UNKNOWN', 'UNSUPPORTED_NODE', 'NO_STATE_ROOT'] as const; + +/** Resolving a network and its endpoints: several local stacks, Blockfrost's project id and limits, an endpoint shut down. */ +export const RESOLVES_NETWORK = defineCodeSet('network', ['AMBIGUOUS_LOCAL_STACKS', 'BLOCKFROST_PROJECT_ID_REQUIRED', 'BLOCKFROST_PROJECT_ID_REJECTED', 'BLOCKFROST_LIMIT_REACHED', 'ENDPOINT_SHUT_DOWN']); + +/** Asking the host for an engine: the other SDK set loaded in the process, or an install without its shrinkwrap. */ +export const LOADS_ENGINE = defineCodeSet('engine', ['OTHER_SDK_SET', 'MIXED_SDK_LAYOUT']); + +/** Syncing a wallet through an engine: a connection that failed, a sync past its deadline, a cache the chain no longer fits. */ +export const ENGINE_SYNC = defineCodeSet('sync', ['NETWORK_ERROR', 'SYNC_TIMEOUT', 'STALE_CACHE']); + +/** Paying for a transaction: the node's refusals, the proof, the Dust for the fee, the NIGHT, coins an open swap offer holds. */ +export const PAYS = defineCodeSet('paying', ['TX_REJECTED', 'STALE_UTXO', 'INVALID_DUST_PROOF', 'PROOF_TIMEOUT', 'PROOF_FAILURE', 'DUST_REQUIRED', 'DUST_GENERATING', 'INSUFFICIENT_BALANCE', 'OFFER_COINS_IN_USE']); + +/** Reading a swap offer's bytes and terms. */ +export const READS_OFFERS = defineCodeSet('offers', ['NOT_AN_OFFER', 'TERMS_MISMATCH']); diff --git a/packages/cli-core/src/lib/command-definition.ts b/packages/cli-core/src/lib/command-definition.ts index 7fb9cd1a..d87d905e 100644 --- a/packages/cli-core/src/lib/command-definition.ts +++ b/packages/cli-core/src/lib/command-definition.ts @@ -8,12 +8,16 @@ // The shell's dispatch and flag checks, help, the manual, the intro and the // MCP server's tools all read the registry; each tool's schema is generated // from what it takes and its command's flags. A package is installed with its -// commands and its agent guidance. +// commands and its agent guidance. Each definition declares the error codes +// its command can end with beyond those every command can, which help, the +// manuals and the tools' descriptions show; scripts/code-reach.mjs holds the +// declaration to what the command's modules can throw. import { getValidNetworkNames } from './network.ts'; import { FULL_FLAG, type ParsedArgs } from './argv.ts'; import { type PackageGuidance, type ToolsTableRow, assertDistinctPlaces } from './agent-guidance.ts'; -import type { CodeDefinition, CodeRegistry } from './error-codes.ts'; +import type { CodeDefinition, CodeRegistry, CodeSet } from './error-codes.ts'; +import { EVERY_COMMAND } from '../commands/core.codes.ts'; import type { CallContext, CommandOutcome } from './call-context.ts'; import type { Host } from './host.ts'; @@ -185,6 +189,20 @@ export interface ToolDefinition { readonly order: number; } +/** An exit code a command's handler returns without throwing, and when. */ +export interface DeclaredOutcome { + readonly exitCode: number; + readonly when: string; +} + +/** What a command can end with besides success and what every command can (EVERY_COMMAND). */ +export interface CommandErrors { + /** Its error codes: each a code of its own, or a named set of codes a package exports beside its codes (READS_CHAIN). */ + readonly codes: readonly (string | CodeSet)[]; + /** The exit codes its handler returns without throwing (a test run whose tests failed). */ + readonly outcomes?: readonly DeclaredOutcome[]; +} + export interface CommandDefinition { readonly name: string; /** Its place among the installed commands, which help lists in this order; a plugin takes one no other command has. */ @@ -200,6 +218,8 @@ export interface CommandDefinition { /** It starts the wallet SDK: the shell gives it more heap and exits when it ends. */ readonly needsWalletSdk: boolean; readonly shell: ShellCall; + /** The error codes it can end with beyond EVERY_COMMAND's, and its exit codes without an error. */ + readonly errors: CommandErrors; /** Loads the handler. A static `import()` specifier, so the MCP server's bundler finds it. */ readonly load: () => Promise; /** Present when the MCP server can load its handler; its tools, possibly none. */ @@ -409,6 +429,63 @@ export function toolArgv(tool: RegisteredTool, params: Readonly (typeof entry === 'string' ? [entry] : [...entry.codes])); +} + +/** The named sets a definition declares, in the order declared. */ +export function declaredSets(command: CommandDefinition): CodeSet[] { + return command.errors.codes.flatMap((entry) => (typeof entry === 'string' ? [] : [entry])); +} + +/** Every set the commands declare, each once, in the order first declared; refuses two sets of one name. */ +export function declaredCodeSets(registry: Pick): CodeSet[] { + const byName = new Map(); + for (const set of registry.commands.flatMap(declaredSets)) { + const known = byName.get(set.name); + if (known !== undefined && known.codes.join() !== set.codes.join()) throw new CommandDefinitionError(`two code sets are named "${set.name}"`); + byName.set(set.name, known ?? set); + } + return [...byName.values()]; +} + +/** Refuses a declared code no installed package defines, one every command can end with, and one declared twice. */ +function checkDeclaredCodes(command: CommandDefinition, defined: ReadonlyMap): void { + const every: readonly string[] = EVERY_COMMAND; + const declared = declaredCodes(command); + assertUnique(declared, `${command.name}: error code`); + for (const code of declared) { + if (every.includes(code)) throw new CommandDefinitionError(`${command.name} declares ${code}, which every command can end with`); + if (!defined.has(code)) throw new CommandDefinitionError(`${command.name} declares ${code}, which no installed package defines`); + } +} + +/** The definitions of `codes`, in the code tables' order; a code no installed package defines is left out. */ +function inTableOrder(registry: Pick, codes: readonly string[]): CodeDefinition[] { + return codes + .flatMap((code) => registry.code(code) ?? []) + .sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.code.localeCompare(b.code)); +} + +/** The definitions of every error code a command declares, its sets' included, in the code tables' order. */ +export function commandErrorCodes(registry: Pick, command: CommandDefinition): CodeDefinition[] { + return inTableOrder(registry, declaredCodes(command)); +} + +/** The definitions of a command's own codes, those it declares in no set, in the code tables' order. */ +export function commandOwnCodes(registry: Pick, command: CommandDefinition): CodeDefinition[] { + return inTableOrder(registry, command.errors.codes.filter((entry): entry is string => typeof entry === 'string')); +} + +/** The exit codes a command can end with: success, its own codes' and every command's, and its outcomes', ascending. */ +export function commandExitCodes(registry: Pick, command: CommandDefinition): number[] { + const own = commandErrorCodes(registry, command).map((definition) => definition.exitCode); + const every = EVERY_COMMAND.flatMap((code) => registry.code(code)?.exitCode ?? []); + const outcomes = (command.errors.outcomes ?? []).map((outcome) => outcome.exitCode); + return [...new Set([0, ...own, ...every, ...outcomes])].sort((a, b) => a - b); +} + /** Collects definitions into a registry, refusing any that contradict each other. */ export function createCommandRegistry( commands: readonly CommandDefinition[], @@ -478,6 +555,8 @@ export function createPackageRegistry( const codes = packages.flatMap((pkg) => pkg.codes ?? []); assertUnique(codes.map((definition) => definition.code), 'error code'); const byCode = new Map(codes.map((definition) => [definition.code, definition])); + for (const command of commands) checkDeclaredCodes(command, byCode); + declaredCodeSets({ commands }); return { ...createCommandRegistry(commands, globalFlags, globalFlagsHelp), packages, code: (code) => byCode.get(code) }; } @@ -487,7 +566,7 @@ export function flagsSectionLines(command: CommandDefinition): string[] { typeof entry === 'string' ? [entry] : command.flags.find((flag) => flag.name === entry.flag)?.help ?? []); } -/** One command as `help `, `help --json` and `manual` show it: its help, the Flags section rendered. */ +/** One command as `help `, `help --json` and `manual` show it: its help, the Flags section rendered, its codes. */ export interface CommandHelpSpec { readonly name: string; readonly description: string; @@ -495,10 +574,20 @@ export interface CommandHelpSpec { readonly flags?: readonly string[]; readonly examples?: readonly string[]; readonly jsonFields?: Readonly>; + /** Every error code it declares, its sets' included, in the code tables' order, each with its exit code and summary. */ + readonly errorCodes: readonly CodeDefinition[]; + /** Its own codes: those it declares in no set. */ + readonly ownCodes: readonly CodeDefinition[]; + /** The names of the sets of codes it declares, in the order declared. */ + readonly errorSets: readonly string[]; + /** The exit codes it can end with without an error besides success (a test run whose tests failed). */ + readonly outcomes: readonly DeclaredOutcome[]; + /** Every exit code it can end with, ascending. */ + readonly exitCodes: readonly number[]; } /** Every command help lists, in the registry's order; a command with no help is left out. */ -export function commandHelpSpecs(registry: Pick): CommandHelpSpec[] { +export function commandHelpSpecs(registry: Pick): CommandHelpSpec[] { return registry.commands.flatMap((command) => { const help = command.help; if (help === undefined) return []; @@ -509,6 +598,11 @@ export function commandHelpSpecs(registry: Pick): C ...(help.flags === undefined ? {} : { flags: flagsSectionLines(command) }), ...(help.examples === undefined ? {} : { examples: [...help.examples] }), ...(help.jsonFields === undefined ? {} : { jsonFields: { ...help.jsonFields } }), + errorCodes: commandErrorCodes(registry, command), + ownCodes: commandOwnCodes(registry, command), + errorSets: declaredSets(command).map((set) => set.name), + outcomes: [...(command.errors.outcomes ?? [])], + exitCodes: commandExitCodes(registry, command), }]; }); } diff --git a/packages/cli-core/src/lib/error-codes.ts b/packages/cli-core/src/lib/error-codes.ts index 21e354d6..4ceecf5d 100644 --- a/packages/cli-core/src/lib/error-codes.ts +++ b/packages/cli-core/src/lib/error-codes.ts @@ -39,3 +39,15 @@ export function defineCodes(codes: T) } return codes; } + +/** A set of codes a package exports for command definitions to declare at once, with the plain name help and the tools' descriptions show it by. */ +export interface CodeSet { + /** One word: "the network codes". */ + readonly name: string; + readonly codes: readonly string[]; +} + +/** A named set of codes, as a package exports it beside its codes. */ +export function defineCodeSet(name: string, codes: readonly string[]): CodeSet { + return { name, codes }; +} diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 663d4609..1e3c5480 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -9,3 +9,7 @@ export function findLayeringProblems(): { unhomed: string[]; violations: { home: export const WORKSPACE_PACKAGES: readonly { name: string; dir: string; prefix?: string }[]; /** A file's path as the homes read it: under its package's source folder, or under src/. */ export function relOf(file: string): string; +/** A file's imports: each specifier, its line, whether it is an `import()`, and whether it brings in types alone. */ +export function importsOf(file: string): { specifier: string; line: number; dynamic: boolean; typeOnly: boolean }[]; +/** The source file an import of `file` names; undefined for an outside package. */ +export function importTarget(file: string, specifier: string): string | undefined; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index e9140505..563db573 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -6,12 +6,14 @@ // // Libraries never call commands, and commands never call another package's // commands: a command is an adapter over library functions, and only the shell -// and the MCP server dispatch to one. +// and the MCP server dispatch to one. A package's codes file is data, not a +// command: a package below lends its sets of codes to the definitions above. // // Usage: node scripts/check-layering.mjs // Imported, it exports sourceFiles and homeOf: which package each file of src/ is in; -// importRule and guidanceRule: the rule an import breaks; and findLayeringProblems, -// which the suite runs. Exits 1 when a file has no package, or an import breaks a rule. +// importRule and guidanceRule: the rule an import breaks; findLayeringProblems, +// which the suite runs; and importsOf and importTarget, a file's imports and the +// files they name (scripts/code-reach.mjs walks them). Exits 1 when a file has no package, or an import breaks a rule. import { readFileSync, readdirSync, statSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; @@ -187,7 +189,9 @@ export function importRule(fromRel, toRel) { const guidance = guidanceRule(fromRel, toRel); if (guidance !== undefined) return guidance; const isCommand = (path) => path.startsWith('commands/'); - const callsCommand = isCommand(toRel) && (!isCommand(fromRel) || targetHome !== home); + // A package's codes (.codes.ts) are data, not a command: its own code and the packages above it name its sets of codes. + const isCodes = (path) => /\.codes\.ts$/.test(path); + const callsCommand = isCommand(toRel) && !isCodes(toRel) && (!isCommand(fromRel) || targetHome !== home); if (callsCommand && !DISPATCHERS.has(home)) return `${isCommand(fromRel) ? 'command' : 'library'} → ${targetHome} command`; if (targetHome === 'engine' && home !== 'engine') { return fromRel === ENGINE_LOADER ? undefined : `${home} → engine (reach it through ${ENGINE_LOADER})`; @@ -197,16 +201,41 @@ export function importRule(fromRel, toRel) { return undefined; } -function importsOf(file) { +/** + * Whether the import ending at `index` brings in types alone: `import type …` + * or `export type … from`, or a `typeof import(…)` in a type. Such an import + * runs nothing, so it adds no code a module can throw (scripts/code-reach.mjs). + */ +function isTypeOnly(source, match) { + const before = source.slice(0, match.index); + if (match[0].includes('(')) return /\btypeof\s+$/.test(before); + if (!/^from\b/.test(match[0])) return false; + const start = Math.max(before.lastIndexOf('import '), before.lastIndexOf('export ')); + return start >= 0 && /^(import|export)\s+type\s/.test(source.slice(start, match.index)); +} + +/** A file's imports: each specifier, its line, whether it is an `import()`, and whether it brings in types alone. */ +export function importsOf(file) { const source = readFileSync(file, 'utf8'); const found = []; for (const match of source.matchAll(IMPORT)) { const line = source.slice(0, match.index).split('\n').length; - found.push({ specifier: match[2], line }); + found.push({ specifier: match[2], line, dynamic: match[0].includes('('), typeOnly: isTypeOnly(source, match) }); } return found; } +/** + * The source file an import of `file` names: a relative path, or a workspace + * package's (`@kuiralabs/midnight-cli-core/lib/errors` is its src/lib/errors.ts, + * the package name alone its index); undefined for an outside package. + */ +export function importTarget(file, specifier) { + const pkg = WORKSPACE_PACKAGES.find((p) => specifier === p.name || specifier.startsWith(p.name + '/')); + if (pkg !== undefined) return join(pkg.dir, `${specifier === pkg.name ? 'index' : specifier.slice(pkg.name.length + 1)}.ts`); + return specifier.startsWith('.') ? resolve(dirname(file), specifier) : undefined; +} + /** Files with no package, and imports that break a rule. */ export function findLayeringProblems() { const unhomed = []; diff --git a/scripts/check-process-safety.d.mts b/scripts/check-process-safety.d.mts index e825ea18..8801a3c0 100644 --- a/scripts/check-process-safety.d.mts +++ b/scripts/check-process-safety.d.mts @@ -11,3 +11,5 @@ export function findViolations( src?: string, allowedSetters?: Record>, ): { file: string; line: number; rule: string; name?: string }[]; +/** The source with string, template-text, regex and comment contents blanked, every offset and line kept. */ +export function codeOnly(source: string): string; diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index e8222b71..b27c4ca9 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -27,7 +27,7 @@ // Usage: node scripts/check-process-safety.mjs // Exits 1 when a library does something the rules above forbid, or any code // breaks the module-state rules, and the allowlist doesn't name it. Imported, it exports -// findViolations. +// findViolations, and codeOnly, which blanks strings and comments. import { readFileSync } from 'node:fs'; import { relative, resolve, dirname, join } from 'node:path'; @@ -112,7 +112,7 @@ const SETTER_NAME = /^(set\w*Source|set\w*Sink|setPrompter|setEngineLoader)$/; * with spaces, keeping line breaks. The code inside a template's `${…}` is * kept and scanned like any other code. */ -function codeOnly(source) { +export function codeOnly(source) { let out = ''; let i = 0; const blank = (s) => s.replace(/[^\n]/g, ' '); diff --git a/scripts/code-reach.d.mts b/scripts/code-reach.d.mts new file mode 100644 index 00000000..18200d60 --- /dev/null +++ b/scripts/code-reach.d.mts @@ -0,0 +1,23 @@ +// Types for what scripts/code-reach.mjs exports when imported. + +/** A site whose code is not a literal in the code: the codes it can carry, and why. */ +export interface DynamicSite { + readonly codes: readonly string[]; + readonly why: string; +} + +export class CodeReachError extends Error {} +export const DYNAMIC_CLASSES: Readonly>; +export const DYNAMIC_MODULES: Readonly>; +export const ENGINE_PARTS: Readonly>; +export const ENGINE_SITES: readonly { readonly site: RegExp; readonly reaches: readonly string[] }[]; +export const CUT_IMPORTS: readonly (readonly [from: string, to: string])[]; +export const SHELL_PROVISIONS: Readonly>; +/** The codes a module's own code can throw. */ +export function moduleCodes(file: string): Set; +/** The codes the entry modules reach: each, with the chain of modules from an entry to the first one throwing it. */ +export function codeReach(entries: readonly string[]): Map; +/** Each command definition's entry modules (paths from the repository's root). */ +export function commandEntries(files?: readonly string[]): { name: string; definition: string; handler: string; provisions: ('payer' | 'protectors')[]; entries: string[] }[]; +/** Where a command's declared codes and its reachable ones part. */ +export function declaredCodeProblems(name: string, declared: readonly string[], reached: ReadonlyMap, everyCommand: readonly string[]): string[]; diff --git a/scripts/code-reach.mjs b/scripts/code-reach.mjs new file mode 100644 index 00000000..e092abcd --- /dev/null +++ b/scripts/code-reach.mjs @@ -0,0 +1,318 @@ +#!/usr/bin/env node +// Which error codes each command can end with, read from the code. From a +// command's handler module (its definition's load() target), every module it +// imports, statically or dynamically (type-only imports run nothing and are +// left out), and in each module every coded error it constructs: `new X(` of a +// class whose `readonly code` is a literal, its own or inherited, or an +// EngineError given a literal code. Errors whose code is not a literal in the +// code are read from two tables, each entry with its reason (DYNAMIC_CLASSES, +// DYNAMIC_MODULES); a module constructing a class whose code is not a literal +// and that the first table lacks fails the scan. +// +// Reaches that don't show as imports are added: +// - the engine: a module that asks the host for one (`engines.load(`, +// `.for(`, `.any(`) reaches the host's engines and loads every shipped +// engine's index; one that uses a part of an engine (its keys, ledger, +// contracts, readers or wallet) reaches that part's modules (ENGINE_SITES); +// - the shell's payer and protectors, given to a command whose definition +// asks for them (SHELL_PROVISIONS). +// And one import is not followed: a definition's dynamic ones (its load() and +// its tools' checks), which run only when the shell or the MCP server calls +// them, not when help reads the registry. +// +// Module granularity: a module that can throw a code anywhere counts for every +// command that reaches it. +// +// Usage: node scripts/code-reach.mjs +// Prints each command's reachable codes. Imported, it exports codeReach (the +// codes some entry modules reach), commandEntries (each definition's entry +// modules), the tables, and declaredCodeProblems, which the suite runs +// (src/__tests__/declared-codes.test.ts). + +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { importTarget, importsOf, sourceFiles } from './check-layering.mjs'; +import { codeOnly } from './check-process-safety.mjs'; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const fromRoot = (path) => join(ROOT, path); +const shown = (file) => relative(ROOT, file); + +/** Thrown when the code holds a coded error the scan can't read. */ +export class CodeReachError extends Error { + constructor(message) { + super(message); + this.name = 'CodeReachError'; + } +} + +// What the engine contract's typed errors report: toEngineError's and +// withEngineCode's codes, read from an SDK or node failure's shape and words. +const ENGINE_FAILURE_CODES = ['NETWORK_ERROR', 'SYNC_TIMEOUT', 'STALE_CACHE', 'INSUFFICIENT_BALANCE', 'DUST_REQUIRED', 'TX_REJECTED', 'STALE_UTXO', 'INVALID_DUST_PROOF', 'PROOF_TIMEOUT', 'PROOF_FAILURE']; + +/** + * Classes whose code is not a literal in the code, and the codes their + * construction can carry, with why. EngineError given a literal code counts + * that code instead. + */ +export const DYNAMIC_CLASSES = { + EngineError: { + codes: ENGINE_FAILURE_CODES, + why: "sdk-errors' typedEngineError makes one for an engine code no subclass names (a refusal's TX_REJECTED), or for a code a DApp connector marked an error with", + }, + TransactionRefusedError: { + codes: ['TX_REJECTED', 'STALE_UTXO', 'INVALID_DUST_PROOF'], + why: "its code is a RefusalCode: the node's reason makes it a stale coin, an invalid Dust proof or another refusal", + }, + ContractScriptError: { + codes: ENGINE_FAILURE_CODES, + why: "a contract script reports the code its failure carried: mn serve's code for a failure there (the engine's, marked by withEngineCode), or NETWORK_ERROR for a connection the script could not make", + }, + PrepStepFailedError: { + codes: [], + why: "it carries its failed step's own error's code, which the step's modules already count", + }, +}; + +/** Modules that give errors a code read from their shape or words, not by constructing a coded class, with why. */ +export const DYNAMIC_MODULES = { + 'packages/cli-core/src/lib/sdk-errors.ts': { + codes: ENGINE_FAILURE_CODES, + why: "toEngineError and withEngineCode name an SDK or node failure by the engine contract's codes", + }, + 'packages/cli-core/src/lib/transport-failure.ts': { + codes: ['NETWORK_ERROR'], + why: 'withTransportCode reports a connection that could not be made as a NetworkError', + }, +}; + +/** The engines this build ships, each a workspace package with the same modules. */ +const ENGINE_SETS = ['rc', 'beta']; + +/** + * The parts of an Engine and the modules of an engine's package each is made + * of (its index assembles them); a test holds this to both engines' indexes. + */ +export const ENGINE_PARTS = { + keys: ['derive-address.ts', 'addresses.ts', 'dust-direct-cache.ts', 'shielded-direct-cache.ts'], + ledger: ['ledger-parameters.ts', 'tx-inspect.ts', 'offer-reader.ts'], + contracts: ['contract-providers.ts', 'contract-scripts.ts'], + readers: ['shielded-direct-cache.ts'], + wallet: ['wallet.ts', 'wallet-data-repository.ts'], +}; + +const engineModules = (files) => ENGINE_SETS.flatMap((set) => files.map((file) => `packages/engine-${set}/src/${file}`)); + +/** + * Calls that reach an engine, and the modules they reach. Asking the host for + * one (`engines.load(`, `.for(`, `.any(`) reaches the host's engines and + * loads every engine's index; using a part of one (`engine.keys.…`, `{ keys } + * = engine`; for the wallet, calling an operation or taking the wallet from a + * loaded engine) reaches that part's modules. + */ +export const ENGINE_SITES = [ + { + site: /\bengines\s*\.\s*(load|for|any)\s*\(/, + reaches: ['packages/cli-core/src/lib/host.ts', ...engineModules(['index.ts'])], + }, + ...['keys', 'ledger', 'contracts', 'readers'].map((part) => ({ + site: new RegExp(`\\.\\s*${part}\\b(?!\\s*\\()|\\{[^{}=]*\\b${part}\\b[^{}=]*\\}\\s*=\\s*(await\\b|engine\\b)`), + reaches: engineModules(ENGINE_PARTS[part]), + })), + { + site: /\.\s*wallet\s*\.\s*\w+\s*\(|\{\s*wallet\s*:\s*\w+\s*\}\s*=\s*await\b/, + reaches: engineModules(ENGINE_PARTS.wallet), + }, +]; + +/** Imports the walk doesn't follow: an engine's index imports its parts' modules, which only a use of that part reaches (ENGINE_SITES). */ +export const CUT_IMPORTS = ENGINE_SETS.flatMap((set) => [...new Set(Object.values(ENGINE_PARTS).flat())].map((file) => [`packages/engine-${set}/src/index.ts`, `packages/engine-${set}/src/${file}`])); + +/** What the shell gives a command whose definition's `shell` asks for it, and the module it loads. */ +export const SHELL_PROVISIONS = { + payer: 'src/lib/serve-payer.ts', + protectors: 'src/lib/grant/account-protector.ts', +}; + +// The class EngineError takes its code as its first argument: `new EngineError('X', …)`, or a subclass's `super('X', …)`. +const CODE_FROM_FIRST_ARGUMENT = 'EngineError'; + +/** The literal string starting at `quote` in `source`. */ +function literalAt(source, quote) { + return source.slice(quote + 1, source.indexOf(source[quote], quote + 1)); +} + +/** The offset of the brace that closes the one at `open`, in code with strings and comments blanked. */ +function closingBrace(code, open) { + let depth = 0; + for (let i = open; i < code.length; i += 1) { + if (code[i] === '{') depth += 1; + else if (code[i] === '}' && --depth === 0) return i; + } + return code.length; +} + +/** The classes a file declares: name, parent, and its own code (a literal, `dynamic`, or one passed to super). */ +function classesIn(file) { + const source = readFileSync(file, 'utf8'); + const code = codeOnly(source); + const found = []; + for (const match of code.matchAll(/\bclass\s+(\w+)(?:\s+extends\s+(\w+))?[^{]*\{/g)) { + const open = match.index + match[0].length - 1; + const body = code.slice(open, closingBrace(code, open)); + const own = /\breadonly\s+code\b\s*(:[^=;\n]*)?(=\s*)?/.exec(body); + let ownCode; + if (own !== null) ownCode = own[2] === undefined ? 'dynamic' : literalAt(source, open + own.index + own[0].length); + const superCall = /\bsuper\(\s*['"]/.exec(body); + found.push({ name: match[1], parent: match[2], file, ownCode, superCode: superCall === null ? undefined : literalAt(source, open + superCall.index + superCall[0].length - 1) }); + } + return found; +} + +/** Every class of the source files, by name: a name declared twice must mean the same code. */ +function classTable(files) { + const byName = new Map(); + for (const file of files) for (const cls of classesIn(file)) byName.set(cls.name, [...(byName.get(cls.name) ?? []), cls]); + const resolved = new Map(); + const codeOf = (name, seen = new Set()) => { + if (resolved.has(name)) return resolved.get(name); + const all = byName.get(name); + if (all === undefined || seen.has(name)) return undefined; + seen.add(name); + const each = all.map((cls) => { + if (cls.ownCode !== undefined) return cls.ownCode; + if (cls.superCode !== undefined && cls.parent !== undefined && descendsFrom(cls.parent, CODE_FROM_FIRST_ARGUMENT)) return cls.superCode; + return cls.parent === undefined ? undefined : codeOf(cls.parent, seen); + }); + if (new Set(each).size > 1) throw new CodeReachError(`class ${name} is declared ${all.length} times with different codes (${all.map((cls) => shown(cls.file)).join(', ')})`); + resolved.set(name, each[0]); + return each[0]; + }; + const descendsFrom = (name, ancestor) => { + for (let current = name, steps = 0; current !== undefined && steps < 20; steps += 1) { + if (current === ancestor) return true; + current = byName.get(current)?.[0]?.parent; + } + return false; + }; + return { codeOf: (name) => codeOf(name), isClass: (name) => byName.has(name) }; +} + +let table; +const classes = () => (table ??= classTable(sourceFiles())); + +/** The codes a module's own code can throw: its coded constructions, and its DYNAMIC_MODULES entry. */ +export function moduleCodes(file) { + const source = readFileSync(file, 'utf8'); + const code = codeOnly(source); + const codes = new Set(DYNAMIC_MODULES[shown(file)]?.codes ?? []); + for (const match of code.matchAll(/\bnew\s+(\w+)\s*\(/g)) { + const name = match[1]; + if (!classes().isClass(name)) continue; + const at = match.index + match[0].length; + const literal = /^\s*['"]/.exec(code.slice(at)); + if (name === CODE_FROM_FIRST_ARGUMENT && literal !== null) { + codes.add(literalAt(source, at + literal[0].length - 1)); + continue; + } + const classCode = name === CODE_FROM_FIRST_ARGUMENT ? 'dynamic' : classes().codeOf(name); + if (classCode === undefined) continue; + if (classCode !== 'dynamic') { + codes.add(classCode); + continue; + } + const entry = DYNAMIC_CLASSES[name]; + if (entry === undefined) throw new CodeReachError(`${shown(file)} constructs ${name}, whose code is not a literal, and DYNAMIC_CLASSES has no entry for it`); + for (const each of entry.codes) codes.add(each); + } + return codes; +} + +/** The source file an import names, with its .ts or index.ts filled in; undefined for an outside package or a file that isn't there. */ +function sourceOf(file, specifier) { + const target = importTarget(file, specifier); + if (target === undefined) return undefined; + for (const candidate of [target, `${target}.ts`, join(target, 'index.ts')]) { + if (existsSync(candidate) && statSync(candidate).isFile() && candidate.endsWith('.ts')) return candidate; + } + return undefined; +} + +/** The modules a module reaches directly: its imports that run, and the engine its calls reach. */ +function nextModules(file) { + const cut = new Set(CUT_IMPORTS.filter(([from]) => fromRoot(from) === file).map(([, to]) => fromRoot(to))); + // A definition is data: its load() and its tools' checks run only when the shell or the MCP server calls them. + const isDefinition = file.endsWith('.definition.ts'); + const next = importsOf(file).filter((each) => !each.typeOnly && !(isDefinition && each.dynamic)).map((each) => sourceOf(file, each.specifier)).filter((target) => target !== undefined && !cut.has(target)); + const code = codeOnly(readFileSync(file, 'utf8')); + for (const { site, reaches } of ENGINE_SITES) if (site.test(code)) next.push(...reaches.map(fromRoot)); + return next; +} + +/** + * The codes the modules `entries` (paths from the repository's root, or + * absolute) reach: each code, with the chain of modules from an entry to the + * first one found throwing it. + */ +export function codeReach(entries) { + const reached = new Map(); + const via = new Map(); + const pending = entries.map((entry) => resolve(ROOT, entry)); + for (const file of pending) via.set(file, undefined); + const chain = (file) => (file === undefined ? [] : [...chain(via.get(file)), shown(file)]); + while (pending.length > 0) { + const file = pending.shift(); + for (const code of moduleCodes(file)) if (!reached.has(code)) reached.set(code, chain(file)); + for (const next of nextModules(file)) { + if (via.has(next)) continue; + via.set(next, file); + pending.push(next); + } + } + return reached; +} + +/** + * Each command definition's entry modules: its handler, and the shell's payer + * and protectors when its `shell` asks for them. The definitions are the + * source files' (`*.definition.ts`), or those of `files`. + */ +export function commandEntries(files = sourceFiles().filter((file) => file.endsWith('.definition.ts'))) { + return files.map((file) => { + const source = readFileSync(file, 'utf8'); + const name = /\bname:\s*'([^']+)'/.exec(source)?.[1]; + const load = /\bload:\s*\(\)\s*=>\s*import\('([^']+)'\)/.exec(source)?.[1]; + if (name === undefined || load === undefined) throw new CodeReachError(`${shown(file)}: no command name or load() target found`); + const shell = /\bshell:\s*\{([^}]*)\}/.exec(source)?.[1] ?? ''; + const handler = sourceOf(file, load); + if (handler === undefined) throw new CodeReachError(`${shown(file)}: its load() target ${load} is not a source file`); + const provisions = Object.keys(SHELL_PROVISIONS).filter((key) => new RegExp(`\\b${key}:\\s*true`).test(shell)); + return { name, definition: shown(file), handler: shown(handler), provisions, entries: [shown(handler), ...provisions.map((key) => SHELL_PROVISIONS[key])] }; + }); +} + +/** + * Where a command's declared codes and its reachable ones part: a reachable + * code neither declared nor one every command can end with, and a declared + * code it can't reach. + */ +export function declaredCodeProblems(name, declared, reached, everyCommand) { + const problems = []; + for (const [code, chain] of reached) { + if (!declared.includes(code) && !everyCommand.includes(code)) problems.push(`${name}: reaches ${code} (${chain.join(' → ')}), which it doesn't declare`); + } + for (const code of declared) { + if (!reached.has(code)) problems.push(`${name}: declares ${code}, which none of its modules can throw`); + } + return problems; +} + +// Run as a script: each command's reachable codes. +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + for (const command of commandEntries().sort((a, b) => a.name.localeCompare(b.name))) { + const reached = codeReach(command.entries); + process.stdout.write(`${command.name}: ${[...reached.keys()].sort().join(' ')}\n`); + if (process.argv.includes('--why')) for (const [code, chain] of [...reached].sort()) process.stdout.write(` ${code}: ${chain.join(' → ')}\n`); + } +} diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index af68f29f..42dd58f7 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -133,6 +133,7 @@ describe('createPackageRegistry', () => { flags: [], needsWalletSdk: false, shell: {}, + errors: { codes: [] }, load: async () => ({ default: async () => {} }), mcp: { tools: tools.map((tool, i) => ({ name: tool, description: tool, params: [], argv: { flags: [] }, order: name.length * 100 + i })) }, }); diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index b003a9ba..95ea5927 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -33,6 +33,7 @@ import cacheCommand from '../commands/cache.ts'; import testCommand from '../commands/test.ts'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { declaredOutcome } from './helpers/expect-declared.ts'; import { testHost } from './helpers/test-host.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; @@ -97,7 +98,7 @@ describe('quick commands: a cancelled call never starts', () => { it.each(quick)('%s: CANCELLED, with no result and nothing written', async (...argv) => { const definition = installedCommands.find(argv[0]!)!; const { default: handler } = await definition.load(); - await expect(cliCall(handler as CommandHandler, parseArgs([...argv]), { signal: cancelled() })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome(argv[0]!, cliCall(handler as CommandHandler, parseArgs([...argv]), { signal: cancelled() }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(io.stdout()).toBe(''); // Nothing under the state root: no config, no wallet, nothing cleared or created. expect(fs.existsSync(stateRootIn(home))).toBe(false); @@ -126,7 +127,7 @@ describe('balance passes the signal into its reads', () => { const call = new AbortController(); void indexer.sentAtLeast(1).then(() => call.abort()); - await expect(cliCall(balanceCommand, parseArgs(['balance', address, '--json', ...endpoints()]), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('balance', cliCall(balanceCommand, parseArgs(['balance', address, '--json', ...endpoints()]), { signal: call.signal }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(io.stdout()).toBe(''); expect(indexer.subscriptions).toHaveLength(1); @@ -138,7 +139,7 @@ describe('balance passes the signal into its reads', () => { const call = new AbortController(); void indexer.sentAtLeast(1).then(() => call.abort()); - await expect(cliCall(balanceCommand, parseArgs(['balance', '--seed', 'bb'.repeat(32), '--network', 'undeployed', '--json', ...endpoints()]), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('balance', cliCall(balanceCommand, parseArgs(['balance', '--seed', 'bb'.repeat(32), '--network', 'undeployed', '--json', ...endpoints()]), { signal: call.signal }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(io.stdout()).toBe(''); await expect.poll(() => indexer.subscriptions[0]?.closedEarly).toBe(true); @@ -168,7 +169,7 @@ describe('inspect-cost passes the signal into its reads', () => { let cancelledAt = 0; server.once('request', () => { cancelledAt = Date.now(); call.abort(); }); - await expect(cliCall(inspectCostCommand, parseArgs(['inspect-cost', '--network', 'undeployed', '--indexer-ws', `ws://127.0.0.1:${port}/api/v4/graphql/ws`, '--json']), { signal: call.signal })) + await expect(declaredOutcome('inspect-cost', cliCall(inspectCostCommand, parseArgs(['inspect-cost', '--network', 'undeployed', '--indexer-ws', `ws://127.0.0.1:${port}/api/v4/graphql/ws`, '--json']), { signal: call.signal }))) .rejects.toMatchObject({ code: 'CANCELLED' }); // Before the signal reached it, it waited out the probe's own 5s time limit, then went on to read the parameters. @@ -202,7 +203,7 @@ describe('status passes the signal into its probes', () => { // Cancelled once all four requests are out. const fetches = hangingFetch((started) => { if (started === 4) call.abort(); }); - await expect(cliCall(statusCommand, parseArgs(['status', '--network', 'preprod', '--json']), { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('status', cliCall(statusCommand, parseArgs(['status', '--network', 'preprod', '--json']), { signal: call.signal }))).rejects.toMatchObject({ code: 'CANCELLED' }); // The dashboard's two, and the network's faucet and explorer (its indexer and node need a Blockfrost project id, which the test gives none). expect(fetches.signals).toHaveLength(4); @@ -222,7 +223,7 @@ describe('status passes the signal into its probes', () => { // Cancelled once the first view is drawn, its last line the dashboard's link: the watch has begun. const drawn = setInterval(() => { if (io.stderr().includes('Dashboard:')) { clearInterval(drawn); call.abort(); } }, 10); - await expect(cliCall(statusCommand, parseArgs(['status', '--network', 'preprod', '--watch']), { signal: call.signal })).resolves.toEqual({ exitCode: 0 }); + await expect(declaredOutcome('status', cliCall(statusCommand, parseArgs(['status', '--network', 'preprod', '--watch']), { signal: call.signal }))).resolves.toEqual({ exitCode: 0 }); clearInterval(drawn); }); }); @@ -233,7 +234,7 @@ describe('commands that write check the call before each whole write', () => { const prompter = cancellingPrompter(call); const target = path.join(home, 'legacy-wallet.json'); - await expect(cliCall(generateCommand, parseArgs(['generate', '--output', target, '--json']), { signal: call.signal, host: testHost({ prompter }) })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('generate', cliCall(generateCommand, parseArgs(['generate', '--output', target, '--json']), { signal: call.signal, host: testHost({ prompter }) }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(prompter.asked).toBeGreaterThan(0); expect(fs.existsSync(target)).toBe(false); @@ -245,7 +246,7 @@ describe('commands that write check the call before each whole write', () => { const call = new AbortController(); const prompter = cancellingPrompter(call); - await expect(cliCall(walletCommand, parseArgs(['wallet', 'generate', 'alice', '--json']), { signal: call.signal, host: testHost({ prompter }) })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('wallet', cliCall(walletCommand, parseArgs(['wallet', 'generate', 'alice', '--json']), { signal: call.signal, host: testHost({ prompter }) }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(prompter.asked).toBeGreaterThan(0); expect(fs.existsSync(path.join(stateRootIn(home), 'wallets', 'alice.json'))).toBe(false); @@ -268,7 +269,7 @@ describe('commands that write check the call before each whole write', () => { const files = [plainWallet('alice', 'a1'), plainWallet('bob', 'b2')]; const call = new AbortController(); - await expect(cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { signal: call.signal, host: testHost({ prompter: cancellingPrompter(call) }) })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('wallet', cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { signal: call.signal, host: testHost({ prompter: cancellingPrompter(call) }) }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(await Promise.all(files.map(isSealed))).toEqual([false, false]); expect(io.stdout()).toBe(''); @@ -301,10 +302,10 @@ describe('commands that write check the call before each whole write', () => { }, }); - await expect(cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { + await expect(declaredOutcome('wallet', cliCall(walletCommand, parseArgs(['wallet', 'protect', '--json']), { signal: call.signal, protectors: [protector('grant', () => call.abort()), protector('later')], - })).rejects.toMatchObject({ code: 'CANCELLED' }); + }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(ran).toEqual(['grant']); expect(io.stdout()).toBe(''); @@ -319,7 +320,7 @@ describe('commands that write check the call before each whole write', () => { fs.writeFileSync(cache, '{}'); const call = new AbortController(); - await expect(cliCall(cacheCommand, parseArgs(['cache', 'clear', '--wallet', 'alice', '--network', 'undeployed', '--json']), { signal: call.signal, host: testHost({ prompter: cancellingPrompter(call) }) })).rejects.toMatchObject({ code: 'CANCELLED' }); + await expect(declaredOutcome('cache', cliCall(cacheCommand, parseArgs(['cache', 'clear', '--wallet', 'alice', '--network', 'undeployed', '--json']), { signal: call.signal, host: testHost({ prompter: cancellingPrompter(call) }) }))).rejects.toMatchObject({ code: 'CANCELLED' }); expect(fs.existsSync(cache)).toBe(true); expect(io.stdout()).toBe(''); @@ -348,7 +349,7 @@ describe('test create, cancelled while Claude scaffolds', () => { process.env.PATH = `${bin}${path.delimiter}${originalPath}`; const call = new AbortController(); - const run = cliCall(testCommand, parseArgs(['test', 'create', '--path', dapp, '--goal', 'count up', '--json']), { signal: call.signal }); + const run = declaredOutcome('test', cliCall(testCommand, parseArgs(['test', 'create', '--path', dapp, '--goal', 'count up', '--json']), { signal: call.signal })); await expect.poll(() => fs.existsSync(started) && fs.readFileSync(started, 'utf8').trim() !== '', { timeout: 10_000 }).toBe(true); const pid = Number(fs.readFileSync(started, 'utf8').trim()); call.abort(); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 64418409..6f3d7198 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -80,7 +80,7 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => const payer = { name: 'test payer' } as unknown as Payer; const protector = { name: 'test protector' } as unknown as WalletProtector; const testCommand = (name: string, shell: CommandDefinition['shell'], outcome?: CommandOutcome): CommandDefinition => ({ - name, order: 1, flags: [], needsWalletSdk: false, shell, + name, order: 1, flags: [], needsWalletSdk: false, shell, errors: { codes: [] }, load: async () => { loaded.push(name); return { @@ -411,6 +411,7 @@ describe('createCommandRegistry', () => { help: { description: 'X', usage: 'midnight x', flags: ['note', { flag: 'a' }] }, needsWalletSdk: false, shell: {}, + errors: { codes: [] }, load: async () => ({ default: async () => {} }), }; diff --git a/src/__tests__/declared-codes.test.ts b/src/__tests__/declared-codes.test.ts new file mode 100644 index 00000000..24980cd8 --- /dev/null +++ b/src/__tests__/declared-codes.test.ts @@ -0,0 +1,149 @@ +// Each command declares the error codes its modules can throw, no more and no +// fewer: scripts/code-reach.mjs walks its handler and everything that runs +// from it (imports, the engine parts it uses, the shell's payer and +// protectors), and every code found must be declared or one every command can +// end with, and every declared code found. The scan's tables for codes that +// are not literals in the code are held to what that code does. + +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + CUT_IMPORTS, + DYNAMIC_CLASSES, + DYNAMIC_MODULES, + ENGINE_PARTS, + codeReach, + commandEntries, + declaredCodeProblems, +} from '../../scripts/code-reach.mjs'; +import { importTarget, importsOf } from '../../scripts/check-layering.mjs'; +import { declaredCodes, type CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { EVERY_COMMAND, READS_OFFERS } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { CancelledError, CommandFailedError, DustRequiredError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { refusalCodeOf, toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; +import { ContractScriptError, SCRIPT_ERROR_MARKER, scriptFailureOf } from '../lib/contract/runner.ts'; +import { PrepStepFailedError } from '../lib/test/prep-runner.ts'; +import { installedCommands } from '../lib/installed-commands.ts'; +import { WalletNotFoundError } from '../lib/wallet-config.ts'; +import { expectDeclared, expectDeclaredToolResult } from './helpers/expect-declared.ts'; +import { fixtureDefinition } from './fixtures/code-reach/fixture.definition.ts'; + +const ROOT = join(import.meta.dirname, '..', '..'); +const FIXTURE = join(import.meta.dirname, 'fixtures', 'code-reach', 'fixture.definition.ts'); + +/** The problems the check finds with `definition` declaring what it does, its entries read from its file. */ +function problemsOf(definition: CommandDefinition, file: string): string[] { + const [entry] = commandEntries([file]); + return declaredCodeProblems(definition.name, declaredCodes(definition), codeReach(entry!.entries), EVERY_COMMAND); +} + +describe('each installed command', () => { + const entries = commandEntries(); + + it('is found with its handler and what the shell gives it', () => { + expect(entries.map((entry) => entry.name).sort()).toStrictEqual(installedCommands.commands.map((command) => command.name).sort()); + for (const command of installedCommands.commands) { + const entry = entries.find((each) => each.name === command.name)!; + expect(entry.provisions, command.name).toStrictEqual([ + ...(command.shell.payer === true ? ['payer'] : []), + ...(command.shell.protectors === true ? ['protectors'] : []), + ]); + } + }); + + it('declares every code its modules can throw, and none they can\'t', () => { + const problems = installedCommands.commands.flatMap((command) => { + const entry = entries.find((each) => each.name === command.name)!; + return declaredCodeProblems(command.name, declaredCodes(command), codeReach(entry.entries), EVERY_COMMAND); + }); + expect(problems).toStrictEqual([]); + }); + + it('declares the exit codes its handler returns without throwing', () => { + for (const command of installedCommands.commands) { + const entry = entries.find((each) => each.name === command.name)!; + // Every non-zero `return { exitCode: n }` in its handler's module. + const returned = [...readFileSync(join(ROOT, entry.handler), 'utf8').matchAll(/return\s*\{\s*exitCode:\s*(\d+)\s*\}/g)].map((match) => Number(match[1])).filter((code) => code !== 0); + expect((command.errors.outcomes ?? []).map((outcome) => outcome.exitCode).sort(), command.name).toStrictEqual([...new Set(returned)].sort()); + } + }); +}); + +describe('a definition whose handler can throw a code it does not declare', () => { + it('is refused, the code named with the modules that reach it', () => { + expect(problemsOf(fixtureDefinition, FIXTURE)).toStrictEqual([ + 'code-reach-fixture: reaches NOT_AN_OFFER (src/__tests__/fixtures/code-reach/handler.ts → src/__tests__/fixtures/code-reach/refuses.ts), which it doesn\'t declare', + 'code-reach-fixture: reaches TERMS_MISMATCH (src/__tests__/fixtures/code-reach/handler.ts → src/__tests__/fixtures/code-reach/refuses.ts → packages/cli-core/src/lib/swap-offer.ts), which it doesn\'t declare', + ]); + }); + + it('holds once it declares them, and is refused for a code it declares and cannot reach', () => { + expect(problemsOf({ ...fixtureDefinition, errors: { codes: [READS_OFFERS] } }, FIXTURE)).toStrictEqual([]); + expect(problemsOf({ ...fixtureDefinition, errors: { codes: [READS_OFFERS, 'WALLET_NOT_FOUND'] } }, FIXTURE)).toStrictEqual([ + 'code-reach-fixture: declares WALLET_NOT_FOUND, which none of its modules can throw', + ]); + }); +}); + +describe("the scan's tables", () => { + it('name only codes the installed packages define', () => { + for (const site of [...Object.values(DYNAMIC_CLASSES), ...Object.values(DYNAMIC_MODULES)]) { + for (const code of site.codes) expect(installedCommands.code(code), code).toBeDefined(); + } + }); + + it("give toEngineError the codes it names an SDK or node failure by, as its engine's errors and a contract script's carry", () => { + const failures = ['ZK proof timeout', 'Custom error: 115', 'Custom error: 170', 'chain reset detected', 'Failed to prove transaction', 'sync timed out', 'No dust available', 'Insufficient funds', 'Transaction rejected', 'fetch failed']; + const named = new Set(failures.map((message) => (toEngineError(new Error(message)) as { code?: string }).code)); + const sdkErrors = DYNAMIC_MODULES['packages/cli-core/src/lib/sdk-errors.ts']!; + expect(new Set(sdkErrors.codes)).toStrictEqual(named); + expect(DYNAMIC_CLASSES.EngineError!.codes).toStrictEqual(sdkErrors.codes); + // A script reports the code its failure carried: mn serve's (withEngineCode marks it with the same codes), or NETWORK_ERROR. + expect(DYNAMIC_CLASSES.ContractScriptError!.codes).toStrictEqual(sdkErrors.codes); + expect(new ContractScriptError(scriptFailureOf(`${SCRIPT_ERROR_MARKER} {"message":"refused","code":"PROOF_FAILURE"}\n`, 1)).code).toBe('PROOF_FAILURE'); + }); + + it("give a node's refusal its three codes, a transport failure NETWORK_ERROR, and a prep step its cause's code", () => { + expect(new Set(['Custom error: 115', 'Custom error: 170', 'BalanceCheckOverspend'].map(refusalCodeOf))).toStrictEqual(new Set(DYNAMIC_CLASSES.TransactionRefusedError!.codes)); + expect(new TransactionRefusedError('anything').code).toBe('TX_REJECTED'); + expect((withTransportCode(new Error('fetch failed')) as { code?: string }).code).toBe('NETWORK_ERROR'); + expect(DYNAMIC_MODULES['packages/cli-core/src/lib/transport-failure.ts']!.codes).toStrictEqual(['NETWORK_ERROR']); + expect(new PrepStepFailedError('cache-clear', new DustRequiredError('short')).code).toBe('DUST_REQUIRED'); + expect(DYNAMIC_CLASSES.PrepStepFailedError!.codes).toStrictEqual([]); + }); + + it("split each engine's index into the parts it assembles, every module it imports in one of them", () => { + const parts = new Set(Object.values(ENGINE_PARTS).flat()); + for (const set of ['rc', 'beta']) { + const index = join(ROOT, 'packages', `engine-${set}`, 'src', 'index.ts'); + const own = importsOf(index).filter((each) => !each.typeOnly && each.specifier.startsWith('./')).map((each) => importTarget(index, each.specifier)!.slice(join(ROOT, 'packages', `engine-${set}`, 'src').length + 1)); + expect(new Set(own), set).toStrictEqual(parts); + expect(CUT_IMPORTS.filter(([from]) => from === `packages/engine-${set}/src/index.ts`).map(([, to]) => to.split('/').pop()).sort(), set).toStrictEqual([...parts].sort()); + } + }); +}); + +describe('the check of what a command a test runs ends with', () => { + it('passes a code the command declares or every command can end with, and fails any other', () => { + expect(() => expectDeclared('balance', new WalletNotFoundError('no alice'))).not.toThrow(); + expect(() => expectDeclared('help', new CancelledError())).not.toThrow(); + expect(() => expectDeclared('help', new Error('no code: UNKNOWN'))).not.toThrow(); + expect(() => expectDeclared('help', new WalletNotFoundError('no alice'))).toThrow('help ended with WALLET_NOT_FOUND'); + }); + + it("reads a node's refusal among an error's causes, as the shell reports it", () => { + const wrapped = new Error('deploy failed', { cause: new TransactionRefusedError('stale', { code: 'STALE_UTXO' }) }); + expect(() => expectDeclared('contract', wrapped)).not.toThrow(); + expect(() => expectDeclared('config', wrapped)).toThrow('config ended with STALE_UTXO'); + }); + + it("lets COMMAND_FAILED through only for a command that declares outcomes, and checks a tool's error by its command", () => { + expect(() => expectDeclared('test', new CommandFailedError('test', 1, {}))).not.toThrow(); + expect(() => expectDeclared('balance', new CommandFailedError('balance', 1, {}))).toThrow('balance ended with COMMAND_FAILED'); + expect(() => expectDeclaredToolResult('midnight_balance', { error: true, code: 'NETWORK_ERROR' })).not.toThrow(); + expect(() => expectDeclaredToolResult('midnight_config_get', { error: true, code: 'NETWORK_ERROR' })).toThrow('config ended with NETWORK_ERROR'); + expect(() => expectDeclaredToolResult('midnight_config_get', { network: 'undeployed' })).not.toThrow(); + }); +}); diff --git a/src/__tests__/error-code-registry.test.ts b/src/__tests__/error-code-registry.test.ts index 562ec8c0..7efead88 100644 --- a/src/__tests__/error-code-registry.test.ts +++ b/src/__tests__/error-code-registry.test.ts @@ -3,11 +3,20 @@ // is defined twice. import { describe, expect, it } from 'vitest'; -import { CodeDefinitionError, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { CommandDefinitionError, createCommandRegistry, createPackageRegistry, type CommandPackage } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { CodeDefinitionError, defineCodeSet, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { + CommandDefinitionError, + commandErrorCodes, + commandExitCodes, + createCommandRegistry, + createPackageRegistry, + declaredCodes, + type CommandDefinition, + type CommandPackage, +} from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { classifyError, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { coreCodes } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { chainCodes } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { coreCodes, ENGINE_SYNC, EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { chainCodes, READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; import { installedCommands } from '../lib/installed-commands.ts'; /** A package with no commands and no guidance: only codes. */ @@ -72,3 +81,59 @@ describe('the package registry\'s codes', () => { expect(createCommandRegistry([], []).code('INVALID_ARGS')).toBeUndefined(); }); }); + +/** A command that declares `codes` (and `outcomes`), in a package of its own. */ +const declaring = (codes: CommandDefinition['errors']['codes'], outcomes?: CommandDefinition['errors']['outcomes']): CommandDefinition => ({ + name: 'declaring', + order: 9_999, + flags: [], + needsWalletSdk: false, + shell: {}, + errors: { codes, ...(outcomes === undefined ? {} : { outcomes }) }, + load: async () => ({ default: async () => {} }), +}); +const withCommand = (command: CommandDefinition, codes: CommandPackage['codes'] = []): CommandPackage => ({ name: 'declaring', commands: [command], guidance: { pieces: [] }, codes }); + +describe('the codes a definition declares', () => { + it('spreads the sets it names, in the order declared', () => { + expect(declaredCodes(declaring([READS_CHAIN, 'CHAIN_CLOCK_BEHIND', ENGINE_SYNC]))).toStrictEqual([ + 'UNSUPPORTED_LEDGER', 'LOCAL_STACK_UNREACHABLE', 'CHAIN_CLOCK_BEHIND', 'NETWORK_ERROR', 'SYNC_TIMEOUT', 'STALE_CACHE', + ]); + }); + + it('refuses a code no installed package defines', () => { + expect(() => createPackageRegistry([codesOnly('core', coreCodes), withCommand(declaring(['PLUGIN_ORACLE_DOWN']))], [])) + .toThrow(new CommandDefinitionError('declaring declares PLUGIN_ORACLE_DOWN, which no installed package defines')); + // Installed with the plugin that defines it, the same declaration holds. + expect(createPackageRegistry([codesOnly('core', coreCodes), withCommand(declaring(['PLUGIN_ORACLE_DOWN']), PLUGIN_CODES)], []).code('PLUGIN_ORACLE_DOWN')).toBe(PLUGIN_CODES[0]); + }); + + it('refuses a code every command can end with, and a code declared twice', () => { + expect(() => createPackageRegistry([codesOnly('core', coreCodes), withCommand(declaring(['CANCELLED']))], [])) + .toThrow(new CommandDefinitionError('declaring declares CANCELLED, which every command can end with')); + expect(() => createPackageRegistry([codesOnly('core', coreCodes), withCommand(declaring([ENGINE_SYNC, 'NETWORK_ERROR']))], [])) + .toThrow(new CommandDefinitionError('declaring: error code "NETWORK_ERROR" is defined twice')); + }); + + it("shows a command's codes in the code tables' order, and its exit codes from them, every command's and its outcomes", () => { + const registry = createPackageRegistry([codesOnly('core', coreCodes), codesOnly('chain', chainCodes), withCommand(declaring([READS_CHAIN, ENGINE_SYNC], [{ exitCode: 9, when: 'it says so' }]))], []); + const command = registry.find('declaring')!; + expect(commandErrorCodes(registry, command).map((definition) => [definition.code, definition.exitCode])).toStrictEqual([ + ['NETWORK_ERROR', 4], ['SYNC_TIMEOUT', 4], ['STALE_CACHE', 6], ['UNSUPPORTED_LEDGER', 4], ['LOCAL_STACK_UNREACHABLE', 4], + ]); + // Success, its codes' (4, 6), every command's (INVALID_ARGS 2, CANCELLED 7, the rest 1), and its outcome's. + expect(commandExitCodes(registry, command)).toStrictEqual([0, 1, 2, 4, 6, 7, 9]); + }); + + it('refuses two sets of codes with one name', () => { + const other = defineCodeSet('chain', ['CHAIN_CLOCK_BEHIND']); + expect(() => createPackageRegistry([codesOnly('core', coreCodes), codesOnly('chain', chainCodes), withCommand(declaring([READS_CHAIN])), { + name: 'second', commands: [{ ...declaring([other]), name: 'second', order: 9_998 }], guidance: { pieces: [] }, + }], [])).toThrow(new CommandDefinitionError('two code sets are named "chain"')); + }); + + it('names five codes every command can end with, all defined by core', () => { + expect([...EVERY_COMMAND]).toStrictEqual(['INVALID_ARGS', 'CANCELLED', 'UNKNOWN', 'UNSUPPORTED_NODE', 'NO_STATE_ROOT']); + for (const code of EVERY_COMMAND) expect(coreCodes.some((definition) => definition.code === code), code).toBe(true); + }); +}); diff --git a/src/__tests__/fixtures/code-reach/fixture.definition.ts b/src/__tests__/fixtures/code-reach/fixture.definition.ts new file mode 100644 index 00000000..7f66356f --- /dev/null +++ b/src/__tests__/fixtures/code-reach/fixture.definition.ts @@ -0,0 +1,14 @@ +// A command for the code reach check: its handler imports a module that throws +// NotAnOfferError (NOT_AN_OFFER), and it declares no code. + +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; + +export const fixtureDefinition: CommandDefinition = { + name: 'code-reach-fixture', + order: 9_999, + flags: [], + needsWalletSdk: false, + shell: {}, + errors: { codes: [] }, + load: () => import('./handler.ts'), +}; diff --git a/src/__tests__/fixtures/code-reach/handler.ts b/src/__tests__/fixtures/code-reach/handler.ts new file mode 100644 index 00000000..c094be4c --- /dev/null +++ b/src/__tests__/fixtures/code-reach/handler.ts @@ -0,0 +1,7 @@ +// The fixture command's handler: it refuses every call, through refuses.ts. + +import { refuse } from './refuses.ts'; + +export default async function fixtureCommand(): Promise { + refuse('the fixture takes no offer'); +} diff --git a/src/__tests__/fixtures/code-reach/refuses.ts b/src/__tests__/fixtures/code-reach/refuses.ts new file mode 100644 index 00000000..94ec5018 --- /dev/null +++ b/src/__tests__/fixtures/code-reach/refuses.ts @@ -0,0 +1,7 @@ +// What the fixture command's handler imports: it throws a coded error. + +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; + +export function refuse(reason: string): never { + throw new NotAnOfferError(reason); +} diff --git a/src/__tests__/help-agent.test.ts b/src/__tests__/help-agent.test.ts index 1f81e246..deba5361 100644 --- a/src/__tests__/help-agent.test.ts +++ b/src/__tests__/help-agent.test.ts @@ -39,6 +39,18 @@ describe('help --agent', () => { expect(missing).toEqual([]); }); + it("names each command's own error codes under its usage", async () => { + await cliCall(helpCommand, parseArgs(['help', '--agent'])); + expect(io.stdout()).toContain('\n tx\n midnight tx status [options]\n Error codes: NETWORK_ERROR; sets: network\n JSON fields:\n'); + expect(io.stdout()).toContain('\n config\n midnight config [value] [--network ]\n Error codes: none; sets: network\n'); + }); + + it('lists each set of codes once, by name, after the code table', async () => { + await cliCall(helpCommand, parseArgs(['help', '--agent'])); + const table = io.stdout().split('ERROR CODES')[1]!.split('MCP SERVER')[0]!; + expect(table).toContain('\n Sets of codes (a command\'s "sets", a tool\'s "Errors" name them):\n network AMBIGUOUS_LOCAL_STACKS, BLOCKFROST_PROJECT_ID_REQUIRED, BLOCKFROST_PROJECT_ID_REJECTED, BLOCKFROST_LIMIT_REACHED, ENDPOINT_SHUT_DOWN\n wallet WALLET_NOT_FOUND, WRONG_PASSPHRASE, PASSPHRASE_REQUIRED\n'); + }); + it('documents all commands', async () => { const args = parseArgs(['help', '--agent']); await cliCall(helpCommand, args); diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index 5c894e9a..35fef913 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import helpCommand, { helpSpecs } from '../commands/help.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { installedCommands } from '../lib/installed-commands.ts'; +import { declaredCodes } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; @@ -196,6 +197,46 @@ describe('help — the lists come from the registry', () => { expect(manifest.commands.map((c) => c.name)).not.toContain('status'); }); + it('help ends with its errors: its own codes with exit code and meaning, its outcomes, then its sets of codes and every command\'s', async () => { + await cliCall(helpCommand, parseArgs(['help', 'tx'])); + const out = io.stdout().replace(/\x1b\[[0-9;]*m/g, ''); + expect(out.indexOf('Errors:')).toBeGreaterThan(out.indexOf('Examples:')); + expect(out.split('Errors:\n')[1]).toBe([ + ' NETWORK_ERROR 4 Indexer/node/proof-server connection refused or DNS failure.', + ' Also: the network codes, and INVALID_ARGS, CANCELLED, UNKNOWN, UNSUPPORTED_NODE, NO_STATE_ROOT (mn manual lists them all).', + '', + '', + ].join('\n')); + io.restore(); + io = captureOutput(); + await cliCall(helpCommand, parseArgs(['help', 'test'])); + expect(io.stdout()).toContain([ + ' NO_NODE_RUNTIME 1 Contract scripts run under Node.js, and none was found on PATH.', + ' (no error) 1 A test failed', + ' Also: the network, wallet, engine, sync, paying, offers and chain codes, and INVALID_ARGS, CANCELLED, UNKNOWN, UNSUPPORTED_NODE, NO_STATE_ROOT (mn manual lists them all).', + ].join('\n')); + }); + + it('help --json gives each command every code it declares with its exit code, the sets by name, and every exit code it can end with', async () => { + await cliCall(helpCommand, parseArgs(['help', '--json'])); + const manifest = JSON.parse(io.stdout()) as { commands: { name: string; errorCodes: { code: string; exitCode: number }[]; errorSets: string[]; exitCodes: number[] }[] }; + const tx = manifest.commands.find((c) => c.name === 'tx')!; + expect(tx.errorCodes).toStrictEqual([ + { code: 'NETWORK_ERROR', exitCode: 4 }, + { code: 'AMBIGUOUS_LOCAL_STACKS', exitCode: 4 }, + { code: 'BLOCKFROST_PROJECT_ID_REQUIRED', exitCode: 4 }, + { code: 'BLOCKFROST_PROJECT_ID_REJECTED', exitCode: 4 }, + { code: 'BLOCKFROST_LIMIT_REACHED', exitCode: 4 }, + { code: 'ENDPOINT_SHUT_DOWN', exitCode: 4 }, + ]); + expect(tx.errorSets).toStrictEqual(['network']); + // Success, its codes' 4, and every command's: INVALID_ARGS 2, CANCELLED 7, the rest 1. + expect(tx.exitCodes).toStrictEqual([0, 1, 2, 4, 7]); + for (const command of manifest.commands) { + expect(command.errorCodes.map((c) => c.code).sort(), command.name).toStrictEqual(declaredCodes(installedCommands.find(command.name)!).sort()); + } + }); + it('help finds a command by its definition, and names the rest when it can\'t', async () => { await cliCall(helpCommand, parseArgs(['help', 'grant'])); expect(io.stdout()).toContain('This wallet\'s account, and the grants that let an agent spend from it (experimental)'); diff --git a/src/__tests__/helpers/expect-declared.ts b/src/__tests__/helpers/expect-declared.ts new file mode 100644 index 00000000..539f37fb --- /dev/null +++ b/src/__tests__/helpers/expect-declared.ts @@ -0,0 +1,52 @@ +// What a command run by a test ended with, held to what its definition +// declares: the code of an error it ends with, as the shell and the MCP server +// classify it, is one of its own (errors.codes) or one every command can end +// with. src/__tests__/declared-codes.test.ts checks the declarations against +// the code; this checks them against what the commands the tests run do. + +import { expect } from 'vitest'; +import { declaredCodes } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { asReported } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { installedCommands } from '../../lib/installed-commands.ts'; + +/** + * The codes `command` can end with: its own, every command's, and + * COMMAND_FAILED when it declares outcomes (under MCP, a handler that returns + * a non-zero exit code fails with it). + */ +export function endableCodes(command: string): string[] { + const definition = installedCommands.find(command); + if (definition === undefined) throw new Error(`No installed command "${command}"`); + return [...declaredCodes(definition), ...EVERY_COMMAND, ...(definition.errors.outcomes === undefined ? [] : ['COMMAND_FAILED'])]; +} + +/** Fails unless `code`, which `command` ended with, is one it can end with. */ +export function expectDeclaredCode(command: string, code: unknown): void { + expect(endableCodes(command), `${command} ended with ${String(code)}, which its definition doesn't declare`).toContain(code); +} + +/** Fails unless the error `command` ended with carries a code it can end with, classified as the shell classifies it. */ +export function expectDeclared(command: string, err: unknown): void { + const reported = asReported(err instanceof Error ? err : new Error(String(err))); + expectDeclaredCode(command, classifyError(reported, installedCommands).errorCode); +} + +/** The call of `command`, its rejection checked by expectDeclared and passed on, its fulfilment as it is. */ +export async function declaredOutcome(command: string, call: Promise): Promise { + try { + return await call; + } catch (err) { + expectDeclared(command, err); + throw err; + } +} + +/** For an MCP tool's result: when it is an error (`error: true`), its code is one the tool's command can end with. */ +export function expectDeclaredToolResult(tool: string, result: Readonly>): void { + if (result.error !== true) return; + const registered = installedCommands.tools.find((each) => each.name === tool); + if (registered === undefined) throw new Error(`No installed tool "${tool}"`); + expectDeclaredCode(registered.command.name, result.code); +} diff --git a/src/__tests__/json-fields.test.ts b/src/__tests__/json-fields.test.ts index b1a10370..121a3bef 100644 --- a/src/__tests__/json-fields.test.ts +++ b/src/__tests__/json-fields.test.ts @@ -12,6 +12,7 @@ import { installedCommands } from '../lib/installed-commands.ts'; import { captureCommand } from '../lib/run-command.ts'; import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { ownCall } from './helpers/own-call.ts'; +import { declaredOutcome } from './helpers/expect-declared.ts'; const PASSPHRASE = 'correct horse battery staple'; let home: string; @@ -36,7 +37,7 @@ async function run(...argv: string[]): Promise> { const args = parseArgs([...argv, '--json']); args.flags._full = true; const { default: handler } = await installedCommands.find(args.command!)!.load(); - return captureCommand(handler as CommandHandler, args, ownCall()); + return declaredOutcome(args.command!, captureCommand(handler as CommandHandler, args, ownCall())); } // In order: a later run reads what an earlier one wrote. diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 8e82c587..e42494d7 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -38,6 +38,13 @@ describe('the layering', () => { expect(importRule('commands/dev.ts', 'commands/contract.ts')).toBe('command → contract command'); }); + it("lets a definition name the code sets of a package below it, and no package above's", () => { + expect(importRule('commands/balance.definition.ts', 'commands/core.codes.ts')).toBeUndefined(); + expect(importRule('commands/balance.definition.ts', 'commands/chain.codes.ts')).toBeUndefined(); + expect(importRule('lib/command-definition.ts', 'commands/core.codes.ts')).toBeUndefined(); + expect(importRule('commands/balance.definition.ts', 'commands/grant.codes.ts')).toBe('wallet → grant'); + }); + it('lets only the shell\'s list of engines reach an engine, and an engine reach only core and chain', () => { expect(importRule('lib/installed-engines.ts', 'engine/rc/index.ts')).toBeUndefined(); expect(importRule('lib/engine.ts', 'engine/rc/index.ts')).toBe('core → engine (reach it through lib/installed-engines.ts)'); diff --git a/src/__tests__/manual-command.test.ts b/src/__tests__/manual-command.test.ts index b116ce13..7633faf6 100644 --- a/src/__tests__/manual-command.test.ts +++ b/src/__tests__/manual-command.test.ts @@ -47,6 +47,20 @@ describe('mn manual', () => { } }); + it("ends each command's page with its errors, as help shows them", () => { + const m = stripAnsi(buildManual()); + const tx = m.split('▸ tx')[1]!.split('▸ ')[0]!; + expect(tx.indexOf('ERRORS')).toBeGreaterThan(tx.indexOf('EXAMPLES')); + expect(tx).toContain(' ERRORS\n NETWORK_ERROR 4 Indexer/node/proof-server connection refused or DNS failure.\n'); + expect(tx).toContain(' Also: the network codes, and INVALID_ARGS, CANCELLED, UNKNOWN, UNSUPPORTED_NODE, NO_STATE_ROOT (mn manual lists them all).\n'); + }); + + it('lists each set of codes the commands name, with its codes', () => { + const codes = stripAnsi(buildManual()).split('Sets of codes')[1]!.split('TROUBLESHOOTING')[0]!; + expect(codes).toContain('\n network AMBIGUOUS_LOCAL_STACKS, BLOCKFROST_PROJECT_ID_REQUIRED, BLOCKFROST_PROJECT_ID_REJECTED, BLOCKFROST_LIMIT_REACHED, ENDPOINT_SHUT_DOWN\n'); + expect(codes).toContain('\n chain UNSUPPORTED_LEDGER, LOCAL_STACK_UNREACHABLE\n'); + }); + it('lists the stable error code strings', () => { const m = stripAnsi(buildManual()); for (const code of [ diff --git a/src/__tests__/mcp-registry-tools.test.ts b/src/__tests__/mcp-registry-tools.test.ts index 28925386..442d253e 100644 --- a/src/__tests__/mcp-registry-tools.test.ts +++ b/src/__tests__/mcp-registry-tools.test.ts @@ -1,9 +1,11 @@ // The MCP server's tools from a registry (src/lib/mcp/registry-tools.ts), // with test commands whose handlers record the argv they get and write -// their JSON result through their call's context, as a command does. +// their JSON result through their call's context, as a command does; and the +// installed tools' descriptions. import { describe, expect, it } from 'vitest'; import { createCommandRegistry, type CommandDefinition, type ToolDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { installedCommands } from '../lib/installed-commands.ts'; import { CONFIRM_TOOL, confirmationFor, findTool, listedTools, runTool } from '../lib/mcp/registry-tools.ts'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { MINIMAL_FLAG, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; @@ -17,6 +19,7 @@ const command = (tools: ToolDefinition[]): CommandDefinition => ({ flags: [{ name: 'size', takesValue: true, agent: { type: 'string', description: 'How big' } }, { name: 'go', takesValue: false, subcommands: ['make'], agent: { notForAgents: 'a person\'s' } }], needsWalletSdk: false, shell: {}, + errors: { codes: [] }, load: async () => ({ default: async (args: ParsedArgs, ctx: CallContext) => { received.push(structuredClone(args)); @@ -77,3 +80,19 @@ describe('the MCP server\'s tools from a registry', () => { expect(await confirmationFor(findTool(registry, 'thing_plain')!, {}, ownCall())).toBe('Plain thing'); }); }); + +describe("the installed tools' descriptions", () => { + it("end with their command's own codes, then its sets of codes by name", () => { + const description = (name: string): string => listedTools(installedCommands).find((tool) => tool.name === name)!.description; + const own = (name: string): string => findTool(installedCommands, name)!.description; + expect(description('midnight_tx_status')).toBe(`${own('midnight_tx_status')} Errors: NETWORK_ERROR; and the network codes (see the skill).`); + expect(description('midnight_config_get')).toBe(`${own('midnight_config_get')} Errors: the network codes (see the skill).`); + expect(description('midnight_transfer')).toBe(`${own('midnight_transfer')} Errors: CHAIN_CLOCK_BEHIND; and the network, wallet, engine, sync, paying, offers and chain codes (see the skill).`); + // Every installed tool says what it can fail with in at most 20 words. + for (const tool of listedTools(installedCommands).slice(0, -1)) { + expect(tool.description.split(' Errors: ')[1]!.split(/\s+/).length + 1, tool.name).toBeLessThanOrEqual(20); + } + // The server's own confirm tool runs no command: its description stays as it is. + expect(listedTools(installedCommands).at(-1)).toStrictEqual(CONFIRM_TOOL); + }); +}); diff --git a/src/__tests__/mcp-server-concurrent-calls.test.ts b/src/__tests__/mcp-server-concurrent-calls.test.ts index 617364ce..85d412f7 100644 --- a/src/__tests__/mcp-server-concurrent-calls.test.ts +++ b/src/__tests__/mcp-server-concurrent-calls.test.ts @@ -24,6 +24,7 @@ import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.j import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { toNight } from '@kuiralabs/midnight-cli-core/ui/format'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; +import { expectDeclaredToolResult } from './helpers/expect-declared.ts'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); const TSX = path.join(REPO, 'node_modules', '.bin', 'tsx'); @@ -86,8 +87,12 @@ const balanceOf = (address: string, indexer: StandInIndexer) => ({ }, }); -const resultOf = (answer: unknown): Record => - JSON.parse(((answer as { content: Array<{ text: string }> }).content)[0]!.text) as Record; +/** A balance call's result, its error (if it is one) held to the codes balance declares. */ +const resultOf = (answer: unknown): Record => { + const result = JSON.parse(((answer as { content: Array<{ text: string }> }).content)[0]!.text) as Record; + expectDeclaredToolResult('midnight_balance', result); + return result; +}; /** The id of the tools/call request the client sent for `address`. */ function requestIdFor(address: string): unknown { diff --git a/src/__tests__/mcp-server-confirmation.test.ts b/src/__tests__/mcp-server-confirmation.test.ts index f054838b..6e5366da 100644 --- a/src/__tests__/mcp-server-confirmation.test.ts +++ b/src/__tests__/mcp-server-confirmation.test.ts @@ -11,6 +11,7 @@ import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { expectDeclaredToolResult } from './helpers/expect-declared.ts'; import { freshGrantee, grantRequestFor, grantRequestLink } from '@kuiralabs/midnight-account-chain/agent'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); @@ -58,9 +59,16 @@ afterAll(async () => { fs.rmSync(home, { recursive: true, force: true }); }); +/** The tool each pending token was issued for: confirming it runs that tool's command. */ +const pendingTools = new Map(); + const call = async (name: string, args: Record) => { const result = await client.callTool({ name, arguments: args }); - return JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record; + const body = JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record; + if (body.pending === true) pendingTools.set(body.token, name); + const ran = name === 'midnight_confirm_operation' ? pendingTools.get(args.token) : name; + if (ran !== undefined) expectDeclaredToolResult(ran, body); + return body; }; /** Every file under the home, with its contents: what a call that does nothing leaves as it was. */ diff --git a/src/__tests__/mcp-server-progress.test.ts b/src/__tests__/mcp-server-progress.test.ts index 1ce68bde..f2cbec88 100644 --- a/src/__tests__/mcp-server-progress.test.ts +++ b/src/__tests__/mcp-server-progress.test.ts @@ -15,6 +15,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.js'; import { startRefusingEndpoint } from './helpers/stand-in-indexer.ts'; +import { expectDeclaredToolResult } from './helpers/expect-declared.ts'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); const TSX = path.join(REPO, 'node_modules', '.bin', 'tsx'); @@ -88,7 +89,9 @@ describe('progress notifications', () => { expect(progress[0]).toMatchObject({ progress: 1, message: 'Checking balance on undeployed...' }); expect(progress.map((update) => update.progress)).toEqual(progress.map((_, index) => index + 1)); expect(Math.max(...progress.map((update) => update.at))).toBeLessThan(answerAt(call.id)); - expect(JSON.parse((result.content as Array<{ text: string }>)[0]!.text)).toMatchObject({ error: true, code: 'NETWORK_ERROR' }); + const body = JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record; + expect(body).toMatchObject({ error: true, code: 'NETWORK_ERROR' }); + expectDeclaredToolResult('midnight_balance', body); }, 60_000); it('sends none to a call that asked for none, which gets the same result', async () => { @@ -96,6 +99,8 @@ describe('progress notifications', () => { const result = await client.callTool(balanceOfAlice()); expect(lastCall().progressToken).toBeUndefined(); expect(fromServer.slice(before).filter((m) => 'method' in m && m.method === 'notifications/progress')).toEqual([]); - expect(JSON.parse((result.content as Array<{ text: string }>)[0]!.text)).toMatchObject({ error: true, code: 'NETWORK_ERROR' }); + const body = JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record; + expect(body).toMatchObject({ error: true, code: 'NETWORK_ERROR' }); + expectDeclaredToolResult('midnight_balance', body); }, 60_000); }); diff --git a/src/__tests__/mcp-server-unknown-parameter.test.ts b/src/__tests__/mcp-server-unknown-parameter.test.ts index 07addefe..d547ab45 100644 --- a/src/__tests__/mcp-server-unknown-parameter.test.ts +++ b/src/__tests__/mcp-server-unknown-parameter.test.ts @@ -12,6 +12,7 @@ import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { expectDeclaredToolResult } from './helpers/expect-declared.ts'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); const TSX = path.join(REPO, 'node_modules', '.bin', 'tsx'); @@ -33,7 +34,10 @@ afterAll(async () => { const call = async (name: string, args: Record) => { const result = await client.callTool({ name, arguments: args }); - return { isError: result.isError === true, body: JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record }; + const body = JSON.parse((result.content as Array<{ text: string }>)[0]!.text) as Record; + // The confirm tool is the server's own: called here with no token it issued, it runs no command. + if (name !== 'midnight_confirm_operation') expectDeclaredToolResult(name, body); + return { isError: result.isError === true, body }; }; // A port nothing listens on: an endpoint a call is given never reaches a chain. diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index 95124ab9..01810923 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -19,6 +19,7 @@ import { servePayerAt } from '../lib/serve-payer.ts'; import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; +import { declaredOutcome } from './helpers/expect-declared.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { testHost } from './helpers/test-host.ts'; @@ -114,7 +115,7 @@ describe('cancelled while the network has not answered', () => { let cancelledAt = 0; onFirstRequest = () => { cancelledAt = Date.now(); call.abort(); }; - const outcome = await cliCall(handler as CommandHandler, args, { signal: call.signal, payer: servePayerAt(0) }).then(() => 'finished', (err: unknown) => err); + const outcome = await declaredOutcome(args.command!, cliCall(handler as CommandHandler, args, { signal: call.signal, payer: servePayerAt(0) })).then(() => 'finished', (err: unknown) => err); expect(requests, `it reached the network: ${String(outcome instanceof Error ? outcome.message : outcome)}`).toBeGreaterThan(0); expect(outcome).toMatchObject({ code: 'CANCELLED' }); diff --git a/src/commands/address.definition.ts b/src/commands/address.definition.ts index 7945d327..68847765 100644 --- a/src/commands/address.definition.ts +++ b/src/commands/address.definition.ts @@ -1,6 +1,8 @@ // The `address` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const addressDefinition: CommandDefinition = { name: 'address', @@ -50,6 +52,7 @@ export const addressDefinition: CommandDefinition = { intro: { brief: 'Derive address from seed', order: 4 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, 'NETWORK_ERROR'] }, load: () => import('./address.ts'), mcp: { tools: [ diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index f925cc4a..b7f46455 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -1,6 +1,9 @@ // The `airdrop` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const airdropDefinition: CommandDefinition = { name: 'airdrop', @@ -71,6 +74,7 @@ export const airdropDefinition: CommandDefinition = { intro: { brief: 'Fund from genesis wallet', order: 7 }, needsWalletSdk: true, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND'] }, load: () => import('./airdrop.ts'), mcp: { tools: [ diff --git a/src/commands/balance.definition.ts b/src/commands/balance.definition.ts index b7ab9d12..9ab9512e 100644 --- a/src/commands/balance.definition.ts +++ b/src/commands/balance.definition.ts @@ -1,6 +1,9 @@ // The `balance` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const balanceDefinition: CommandDefinition = { name: 'balance', @@ -77,6 +80,7 @@ export const balanceDefinition: CommandDefinition = { intro: { brief: 'Check balance', order: 3 }, needsWalletSdk: true, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND'] }, load: () => import('./balance.ts'), mcp: { tools: [ diff --git a/src/commands/cache.definition.ts b/src/commands/cache.definition.ts index 946d9284..1f4acdba 100644 --- a/src/commands/cache.definition.ts +++ b/src/commands/cache.definition.ts @@ -1,6 +1,8 @@ // The `cache` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const cacheDefinition: CommandDefinition = { name: 'cache', @@ -43,6 +45,7 @@ export const cacheDefinition: CommandDefinition = { intro: { brief: 'Manage wallet cache', order: 14 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, 'NETWORK_ERROR'] }, load: () => import('./cache.ts'), mcp: { tools: [ diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index e703bf35..c6a5f01b 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -2,6 +2,9 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; /** The subcommands that reach a chain: inspect reads only the compiled contract (--path, --managed, --name). */ const ON_CHAIN: readonly string[] = ['deploy', 'call', 'state']; @@ -154,6 +157,7 @@ export const contractDefinition: CommandDefinition = { intro: { brief: 'Inspect, deploy, call contracts', order: 10 }, needsWalletSdk: true, shell: { payer: true }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_NODE_RUNTIME', 'NO_PAYER'] }, load: () => import('./contract.ts'), mcp: { tools: [ diff --git a/src/commands/dev.definition.ts b/src/commands/dev.definition.ts index 31a6c26c..820d9ee9 100644 --- a/src/commands/dev.definition.ts +++ b/src/commands/dev.definition.ts @@ -1,6 +1,9 @@ // The `dev` command, described once. import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const devDefinition: CommandDefinition = { name: 'dev', @@ -21,10 +24,13 @@ export const devDefinition: CommandDefinition = { ' Ctrl+C Quit cleanly', ], examples: ['midnight dev', 'midnight dev ./contract'], + // An interactive loop at a terminal: it writes no JSON result, --json or not. + jsonFields: {}, }, intro: { brief: 'Contract dev loop (watch + deploy)', order: 11 }, // It provisions wallets itself (airdrop, Dust registration), whose facades' WebSocket handles aren't reliably reclaimed. needsWalletSdk: true, shell: { payer: true }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_NODE_RUNTIME', 'NO_PAYER'] }, load: () => import('./dev.ts'), }; diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index 7043a318..933f25d2 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -1,6 +1,9 @@ // The `dust` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const dustDefinition: CommandDefinition = { name: 'dust', @@ -98,6 +101,7 @@ export const dustDefinition: CommandDefinition = { intro: { brief: 'Manage dust (fee tokens)', order: 9 }, needsWalletSdk: true, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND'] }, load: () => import('./dust.ts'), mcp: { tools: [ diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index 8fcad9c1..25a9f054 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -2,6 +2,8 @@ import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const generateDefinition: CommandDefinition = { name: 'generate', @@ -58,6 +60,7 @@ export const generateDefinition: CommandDefinition = { }, needsWalletSdk: false, shell: { notice: '\n Note: "midnight generate" is deprecated.\n Use "midnight wallet generate " instead.\n\n' }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, 'NETWORK_ERROR'] }, load: () => import('./generate.ts'), // The MCP server can load generate's handler, but its tool was removed (agents use midnight_wallet_generate). mcp: { tools: [] }, diff --git a/src/commands/genesis-address.definition.ts b/src/commands/genesis-address.definition.ts index d1f44502..17a8e788 100644 --- a/src/commands/genesis-address.definition.ts +++ b/src/commands/genesis-address.definition.ts @@ -1,6 +1,7 @@ // The `genesis-address` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; export const genesisAddressDefinition: CommandDefinition = { name: 'genesis-address', @@ -26,6 +27,7 @@ export const genesisAddressDefinition: CommandDefinition = { intro: { brief: 'Show genesis address', order: 5 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, LOADS_ENGINE, 'NETWORK_ERROR'] }, load: () => import('./genesis-address.ts'), mcp: { tools: [ diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index b5909248..75cfc7e6 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -1,6 +1,9 @@ // The `grant` command, described once. import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; /** A grant request can run: its arguments, the network, the account and the wallet are all in order. */ async function checkGrant(params: Readonly>, call: ToolCheckCall) { @@ -167,6 +170,7 @@ export const grantDefinition: CommandDefinition = { intro: { brief: 'Grants that let agents spend', order: 12 }, needsWalletSdk: true, shell: { payer: true }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_ACCOUNT', 'NO_PAYER'] }, load: () => import('./grant.ts'), mcp: { tools: [ diff --git a/src/commands/help.definition.ts b/src/commands/help.definition.ts index 819a7a58..4e1e4f2a 100644 --- a/src/commands/help.definition.ts +++ b/src/commands/help.definition.ts @@ -1,6 +1,7 @@ // The `help` command, described once. import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; export const helpDefinition: CommandDefinition = { name: 'help', @@ -23,5 +24,6 @@ export const helpDefinition: CommandDefinition = { intro: { brief: 'Show command usage', order: 18 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK] }, load: () => import('./help.ts'), }; diff --git a/src/commands/help.ts b/src/commands/help.ts index f969b3cd..2680f032 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -12,6 +12,7 @@ import { animateMaterialize } from '../ui/animate.ts'; import { WORDMARK_BIG } from '../ui/art.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { agentManual } from '../lib/agent-manual.ts'; +import { commandCodeLines } from '../lib/code-tables.ts'; import { commandHelpSpecs, introBriefs, type CommandHelpSpec } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { hasShownIntroThisSession, markIntroShown } from '../lib/intro-marker.ts'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; @@ -80,6 +81,10 @@ function printCommandHelp(output: CallOutput, spec: CommandSpec): void { } output.stdout('\n'); } + + output.stdout(gray('Errors:') + '\n'); + for (const line of commandCodeLines(spec, 2)) output.stdout(`${line}\n`); + output.stdout('\n'); } function outputJsonManifest(ctx: CallContext): void { @@ -98,6 +103,9 @@ function outputJsonManifest(ctx: CallContext): void { flags: spec.flags, examples: spec.examples, jsonFields: spec.jsonFields, + errorCodes: spec.errorCodes.map(({ code, exitCode }) => ({ code, exitCode })), + errorSets: spec.errorSets, + exitCodes: spec.exitCodes, })), }; diff --git a/src/commands/info.definition.ts b/src/commands/info.definition.ts index 062b2cee..18f97cae 100644 --- a/src/commands/info.definition.ts +++ b/src/commands/info.definition.ts @@ -2,6 +2,8 @@ import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const infoDefinition: CommandDefinition = { name: 'info', @@ -36,6 +38,7 @@ export const infoDefinition: CommandDefinition = { intro: { brief: 'Display wallet metadata', order: 2 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, 'NETWORK_ERROR'] }, load: () => import('./info.ts'), mcp: { tools: [ diff --git a/src/commands/inspect-cost.definition.ts b/src/commands/inspect-cost.definition.ts index ba246ff7..2bc91a76 100644 --- a/src/commands/inspect-cost.definition.ts +++ b/src/commands/inspect-cost.definition.ts @@ -1,6 +1,8 @@ // The `inspect-cost` command, described once. import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; export const inspectCostDefinition: CommandDefinition = { name: 'inspect-cost', @@ -38,6 +40,7 @@ export const inspectCostDefinition: CommandDefinition = { intro: { brief: 'Display block limits', order: 6 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, LOADS_ENGINE, READS_CHAIN, READS_OFFERS, 'NETWORK_ERROR'] }, load: () => import('./inspect-cost.ts'), mcp: { tools: [ diff --git a/src/commands/localnet.definition.ts b/src/commands/localnet.definition.ts index 61dcfef0..2a2233d6 100644 --- a/src/commands/localnet.definition.ts +++ b/src/commands/localnet.definition.ts @@ -1,6 +1,7 @@ // The `localnet` command, described once. import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; export const localnetDefinition: CommandDefinition = { name: 'localnet', @@ -46,6 +47,7 @@ export const localnetDefinition: CommandDefinition = { intro: { brief: 'Manage local network', order: 15 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK, LOADS_ENGINE, 'NETWORK_ERROR', 'SYNC_TIMEOUT', 'LOCALNET_UNAVAILABLE'] }, load: () => import('./localnet.ts'), mcp: { tools: [ diff --git a/src/commands/manual.definition.ts b/src/commands/manual.definition.ts index 5311dc48..ac6abbc3 100644 --- a/src/commands/manual.definition.ts +++ b/src/commands/manual.definition.ts @@ -1,6 +1,7 @@ // The `manual` command, described once. import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; export const manualDefinition: CommandDefinition = { name: 'manual', @@ -39,5 +40,6 @@ export const manualDefinition: CommandDefinition = { intro: { brief: 'Full reference manual', order: 19 }, needsWalletSdk: false, shell: {}, + errors: { codes: [RESOLVES_NETWORK] }, load: () => import('./manual.ts'), }; diff --git a/src/commands/manual.ts b/src/commands/manual.ts index e7f98c97..abb0e188 100644 --- a/src/commands/manual.ts +++ b/src/commands/manual.ts @@ -11,7 +11,7 @@ import { bold, dim, teal, yellow, white } from '@kuiralabs/midnight-cli-core/ui/ import { helpSpecs, type CommandSpec } from './help.ts'; import { PKG_NAME, PKG_VERSION, PKG_REPOSITORY_URL } from '../lib/pkg.ts'; import { installedCommands } from '../lib/installed-commands.ts'; -import { manualCodeLines } from '../lib/code-tables.ts'; +import { codeSetLines, commandCodeLines, manualCodeLines } from '../lib/code-tables.ts'; const SECTION_BAR = '═'.repeat(63); const RULE = '─'.repeat(64); @@ -56,6 +56,9 @@ function renderCommandSection(spec: CommandSpec): string { lines.push(` ${dim('$')} ${dim(example)}`); } } + lines.push(''); + lines.push(` ${bold('ERRORS')}`); + lines.push(...commandCodeLines(spec, 4, yellow)); return lines.join('\n'); } @@ -214,6 +217,9 @@ export function buildManual(): string { out.push(` ${bold('Stable error code strings')} (in JSON ${yellow('--json')} error output), with the exit code of each:`); // Every installed package's codes, from their definitions. out.push(...manualCodeLines(installedCommands, yellow)); + out.push(''); + out.push(` ${bold('Sets of codes')} (a command's ERRORS names those it can end with):`); + out.push(...codeSetLines(installedCommands, 4)); // ── Troubleshooting ─────────────────────────────────────── out.push(subhead('TROUBLESHOOTING')); diff --git a/src/commands/serve.definition.ts b/src/commands/serve.definition.ts index 422c621e..d2d66d84 100644 --- a/src/commands/serve.definition.ts +++ b/src/commands/serve.definition.ts @@ -1,6 +1,9 @@ // The `serve` command, described once. import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const serveDefinition: CommandDefinition = { name: 'serve', @@ -110,5 +113,6 @@ export const serveDefinition: CommandDefinition = { intro: { brief: 'DApp Connector server', order: 16 }, needsWalletSdk: true, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND'] }, load: () => import('./serve.ts'), }; diff --git a/src/commands/swap.definition.ts b/src/commands/swap.definition.ts index 37884be7..76237ce3 100644 --- a/src/commands/swap.definition.ts +++ b/src/commands/swap.definition.ts @@ -1,6 +1,9 @@ // The `swap` command, described once. import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; /** The terms a swap request states, as the maker gives and wants them. */ function describeTerms(params: Readonly>): string { @@ -141,6 +144,7 @@ export const swapDefinition: CommandDefinition = { intro: { brief: 'Private swaps through offer files', order: 12.5 }, needsWalletSdk: true, shell: { payer: true }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_PAYER', 'OFFER_EXPIRED'] }, load: () => import('./swap.ts'), mcp: { tools: [ diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index 82f84e1c..a527f02d 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -1,6 +1,10 @@ // The `test` command, described once. import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const testDefinition: CommandDefinition = { name: 'test', @@ -171,6 +175,11 @@ export const testDefinition: CommandDefinition = { intro: { brief: 'Run dApp E2E tests', order: 17 }, needsWalletSdk: true, shell: {}, + errors: { + codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_NODE_RUNTIME'], + // `test run` returns it when a test fails, with the results as its JSON (COMMAND_FAILED under MCP). + outcomes: [{ exitCode: EXIT_GENERAL_ERROR, when: 'A test failed' }], + }, load: () => import('./test.ts'), mcp: { tools: [ diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index 2177b3c7..b5faaa0f 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -1,6 +1,9 @@ // The `transfer` command, described once. import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const transferDefinition: CommandDefinition = { name: 'transfer', @@ -91,6 +94,7 @@ export const transferDefinition: CommandDefinition = { intro: { brief: 'Send NIGHT tokens', order: 8 }, needsWalletSdk: true, shell: {}, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND'] }, load: () => import('./transfer.ts'), mcp: { tools: [ diff --git a/src/commands/wallet.codes.ts b/src/commands/wallet.codes.ts index d73bdca6..be9ed1b8 100644 --- a/src/commands/wallet.codes.ts +++ b/src/commands/wallet.codes.ts @@ -1,8 +1,12 @@ -// The error codes the wallet package owns. +// The error codes the wallet package owns, and the set a command definition +// declares when it opens a saved wallet. -import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { defineCodeSet, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { EXIT_WALLET_NOT_FOUND } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; export const walletCodes = defineCodes([ { code: 'WALLET_NOT_FOUND', exitCode: EXIT_WALLET_NOT_FOUND, order: 20, summary: "Named wallet doesn't exist on disk.", recovery: '`midnight_wallet_list()` — user may have removed it.' }, ]); + +/** Opening a saved wallet: none by that name, or its seed sealed with another passphrase or none to be had. */ +export const OPENS_WALLET = defineCodeSet('wallet', ['WALLET_NOT_FOUND', 'WRONG_PASSPHRASE', 'PASSPHRASE_REQUIRED']); diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 1a92d382..28bcacd7 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -2,6 +2,8 @@ import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { OPENS_WALLET } from './wallet.codes.ts'; export const walletDefinition: CommandDefinition = { name: 'wallet', @@ -113,6 +115,7 @@ export const walletDefinition: CommandDefinition = { intro: { brief: 'Manage named wallets', order: 1 }, needsWalletSdk: false, shell: { protectors: true }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, 'NETWORK_ERROR'] }, load: () => import('./wallet.ts'), mcp: { tools: [ diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index bbab1c69..61731369 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -5,6 +5,7 @@ // registry's tools, each in the topic group its package's row names. import { PKG_VERSION } from './pkg.ts'; +import { codeSetLines } from './code-tables.ts'; import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type ToolsTableRow } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; import { commandHelpSpecs, type CommandRegistry, type RegisteredTool } from '@kuiralabs/midnight-cli-core/lib/command-definition'; @@ -121,7 +122,7 @@ examples, and JSON field schemas. }; } -/** Each command's usage and the fields of its --json output, from the registry. */ +/** Each command's usage, its own error codes and the sets of codes it declares, and the fields of its --json output, from the registry. */ function jsonSchemas(registry: CommandRegistry): GuidancePiece { const schemas = commandHelpSpecs(registry).filter((spec) => spec.jsonFields).map((spec) => { const fields = Object.entries(spec.jsonFields!) @@ -130,6 +131,7 @@ function jsonSchemas(registry: CommandRegistry): GuidancePiece { return ` ${spec.name} ${spec.usage} + Error codes: ${spec.ownCodes.map((definition) => definition.code).join(', ') || 'none'}; sets: ${spec.errorSets.join(', ') || 'none'} JSON fields: ${fields}`; }).join('\n'); @@ -320,6 +322,11 @@ resources/list. Ground responses in these instead of training-data guesses. }, ]; +/** After the code table, each set of codes the commands declare, by the name the commands and the tools' descriptions give it. */ +function codeSets(registry: CommandRegistry): GuidancePiece { + return { text: 'agent-manual', section: 'error-codes', order: 999, body: `\n Sets of codes (a command's "sets", a tool's "Errors" name them):\n${codeSetLines(registry, 4).map((line) => `${line}\n`).join('')}` }; +} + /** The tools behind the two-step confirmation, one per line, from the registry. */ function confirmedTools(registry: CommandRegistry): GuidancePiece { const names = registry.tools.filter((tool) => tool.confirmation !== undefined).map((tool) => ` ${tool.name}\n`); @@ -328,7 +335,7 @@ function confirmedTools(registry: CommandRegistry): GuidancePiece { /** The `help --agent` manual for the installed packages. */ export function agentManual(registry: CommandRegistry): string { - const pieces = [overview(), jsonSchemas(registry), mcpTools(registry), confirmedTools(registry), ...SHELL_PIECES, ...registry.packages.flatMap((pkg) => pkg.guidance.pieces)]; + const pieces = [overview(), jsonSchemas(registry), mcpTools(registry), codeSets(registry), confirmedTools(registry), ...SHELL_PIECES, ...registry.packages.flatMap((pkg) => pkg.guidance.pieces)]; const added = registry.packages.flatMap((pkg) => pkg.guidance.sections ?? []); return assembleGuidance('agent-manual', sectionsWithAdded('agent-manual', AGENT_MANUAL_SECTIONS, added), pieces); } diff --git a/src/lib/code-tables.ts b/src/lib/code-tables.ts index ba5156ae..a875c926 100644 --- a/src/lib/code-tables.ts +++ b/src/lib/code-tables.ts @@ -1,11 +1,14 @@ // The tables of error codes that are not agent guidance, from the installed // packages' code definitions: docs/JSON_CONTRACT.md's, which // scripts/write-readme-commands.ts writes between its markers (a test fails -// when the file differs), and the lines of `mn manual`'s EXIT CODES block. +// when the file differs), the lines of `mn manual`'s EXIT CODES block (its +// codes and the sets of them commands declare), and a command's Errors +// section in `mn help ` and the manual. // The manual's and the skills' rows come from each package's guidance // (codeGuidancePieces). -import type { CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { declaredCodeSets, type CommandHelpSpec, type CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands/core.codes'; import type { CodeDefinition } from '@kuiralabs/midnight-cli-core/lib/error-codes'; import { wrapWords } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; import { withGeneratedBlock } from './readme-commands.ts'; @@ -39,7 +42,7 @@ export function withJsonContractCodeTable(doc: string, table: string): string { // `mn manual`'s list: the code in a column of 31 (the longest code is 30), its // exit code, then the meaning from column 38 of an 80-column page. const MANUAL_CODE_INDENT = 4; -const MANUAL_CODE_COLUMN = 31; +const CODE_COLUMN = 31; const MANUAL_MEANING_COLUMN = 38; const MANUAL_WIDTH = 80; @@ -47,7 +50,35 @@ const MANUAL_WIDTH = 80; export function manualCodeLines(registry: Pick, styleCode: (code: string) => string = (code) => code): string[] { return installedCodes(registry).flatMap(({ code, exitCode, summary }) => { const [first = '', ...rest] = wrapWords(summary, MANUAL_WIDTH - MANUAL_MEANING_COLUMN); - const head = `${' '.repeat(MANUAL_CODE_INDENT)}${styleCode(code)}${' '.repeat(Math.max(1, MANUAL_CODE_COLUMN - code.length))}${exitCode} `; + const head = `${' '.repeat(MANUAL_CODE_INDENT)}${styleCode(code)}${' '.repeat(Math.max(1, CODE_COLUMN - code.length))}${exitCode} `; return [head + first, ...rest.map((line) => ' '.repeat(MANUAL_MEANING_COLUMN) + line)]; }); } + +/** Names in a sentence: "network", "network and wallet", "network, wallet and engine". */ +export function listedNames(names: readonly string[]): string { + return names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`; +} + +/** + * A command's Errors section, each line from `indent`: one per code of its own + * (the code in the manual's column, its exit code, its meaning), one per exit + * code it ends with without an error, then the sets of codes it declares and + * the codes every command can end with; `styleCode` colours a code. + */ +export function commandCodeLines(spec: Pick, indent: number, styleCode: (code: string) => string = (code) => code): string[] { + const pad = ' '.repeat(indent); + const sets = spec.errorSets.length === 0 ? '' : `the ${listedNames(spec.errorSets)} codes, and `; + return [ + ...spec.ownCodes.map(({ code, exitCode, summary }) => `${pad}${styleCode(code)}${' '.repeat(Math.max(1, CODE_COLUMN - code.length))}${exitCode} ${summary}`), + ...spec.outcomes.map(({ exitCode, when }) => `${pad}${'(no error)'.padEnd(CODE_COLUMN)}${exitCode} ${when}`), + `${pad}Also: ${sets}${EVERY_COMMAND.join(', ')} (mn manual lists them all).`, + ]; +} + +/** Each set of codes the commands declare, one line each from `indent`: its name, then its codes. */ +export function codeSetLines(registry: Pick, indent: number): string[] { + const sets = declaredCodeSets(registry); + const width = Math.max(...sets.map((set) => set.name.length)) + 2; + return sets.map((set) => `${' '.repeat(indent)}${set.name.padEnd(width)}${set.codes.join(', ')}`); +} diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index 501fe875..bf15f6d8 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -1,10 +1,12 @@ // The MCP server's tools, from the command registry: each command's -// definition gives its tools' names, descriptions, annotations, schemas, argv -// mapping and confirmation; the server runs the command's own handler. The +// definition gives its tools' names, descriptions (ending with the codes its +// command can end with), annotations, schemas, argv mapping and confirmation; the +// server runs the command's own handler. The // server's one tool of its own, midnight_confirm_operation, redeems the tokens // the confirmation flow gives. import { type CommandRun, captureCommand } from '../run-command.ts'; +import { listedNames } from '../code-tables.ts'; import { getEndpointOverridesForNetwork, loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { @@ -12,7 +14,9 @@ import { type RegisteredTool, type ToolAnnotations, type ToolInputSchema, + commandOwnCodes, confirmationText, + declaredSets, toolArgv, } from '@kuiralabs/midnight-cli-core/lib/command-definition'; @@ -32,9 +36,22 @@ export const CONFIRM_TOOL: ListedTool = { annotations: { destructiveHint: true, openWorldHint: true }, }; +/** + * A command's tool's description as tools/list sends it: its definition's, + * then the codes its command can end with: its own, and the sets it declares + * by name, which the full skill lists. + */ +export function toolDescription(registry: Pick, tool: RegisteredTool): string { + const own = commandOwnCodes(registry, tool.command).map((definition) => definition.code); + const sets = declaredSets(tool.command).map((set) => set.name); + if (own.length === 0 && sets.length === 0) return tool.description; + const named = sets.length === 0 ? '' : `the ${listedNames(sets)} codes (see the skill)`; + return `${tool.description} Errors: ${own.join(', ')}${own.length > 0 && named !== '' ? '; and ' : ''}${named}.`; +} + /** tools/list: every tool the installed commands define, in the registry's order, then the confirm tool. */ export function listedTools(registry: CommandRegistry): ListedTool[] { - return [...registry.tools, CONFIRM_TOOL].map((tool) => ({ + return [...registry.tools.map((tool) => ({ ...tool, description: toolDescription(registry, tool) })), CONFIRM_TOOL].map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, diff --git a/src/lib/mcp/skills.ts b/src/lib/mcp/skills.ts index e3b3e990..aaab7df0 100644 --- a/src/lib/mcp/skills.ts +++ b/src/lib/mcp/skills.ts @@ -7,7 +7,7 @@ // docs/SKILL-CORE.md and docs/SKILL.md, the copies the README links to. import { assembleGuidance, sectionsWithAdded, type GuidancePiece } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; -import type { CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { declaredCodeSets, type CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; /** skill/core's sections, in order. */ export const SKILL_CORE_SECTIONS = ['title', 'intent-routing', 'safety-rules', 'when-to-fetch'] as const; @@ -267,8 +267,8 @@ const confirmedTools = (registry: CommandRegistry): string => /** * What the skills say from the registry: the safety rule on the confirmed - * tools, in both, and in skill/full the commands no tool runs, which the user - * runs in a terminal. + * tools, in both, and in skill/full the sets of codes the tools' descriptions + * name and the commands no tool runs, which the user runs in a terminal. */ function registryPieces(registry: CommandRegistry): GuidancePiece[] { const confirmation = `- **Some tools use a two-step confirmation token**: ${confirmedTools(registry)}. The first call returns a pending token + description and does nothing else; show the description verbatim, and call \`midnight_confirm_operation({ token })\` only after the user explicitly says yes. (\`midnight_wallet_generate\` asks only with \`force: true\`, which replaces a wallet.)`; @@ -276,6 +276,12 @@ function registryPieces(registry: CommandRegistry): GuidancePiece[] { return [ { text: 'skill-core', section: 'safety-rules', order: 500, body: `${confirmation} Full flow in \`midnight-wallet://skill/full\`.\n\n` }, { text: 'skill-full', section: 'safety-rules', order: 500, body: `${confirmation}\n\n` }, + { + text: 'skill-full', + section: 'error-recovery', + order: 999, + body: `\nA tool's description ends with the codes it can fail with: its own, and sets of them by name. The sets:\n\n| Set | Codes |\n|---|---|\n${declaredCodeSets(registry).map((set) => `| ${set.name} | ${set.codes.map((code) => `\`${code}\``).join(', ')} |\n`).join('')}`, + }, { text: 'skill-full', section: 'what-you-can-do', From 7476232dd7dcd97bbe9885fb62258a3a7a415c84 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 13:35:25 -0800 Subject: [PATCH 67/88] Library functions for balance and Dust; shared shapes (3E, 1-3 of 8) A program calls what a command does with plain values: shared shapes in core (networkTargetOf from a network choice, ProgressEvent and the spinner adapter, WalletSource as a wallet name or path or a seed, seedOf) and chain's transactionStatus; then readAddressBalance and readWalletBalance, and readDustStatus, registerDust and exportDustSnapshot in src/lib/wallet/. The balance, dust and tx handlers only parse, call and print. Amounts are bigint. Small changes in edge cases: balance through MCP now sends progress notifications on the wallet path (its result is unchanged); an invalid --seed together with an invalid --network reports the seed first; dust register --no-cache is refused before the wallet unlocks (the shell already refuses that flag there). Suite 2798, beta 180; snapshot unchanged; fresh install; scratch chain swap 30/30 and tx 25/25 (dust register with its receipt); stagenet balance and Dust status read. --- packages/chain/api-report.md | 11 + packages/chain/src/commands/tx.ts | 15 +- packages/chain/src/lib/tx-status.ts | 35 +- packages/cli-core/api-report.md | 48 ++- packages/cli-core/src/lib/network-target.ts | 45 ++ packages/cli-core/src/lib/payer.ts | 26 +- packages/cli-core/src/lib/progress.ts | 31 ++ packages/cli-core/src/lib/sdk-warnings.ts | 8 + packages/cli-core/src/ui/spinner.ts | 41 ++ scripts/check-layering.mjs | 3 +- src/__tests__/command-flags.test.ts | 2 + src/__tests__/payer.test.ts | 37 ++ src/__tests__/seed-resolver.test.ts | 61 ++- src/__tests__/spinner-reporter.test.ts | 70 +++ src/__tests__/tx-status.test.ts | 35 +- src/__tests__/wallet-balance-lib.test.ts | 162 +++++++ src/__tests__/wallet-dust-lib.test.ts | 165 +++++++ src/commands/balance.ts | 288 ++++--------- src/commands/dust.ts | 453 +++++++------------- src/lib/seed-resolver.ts | 65 ++- src/lib/wallet/balance.ts | 192 +++++++++ src/lib/wallet/dust.ts | 205 +++++++++ src/lib/wallet/wallet-call.ts | 42 ++ 23 files changed, 1474 insertions(+), 566 deletions(-) create mode 100644 packages/cli-core/src/lib/network-target.ts create mode 100644 packages/cli-core/src/lib/progress.ts create mode 100644 src/__tests__/spinner-reporter.test.ts create mode 100644 src/__tests__/wallet-balance-lib.test.ts create mode 100644 src/__tests__/wallet-dust-lib.test.ts create mode 100644 src/lib/wallet/balance.ts create mode 100644 src/lib/wallet/dust.ts create mode 100644 src/lib/wallet/wallet-call.ts diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md index b541b60f..62ddf944 100644 --- a/packages/chain/api-report.md +++ b/packages/chain/api-report.md @@ -270,6 +270,8 @@ export declare function fetchPartialSuccessSegments(indexerHttpUrl: string, txHa ## `@kuiralabs/midnight-chain/lib/tx-status` ```ts +import { type ProgressListener } from "@kuiralabs/midnight-cli-core/lib/progress"; +export declare const TX_STATUS_WAIT_MS = 120000; export type TxReference = { hash: string; } | { @@ -300,4 +302,13 @@ export type TransactionStatus = FinalTransaction | UnknownTransaction; export declare function parseTxReference(text: string): TxReference; export declare function fetchTransactionStatus(indexerHttpUrl: string, ref: TxReference, signal?: AbortSignal): Promise; export declare function waitForTransactionStatus(indexerHttpUrl: string, ref: TxReference, timeoutMs: number, signal?: AbortSignal, intervalMs?: number): Promise; +export interface TransactionStatusOptions { + indexer: string; + ref: TxReference; + wait?: boolean; + timeoutMs?: number; + signal?: AbortSignal; + onProgress?: ProgressListener; +} +export declare function transactionStatus(options: TransactionStatusOptions): Promise; ``` diff --git a/packages/chain/src/commands/tx.ts b/packages/chain/src/commands/tx.ts index e70a1200..2f4e500b 100644 --- a/packages/chain/src/commands/tx.ts +++ b/packages/chain/src/commands/tx.ts @@ -7,14 +7,13 @@ import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { header, keyValue, formatDust } from '@kuiralabs/midnight-cli-core/ui/format'; import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { fetchTransactionStatus, parseTxReference, waitForTransactionStatus } from '../lib/tx-status.ts'; +import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { parseTxReference, transactionStatus, TX_STATUS_WAIT_MS } from '../lib/tx-status.ts'; import { transactionStatusJson } from '../lib/tx-receipt.ts'; -const DEFAULT_TIMEOUT_S = 120; - function timeoutMsOf(args: ParsedArgs): number { const raw = getFlag(args, 'timeout'); - if (raw === undefined) return DEFAULT_TIMEOUT_S * 1000; + if (raw === undefined) return TX_STATUS_WAIT_MS; if (!hasFlag(args, 'wait')) throw new UsageError('--timeout is how long --wait waits; give --wait with it'); if (!/^\d+$/.test(raw) || Number(raw) === 0) throw new UsageError(`--timeout must be a whole number of seconds, 1 or more (got "${raw}")`); return Number(raw) * 1000; @@ -29,12 +28,8 @@ export default async function txCommand(args: ParsedArgs, ctx: CallContext): Pro const jsonMode = hasFlag(args, 'json'); const { name: network, config } = resolveNetwork({ args, configDir: ctx.config.paths.stateRoot }, ctx.config.settings); - const wait = hasFlag(args, 'wait'); - const spinner = jsonMode ? ctx.progress.silent() : ctx.progress.start(wait ? 'Waiting for the indexer to list it...' : 'Asking the indexer...'); - const status = wait - ? await waitForTransactionStatus(config.indexer, ref, timeoutMs, ctx.signal) - : await fetchTransactionStatus(config.indexer, ref, ctx.signal); - spinner.stop(status.state === 'final' ? 'Final' : 'Not found'); + const progress = spinnerReporter(ctx.progress, jsonMode); + const status = await transactionStatus({ indexer: config.indexer, ref, wait: hasFlag(args, 'wait'), timeoutMs, signal: ctx.signal, onProgress: progress.report }); if (jsonMode) { ctx.output.result({ subcommand: 'status', network, transaction: given, ...transactionStatusJson(status) }); diff --git a/packages/chain/src/lib/tx-status.ts b/packages/chain/src/lib/tx-status.ts index 32785eae..9a6cf92e 100644 --- a/packages/chain/src/lib/tx-status.ts +++ b/packages/chain/src/lib/tx-status.ts @@ -7,12 +7,15 @@ // (33 bytes): what mn reports as a submitted transaction's `txHash` is the // wallet SDK's identifier. -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { progressSteps, type ProgressListener } from '@kuiralabs/midnight-cli-core/lib/progress'; import { queryIndexer } from './indexer-graphql.ts'; const QUERY_TIMEOUT_MS = 10_000; const POLL_INTERVAL_MS = 2_000; +/** How long a wait for the indexer to list a transaction lasts when not told. */ +export const TX_STATUS_WAIT_MS = 120_000; /** How a transaction was looked up: by its hash or by one of its identifiers. */ export type TxReference = { hash: string } | { identifier: string }; @@ -114,3 +117,33 @@ export async function waitForTransactionStatus( await sleep(Math.min(intervalMs, left), signal); } } + +export interface TransactionStatusOptions { + /** The indexer's GraphQL URL (HTTP), as a network's `indexer` endpoint. */ + indexer: string; + ref: TxReference; + /** Ask until the indexer has the transaction or `timeoutMs` passes; otherwise ask once. */ + wait?: boolean; + /** How long `wait` asks, in milliseconds (TX_STATUS_WAIT_MS when not given). */ + timeoutMs?: number; + signal?: AbortSignal; + onProgress?: ProgressListener; +} + +/** + * What became of a transaction: what the indexer knows of it now, or, with + * `wait`, once it lists it or the time passes. Throws CancelledError when + * `signal` cancels it (a call cancelled already never asks), and + * IndexerQueryError when the indexer can't answer. + */ +export async function transactionStatus(options: TransactionStatusOptions): Promise { + const { indexer, ref, wait = false, timeoutMs = TX_STATUS_WAIT_MS, signal } = options; + throwIfCancelled(signal); + const steps = progressSteps(options.onProgress); + steps.start(wait ? 'Waiting for the indexer to list it...' : 'Asking the indexer...'); + const status = wait + ? await waitForTransactionStatus(indexer, ref, timeoutMs, signal) + : await fetchTransactionStatus(indexer, ref, signal); + steps.done(status.state === 'final' ? 'Final' : 'Not found'); + return status; +} diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 6242d20d..b124243a 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -1596,6 +1596,21 @@ export declare function getNetworkId(networkIdStr: string): MidnightNetworkId; export declare function networkIdForName(name: NetworkName): MidnightNetworkId; ``` +## `@kuiralabs/midnight-cli-core/lib/network-target` + +```ts +import { type ParsedArgs } from "./argv.ts"; +import { type EndpointOverrides, type NetworkName } from "./network.ts"; +import type { Host } from "./host.ts"; +import type { PayingTarget } from "./payer.ts"; +export interface NetworkChoice extends EndpointOverrides { + network?: NetworkName; +} +export declare function networkChoiceFromArgs(args: ParsedArgs): NetworkChoice; +export declare function networkTargetOf(host: Host, choice?: NetworkChoice): PayingTarget; +export declare function networkTargetUnder(root: string, host: Host, choice: NetworkChoice): PayingTarget; +``` + ## `@kuiralabs/midnight-cli-core/lib/notices` ```ts @@ -1653,8 +1668,8 @@ export declare function assertSpendsNoOfferCoin(open: readonly OpenOffer[], spen ## `@kuiralabs/midnight-cli-core/lib/payer` ```ts -import { type ParsedArgs } from "./argv.ts"; -import { type EndpointOverrides, type NetworkConfig, type NetworkName } from "./network.ts"; +import type { ParsedArgs } from "./argv.ts"; +import type { EndpointOverrides, NetworkConfig, NetworkName } from "./network.ts"; import type { Spinner } from "../ui/spinner.ts"; import type { CallSdkWarnings } from "./sdk-warnings.ts"; import type { WalletSession } from "./wallet-session.ts"; @@ -1712,6 +1727,28 @@ export interface PhaseCallbacks { export declare function createPhaseTracker(callbacks?: PhaseCallbacks): PhaseTracker; ``` +## `@kuiralabs/midnight-cli-core/lib/progress` + +```ts +export type ProgressEvent = { + readonly kind: "start"; + readonly message: string; +} | { + readonly kind: "update"; + readonly message: string; +} | { + readonly kind: "done"; + readonly message: string; +}; +export type ProgressListener = (event: Event) => void; +export interface ProgressSteps { + start(message: string): void; + update(message: string): void; + done(message: string): void; +} +export declare function progressSteps(listener: ProgressListener | undefined): ProgressSteps; +``` + ## `@kuiralabs/midnight-cli-core/lib/prompter` ```ts @@ -1815,6 +1852,7 @@ export interface SdkWarningCalls { run(run: (warnings: CallSdkWarnings) => Promise): Promise; } export declare function sdkWarningCallsOn(router: SdkWarningRouter): SdkWarningCalls; +export declare function withCallSdkWarnings(calls: SdkWarningCalls, given: CallSdkWarnings | undefined, work: (warnings: CallSdkWarnings) => Promise): Promise; export declare function sdkTransientWarning(value: unknown): { tag: string; message: string; @@ -2083,6 +2121,7 @@ export declare function successMessage(msg: string, txHash?: string): string; ## `@kuiralabs/midnight-cli-core/ui/spinner` ```ts +import type { ProgressEvent } from "../lib/progress.ts"; export interface Spinner { update(message: string): void; stop(finalMessage?: string): void; @@ -2098,6 +2137,11 @@ export interface Progress { active(): Spinner | null; } export declare function createProgress(report?: ProgressReport): Progress; +export interface SpinnerReporter { + report(event: ProgressEvent): void; + fail(message?: string): void; +} +export declare function spinnerReporter(progress: Progress, silent: boolean): SpinnerReporter; export declare function start(message: string, report?: ProgressReport, onEnd?: (spinner: Spinner) => void): Spinner; export declare function trackElapsed(spinner: Spinner, baseMessage: string, promise: Promise): Promise; export declare function withSpinner(message: string, fn: () => Promise): Promise; diff --git a/packages/cli-core/src/lib/network-target.ts b/packages/cli-core/src/lib/network-target.ts new file mode 100644 index 00000000..29716ae2 --- /dev/null +++ b/packages/cli-core/src/lib/network-target.ts @@ -0,0 +1,45 @@ +// The network a call acts on, with its endpoints resolved: the one it names, +// else the one saved with `midnight config set network`, else undeployed (as +// every command), with the endpoints it gives over the saved ones and the +// defaults. Without endpoints, `undeployed` resolves to whatever local stack +// docker shows, which is ambiguous when more than one runs. + +import { getFlag, type ParsedArgs } from './argv.ts'; +import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkName } from './network.ts'; +import { resolveNetwork } from './resolve-network.ts'; +import type { Host } from './host.ts'; +import type { PayingTarget } from './payer.ts'; + +/** The network a call acts on, and the endpoints it uses instead of the saved or default ones. */ +export interface NetworkChoice extends EndpointOverrides { + /** The network's name; refused when it names none. Absent: the network set with `midnight config set network`, else undeployed. */ + network?: NetworkName; +} + +/** What a command's --network, --node, --indexer-ws and --proof-server choose. */ +export function networkChoiceFromArgs(args: ParsedArgs): NetworkChoice { + return { + // Resolving refuses a name that is no network's. + network: getFlag(args, 'network') as NetworkName | undefined, + node: getFlag(args, 'node'), + indexerWS: getFlag(args, 'indexer-ws'), + proofServer: getFlag(args, 'proof-server'), + }; +} + +/** The target `choice` names, from the config under the host's state root. */ +export function networkTargetOf(host: Host, choice: NetworkChoice = {}): PayingTarget { + return networkTargetUnder(host.paths().stateRoot, host, choice); +} + +/** The target `choice` names, from the config under the state root `root` (a command's call's); the call runs in `host`. */ +export function networkTargetUnder(root: string, host: Host, choice: NetworkChoice): PayingTarget { + const { network } = choice; + const endpoints: EndpointOverrides = { node: choice.node, indexerWS: choice.indexerWS, proofServer: choice.proofServer }; + const { name, config: networkConfig } = resolveNetwork({ + args: { command: 'network-target', subcommand: '', positionals: [], flags: { ...(network ? { network } : {}), ...endpointFlags(endpoints) } }, + configDir: root, + }, host.settings()); + applyEndpointOverrides(networkConfig, endpoints, name, root); + return { network: name, root, host, networkConfig, endpoints }; +} diff --git a/packages/cli-core/src/lib/payer.ts b/packages/cli-core/src/lib/payer.ts index 6e0bcefc..6a1f16b7 100644 --- a/packages/cli-core/src/lib/payer.ts +++ b/packages/cli-core/src/lib/payer.ts @@ -3,9 +3,9 @@ // the MCP server pass mn serve's), so a program that imports the command can // pay with a wallet of its own. -import { type ParsedArgs, getFlag } from './argv.ts'; -import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from './network.ts'; -import { resolveNetwork } from './resolve-network.ts'; +import type { ParsedArgs } from './argv.ts'; +import type { EndpointOverrides, NetworkConfig, NetworkName } from './network.ts'; +import { networkChoiceFromArgs, networkTargetUnder } from './network-target.ts'; import type { Spinner } from '../ui/spinner.ts'; import type { CallSdkWarnings } from './sdk-warnings.ts'; import type { WalletSession } from './wallet-session.ts'; @@ -24,26 +24,12 @@ export interface PayingTarget { } /** - * --network, else the network set with `midnight config set network`, else - * undeployed (as every other command), then explicit endpoint flags over the - * defaults. Without endpoint flags, `undeployed` resolves to whatever local - * stack docker shows, which is ambiguous when more than one runs. The saved - * network and endpoints are the config's under the state root `root`; the + * The target a command's --network and endpoint flags choose + * (network-target.ts), from the config under the state root `root`; the * command runs in `host`. */ export function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string, host: Host): PayingTarget { - const network = getFlag(args, 'network'); - const endpoints: EndpointOverrides = { - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - proofServer: getFlag(args, 'proof-server'), - }; - const { name, config: networkConfig } = resolveNetwork({ - args: { command, subcommand, positionals: [], flags: { ...(network ? { network } : {}), ...endpointFlags(endpoints) } }, - configDir: root, - }, host.settings()); - applyEndpointOverrides(networkConfig, endpoints, name, root); - return { network: name, root, host, networkConfig, endpoints }; + return networkTargetUnder(root, host, networkChoiceFromArgs(args)); } /** A wallet served over the DApp connector's WebSocket, for a script in another process to pay through. */ diff --git a/packages/cli-core/src/lib/progress.ts b/packages/cli-core/src/lib/progress.ts new file mode 100644 index 00000000..f6bfb1d8 --- /dev/null +++ b/packages/cli-core/src/lib/progress.ts @@ -0,0 +1,31 @@ +// What a library function says while it works, for whoever runs it: each step +// starts, may say more as it goes, and ends, in words for a person. The CLI +// shows them on its spinners (ui/spinner.ts spinnerReporter), the MCP server +// sends them as progress notifications, and a program does as it likes. A +// function may add events of its own that carry values (a balance read so +// far), typed beside it. + +/** One step of a library function's work, in words for a person. */ +export type ProgressEvent = + | { readonly kind: 'start'; readonly message: string } + | { readonly kind: 'update'; readonly message: string } + | { readonly kind: 'done'; readonly message: string }; + +/** Where a library function's progress events go. */ +export type ProgressListener = (event: Event) => void; + +/** How a library function says its steps: to `listener`, or nowhere when none is given. */ +export interface ProgressSteps { + start(message: string): void; + update(message: string): void; + done(message: string): void; +} + +/** The steps a function says, to `listener` when there is one. */ +export function progressSteps(listener: ProgressListener | undefined): ProgressSteps { + return { + start: (message) => listener?.({ kind: 'start', message }), + update: (message) => listener?.({ kind: 'update', message }), + done: (message) => listener?.({ kind: 'done', message }), + }; +} diff --git a/packages/cli-core/src/lib/sdk-warnings.ts b/packages/cli-core/src/lib/sdk-warnings.ts index 721030da..91c11827 100644 --- a/packages/cli-core/src/lib/sdk-warnings.ts +++ b/packages/cli-core/src/lib/sdk-warnings.ts @@ -91,6 +91,14 @@ export function sdkWarningCallsOn(router: SdkWarningRouter): SdkWarningCalls { return { run: (run) => run(router.openCall().warnings) }; } +/** + * Runs `work` with a call's SDK warnings: `given`, the caller's, or else those + * of a call of its own on `calls` (its host's). + */ +export function withCallSdkWarnings(calls: SdkWarningCalls, given: CallSdkWarnings | undefined, work: (warnings: CallSdkWarnings) => Promise): Promise { + return given === undefined ? calls.run(work) : work(given); +} + /** What a transient warning says when the SDK gives no message. */ const TRANSIENT_FALLBACK_MESSAGE = 'transient error'; /** The tag a bare-string Wallet.* trace is reported under. */ diff --git a/packages/cli-core/src/ui/spinner.ts b/packages/cli-core/src/ui/spinner.ts index 88c2ddda..48b46379 100644 --- a/packages/cli-core/src/ui/spinner.ts +++ b/packages/cli-core/src/ui/spinner.ts @@ -2,6 +2,7 @@ // Supports interleaved log lines without breaking the animation import { teal, isColorEnabled } from './colors.ts'; +import type { ProgressEvent } from '../lib/progress.ts'; const BRAILLE_FRAMES: readonly string[] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; const FRAME_INTERVAL_MS = 80; @@ -60,6 +61,46 @@ export function createProgress(report: ProgressReport = reportNowhere): Progress }; } +/** A library function's progress, shown on a call's spinners: one spinner per step. */ +export interface SpinnerReporter { + /** Shows one event: a step's start opens a spinner, its updates change it, its end stops it. */ + report(event: ProgressEvent): void; + /** Stops the running step's spinner with a failure mark, as a handler does when the function throws. */ + fail(message?: string): void; +} + +/** + * Shows a library function's steps on `progress`'s spinners. `silent` (a + * `--json` call) shows nothing on the terminal, while what each step says, + * its start included, still reaches the call's report (the MCP server's + * progress notifications). + */ +export function spinnerReporter(progress: Progress, silent: boolean): SpinnerReporter { + let current: Spinner | null = null; + return { + report(event) { + if (event.kind === 'start') { + current?.stop(); + if (silent) { + current = progress.silent(); + current.update(event.message); + } else { + current = progress.start(event.message); + } + } else if (event.kind === 'update') { + current?.update(event.message); + } else { + current?.stop(event.message); + current = null; + } + }, + fail(message) { + current?.fail(message); + current = null; + }, + }; +} + /** Strip ANSI escape codes for accurate visible-length measurement. */ function stripAnsi(str: string): string { return str.replace(/\x1b\[[0-9;]*m/g, ''); diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 563db573..a0fbf591 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -44,7 +44,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], @@ -54,6 +54,7 @@ const HOMES = [ ['wallet', /^commands\/(wallet|generate|address|genesis-address|info|balance|transfer|airdrop|dust|cache)(\.definition)?\.ts$/], ['wallet', /^lib\/(derivation|derive-address|wallet-config|seed-resolver|passphrase|facade|wallet-data-repository|transfer|transfer-request|sync-eta|wallet-can-pay|wallet-create|airdrop|wallet-protector|chain-caches|wallet-paths|fork-schedule)\.ts$/], ['wallet', /^lib\/(dust-[a-z-]+|shielded-[a-z-]+)\.ts$/], + ['wallet', /^lib\/wallet\//], ['wallet', /^ui\/receipt\.ts$/], ['contract', /^commands\/(contract|inspect-cost)(\.definition)?\.ts$/], diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index d88dbc4b..3c5446f3 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -102,6 +102,7 @@ describe('the accepted flags match the code', () => { 'resolveNetwork(': ['network', 'node', 'indexer-ws', 'proof-server'], 'resolveNetworkName(': ['network'], 'resolvePayingTarget(': ['network', 'node', 'indexer-ws', 'proof-server'], + 'networkChoiceFromArgs(': ['network', 'node', 'indexer-ws', 'proof-server'], // Reads the request's flags, and the network and endpoints. 'prepareGrant(': ['backup', 'cap', 'expires-in', 'max-coin', 'per-call', 'yes', 'network', 'node', 'indexer-ws', 'proof-server', 'wallet'], // The swap request's terms and expiry, and the network and endpoints. @@ -109,6 +110,7 @@ describe('the accepted flags match the code', () => { 'prepareTake(': ['give', 'give-token', 'want', 'want-token', 'network', 'node', 'indexer-ws', 'proof-server'], 'resolveSeedSource(': ['seed', 'wallet'], 'resolveSeed(': ['seed', 'wallet'], + 'walletSourceOf(': ['seed', 'wallet'], 'isVerbose(': ['verbose'], // The call's diagnostics are verbose when its --verbose is given: a command that writes them, or hands them to a library, reads it. 'ctx.diagnostics.': ['verbose'], diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index 22385461..c83efe4f 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -10,6 +10,8 @@ import * as path from 'node:path'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; import { NoPayerError, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { NoAccountError } from '../lib/grant/prepare.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; import { probeServeNetwork } from '../lib/serve-manager.ts'; @@ -59,6 +61,41 @@ describe('resolvePayingTarget', () => { }); }); +describe('networkTargetOf', () => { + const GIVEN = { node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', proofServer: 'http://localhost:26300' }; + const hostAt = (root: string) => createHost({ paths: { stateRoot: root, home } }); + + it('acts on undeployed when no network is given, with the endpoints given, under the host\'s state root', () => { + const target = networkTargetOf(hostAt(stateRootIn(home)), GIVEN); + expect(target.network).toBe('undeployed'); + expect(target.root).toBe(stateRootIn(home)); + expect(target.endpoints).toEqual(GIVEN); + expect(target.networkConfig.indexer).toBe('http://localhost:28088/api/v4/graphql'); + expect(target.networkConfig.proofServer).toBe('http://localhost:26300'); + }); + + it('acts on the network saved under each host\'s own state root, and on the one given over it', () => { + const rootA = path.join(home, 'a'); + const rootB = path.join(home, 'b'); + saveCliConfig({ network: 'preprod' }, rootA); + saveCliConfig({ network: 'preview' }, rootB); + expect(networkTargetOf(hostAt(rootA), GIVEN).network).toBe('preprod'); + expect(networkTargetOf(hostAt(rootB), GIVEN).network).toBe('preview'); + expect(networkTargetOf(hostAt(rootA), { ...GIVEN, network: 'undeployed' }).network).toBe('undeployed'); + }); + + it('refuses a name that is no network\'s', () => { + expect(() => networkTargetOf(hostAt(stateRootIn(home)), { ...GIVEN, network: 'mainnet' as NetworkName })).toThrow('Invalid network: "mainnet"'); + }); + + it('gives what resolvePayingTarget gives for the same flags', () => { + const args = parseArgs(['contract', 'deploy', '--network', 'undeployed', ...ENDPOINTS]); + const { host: _a, ...fromArgs } = resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host); + const { host: _b, ...fromChoice } = networkTargetOf(hostAt(stateRootIn(home)), { network: 'undeployed', ...GIVEN }); + expect(fromChoice).toEqual(fromArgs); + }); +}); + describe('a command called without a payer', () => { it.each(['deploy', 'call'])('contract %s refuses, naming itself', async (subcommand) => { const refused = cliCall(contractCommand, parseArgs(['contract', subcommand, ...ENDPOINTS])); diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 04578270..5c42c54b 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -7,7 +7,11 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { parseSeedHex, resolveSeedSource, resolveSeed } from '../lib/seed-resolver.ts'; +import { parseSeedHex, resolveSeedSource, resolveSeed, seedOf, walletSourceOf } from '../lib/seed-resolver.ts'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { mkdirSync } from 'node:fs'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; @@ -150,3 +154,58 @@ describe('resolveSeedSource', () => { expect((await resolveSeed(argsFor(['--seed', SEED_A]), stateRootIn(TMP), host)).toString('hex')).toBe(SEED_A); }); }); + +describe('seedOf', () => { + // A program's host: its own state root, its passphrase given in its settings, no environment read. + const programHost = (root: string) => createHost({ + paths: { stateRoot: root, home: TMP }, + settings: settingsFromEnvironment({ [PASSPHRASE_ENV]: PASSPHRASE }), + engineLoader: loadInstalledEngine, + }); + + it('gives a seed the program holds as it is, with no wallet file', async () => { + const r = await seedOf(programHost(stateRootIn(TMP)), { seed: Buffer.from(SEED_A, 'hex') }); + expect(r).toEqual({ seed: Buffer.from(SEED_A, 'hex'), walletPath: null, config: null }); + expect((await seedOf(programHost(stateRootIn(TMP)), { seed: new Uint8Array(64).fill(7) })).seed.length).toBe(64); + }); + + it.each([0, 16, 33, 65])('refuses a seed of %i bytes as a usage error', async (size) => { + await expect(seedOf(programHost(stateRootIn(TMP)), { seed: new Uint8Array(size) })).rejects.toMatchObject({ code: 'INVALID_ARGS', message: expect.stringContaining('32 or 64 bytes') }); + }); + + it('unlocks a sealed wallet by path through the host\'s passphrase', async () => { + const root = stateRootIn(TMP); + establishPassphrase(root, PASSPHRASE); + const p = writeSealedWallet(join(TMP, 'sealed.json'), { addresses: {} as WalletPublic['addresses'], createdAt: new Date().toISOString() }, { seed: SEED_B }, PASSPHRASE); + const r = await seedOf(programHost(root), { wallet: p }); + expect(r.seed.toString('hex')).toBe(SEED_B); + expect(r.walletPath).toBe(p); + expect(r.config?.isSealed).toBe(true); + }); + + it('finds a wallet by name, and the active one, each under its own host\'s state root', async () => { + const rootA = join(TMP, 'a'); + const rootB = join(TMP, 'b'); + for (const [root, seed] of [[rootA, SEED_A], [rootB, SEED_B]] as const) { + mkdirSync(join(root, 'wallets'), { recursive: true }); + writeFileSync(join(root, 'wallets', 'alice.json'), JSON.stringify({ seed, addresses: {}, createdAt: new Date().toISOString() })); + writeFileSync(join(root, 'config.json'), JSON.stringify({ wallet: 'alice' })); + } + expect((await seedOf(programHost(rootA), { wallet: 'alice' })).seed.toString('hex')).toBe(SEED_A); + expect((await seedOf(programHost(rootB), { wallet: 'alice' })).seed.toString('hex')).toBe(SEED_B); + expect((await seedOf(programHost(rootB), {})).seed.toString('hex')).toBe(SEED_B); + }); + + it('refuses a wallet that is not there, with WALLET_NOT_FOUND', async () => { + await expect(seedOf(programHost(stateRootIn(TMP)), { wallet: 'nobody' })).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + }); +}); + +describe('walletSourceOf', () => { + it('takes --seed over MN_SEED over --wallet, and the active wallet when none is given', () => { + expect(walletSourceOf(argsFor(['--seed', SEED_A, '--wallet', 'bob']), { seed: SEED_B })).toEqual({ seed: Buffer.from(SEED_A, 'hex') }); + expect(walletSourceOf(argsFor(['--wallet', 'bob']), { seed: SEED_B })).toEqual({ seed: Buffer.from(SEED_B, 'hex') }); + expect(walletSourceOf(argsFor(['--wallet', 'bob']), { seed: undefined })).toEqual({ wallet: 'bob' }); + expect(walletSourceOf(argsFor([]), { seed: undefined })).toEqual({}); + }); +}); diff --git a/src/__tests__/spinner-reporter.test.ts b/src/__tests__/spinner-reporter.test.ts new file mode 100644 index 00000000..aff5d47f --- /dev/null +++ b/src/__tests__/spinner-reporter.test.ts @@ -0,0 +1,70 @@ +// A library function's progress events, shown on a call's spinners: each step +// a spinner on the terminal, or, silent (--json), nothing there while what the +// steps say still reaches the call's report (the MCP server's progress). + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createProgress, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; + +let io: CapturedOutput; +const originalNoColor = process.env.NO_COLOR; + +beforeEach(() => { + process.env.NO_COLOR = '1'; + io = captureOutput(); +}); + +afterEach(() => { + io.restore(); + if (originalNoColor === undefined) delete process.env.NO_COLOR; + else process.env.NO_COLOR = originalNoColor; +}); + +describe('spinnerReporter', () => { + it('shows each step as a spinner that ends with the step\'s last words, and reports every message', () => { + const reported: string[] = []; + const progress = createProgress((message) => reported.push(message)); + const reporter = spinnerReporter(progress, false); + + reporter.report({ kind: 'start', message: 'Checking unshielded...' }); + expect(progress.active()).not.toBeNull(); + reporter.report({ kind: 'update', message: 'Checking unshielded... 50%' }); + reporter.report({ kind: 'done', message: 'Unshielded ready' }); + expect(progress.active()).toBeNull(); + + expect(io.stderr()).toContain('⠋ Checking unshielded...'); + expect(io.stderr()).toContain('✓ Unshielded ready\x1b[K\n'); + expect(reported).toEqual(['Checking unshielded...', 'Checking unshielded... 50%', 'Unshielded ready']); + }); + + it('silent, writes nothing on the terminal and reports every message, the start included', () => { + const reported: string[] = []; + const reporter = spinnerReporter(createProgress((message) => reported.push(message)), true); + + reporter.report({ kind: 'start', message: 'Asking the indexer...' }); + reporter.report({ kind: 'done', message: 'Final' }); + + expect(io.stderr()).toBe(''); + expect(reported).toEqual(['Asking the indexer...', 'Final']); + }); + + it('fails the running step with a red mark, once, and nothing when no step runs', () => { + const reporter = spinnerReporter(createProgress(), false); + reporter.fail('Failed'); + expect(io.stderr()).toBe(''); + + reporter.report({ kind: 'start', message: 'Syncing shielded...' }); + reporter.fail('Failed'); + reporter.fail('Failed'); + expect(io.stderr().match(/✗ Failed/g)).toHaveLength(1); + }); + + it('ignores an update or an end with no step running', () => { + const reported: string[] = []; + const reporter = spinnerReporter(createProgress((message) => reported.push(message)), false); + reporter.report({ kind: 'update', message: 'late' }); + reporter.report({ kind: 'done', message: 'late' }); + expect(io.stderr()).toBe(''); + expect(reported).toEqual([]); + }); +}); diff --git a/src/__tests__/tx-status.test.ts b/src/__tests__/tx-status.test.ts index 5885a976..d4529ee1 100644 --- a/src/__tests__/tx-status.test.ts +++ b/src/__tests__/tx-status.test.ts @@ -10,7 +10,8 @@ import { join } from 'node:path'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { CancelledError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { IndexerQueryError } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; -import { fetchTransactionStatus, parseTxReference, waitForTransactionStatus } from '@kuiralabs/midnight-chain/lib/tx-status'; +import { fetchTransactionStatus, parseTxReference, transactionStatus, waitForTransactionStatus } from '@kuiralabs/midnight-chain/lib/tx-status'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; import { receiptJson, receiptOf, transactionStatusJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; import txCommand from '@kuiralabs/midnight-chain/commands/tx'; import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; @@ -116,6 +117,38 @@ describe('waitForTransactionStatus', () => { }); }); +describe('transactionStatus', () => { + it('asks once, saying so, and gives what the indexer knows', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const said: ProgressEvent[] = []; + const status = await transactionStatus({ indexer: indexer.url, ref: { hash: HASH }, onProgress: (event) => said.push(event) }); + expect(status).toMatchObject({ state: 'final', result: 'SUCCESS', feeSpecks: 845170285714286n, block: { height: BLOCK.height } }); + expect(indexer.requests).toHaveLength(1); + expect(said).toEqual([{ kind: 'start', message: 'Asking the indexer...' }, { kind: 'done', message: 'Final' }]); + }); + + it('with wait, asks until the time passes, and says it was not found', async () => { + indexer = await startLocalIndexer(() => answer([])); + const said: ProgressEvent[] = []; + const status = await transactionStatus({ indexer: indexer.url, ref: { identifier: IDENTIFIER }, wait: true, timeoutMs: 100, onProgress: (event) => said.push(event) }); + expect(status).toEqual({ state: 'notFound' }); + expect(said).toEqual([{ kind: 'start', message: 'Waiting for the indexer to list it...' }, { kind: 'done', message: 'Not found' }]); + }); + + it('never asks when its call is cancelled already', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const said: ProgressEvent[] = []; + await expect(transactionStatus({ indexer: indexer.url, ref: { hash: HASH }, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toThrow(CancelledError); + expect(indexer.requests).toEqual([]); + expect(said).toEqual([]); + }); + + it('throws IndexerQueryError when the indexer refuses', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'invalid transaction hash' }] })); + await expect(transactionStatus({ indexer: indexer.url, ref: { hash: HASH } })).rejects.toBeInstanceOf(IndexerQueryError); + }); +}); + describe('receiptOf', () => { it('gives the transaction once listed, and its JSON with the fee in DUST exactly', async () => { indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); diff --git a/src/__tests__/wallet-balance-lib.test.ts b/src/__tests__/wallet-balance-lib.test.ts new file mode 100644 index 00000000..4996f859 --- /dev/null +++ b/src/__tests__/wallet-balance-lib.test.ts @@ -0,0 +1,162 @@ +// readAddressBalance and readWalletBalance, called as a program calls them: +// a host of its own (a temporary state root, its settings given, never the +// environment), plain values in, typed results out, no argv and no call +// context. The indexer is a stand-in run by the test (stand-in-indexer.ts), +// the node and proof server an endpoint that refuses every connection. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { deriveAllAddresses, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { establishPassphrase, PASSPHRASE_ENV } from '../lib/passphrase.ts'; +import { writeSealedWallet, type WalletPublic } from '../lib/wallet-config.ts'; +import { readAddressBalance, readWalletBalance, type UnshieldedRead } from '../lib/wallet/balance.ts'; +import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const SEED_A = 'a1'.repeat(32); +const SEED_B = 'b2'.repeat(32); + +let home: string; +let indexer: StandInIndexer; +let refusing: { port: number; close(): Promise }; + +beforeEach(async () => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-balance-lib-'))); + indexer = await startStandInIndexer([1_000_000n, 2_500_000n], 5); + refusing = await startRefusingEndpoint(); +}); + +afterEach(async () => { + await indexer.close(); + await refusing.close(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A program's host: its own state root under the test's folder, its passphrase in its settings, and a prompter that counts what it is asked. */ +function programHost(name: string): Host & { asked: () => number } { + let asked = 0; + const prompter: Prompter = { isInteractive: () => true, ask: async () => { asked += 1; return null; }, askSecret: async () => { asked += 1; return PASSPHRASE; } }; + const host = createHost({ + paths: { stateRoot: path.join(home, name, '.midnight'), home: path.join(home, name) }, + settings: settingsFromEnvironment({ [PASSPHRASE_ENV]: PASSPHRASE }), + prompter, + engineLoader: loadInstalledEngine, + }); + return Object.assign(host, { asked: () => asked }); +} + +/** The stand-ins as endpoints. */ +const endpoints = () => ({ indexerWS: indexer.url, node: `ws://127.0.0.1:${refusing.port}`, proofServer: `http://127.0.0.1:${refusing.port}` }); + +describe('readAddressBalance', () => { + it('reads an address on the network its prefix names: balances in the smallest unit as bigint, with each step said', async () => { + const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + const said: ProgressEvent[] = []; + const result = await readAddressBalance(programHost('a'), address, { ...endpoints(), forceFresh: true, onProgress: (event) => said.push(event) }); + + expect(result).toEqual({ address, network: 'undeployed', balances: new Map([[NATIVE_TOKEN_TYPE, 3_500_000n]]), utxoCount: 2, txCount: 2 }); + expect(said[0]).toEqual({ kind: 'start', message: 'Checking balance on undeployed...' }); + expect(said.filter((event) => event.kind === 'update').map((event) => event.message)).toContain('Syncing transactions... 100%'); + expect(said.at(-1)).toEqual({ kind: 'done', message: 'Synced 2 transactions' }); + expect(indexer.subscriptions.map((s) => s.address)).toEqual([address]); + }); + + it('refuses a network other than the one the address is for, as a usage error, before reading', async () => { + const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + await expect(readAddressBalance(programHost('a'), address, { ...endpoints(), network: 'preprod' })).rejects.toMatchObject({ code: 'INVALID_ARGS', message: expect.stringContaining('Address belongs to undeployed but --network is preprod') }); + expect(indexer.subscriptions).toEqual([]); + }); + + it('fails with NETWORK_ERROR when the indexer refuses the connection', async () => { + const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + await expect(readAddressBalance(programHost('a'), address, { ...endpoints(), indexerWS: `ws://127.0.0.1:${refusing.port}/api/v4/graphql/ws`, forceFresh: true })).rejects.toMatchObject({ code: 'NETWORK_ERROR' }); + }); + + it('cancelled already: CancelledError, and nothing asked of the indexer or said', async () => { + const said: ProgressEvent[] = []; + const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + await expect(readAddressBalance(programHost('a'), address, { ...endpoints(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(indexer.subscriptions).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('readWalletBalance', () => { + type Said = ProgressEvent | WalletOpened | UnshieldedRead; + + it('reads a seed the program holds: unshielded NIGHT as bigint, shielded not read where the network has no faucet', async () => { + const said: Said[] = []; + const seed = Buffer.from(SEED_A, 'hex'); + const address = deriveUnshieldedAddress(seed, 'preview'); + const result = await readWalletBalance(programHost('a'), { seed }, { ...endpoints(), network: 'preview', forceFresh: true, onProgress: (event) => said.push(event) }); + + expect(result).toEqual({ network: 'preview', address, unshielded: { night: 3_500_000n, utxoCount: 2 }, shielded: null }); + expect(said).toEqual([ + { kind: 'wallet-opened', network: 'preview', address }, + { kind: 'start', message: 'Checking unshielded...' }, + { kind: 'done', message: 'Unshielded ready' }, + { kind: 'unshielded-read', night: 3_500_000n, utxoCount: 2 }, + ]); + }); + + it('unlocks a sealed wallet by name through the host\'s passphrase, and says the shielded address its file saved', async () => { + const host = programHost('a'); + const root = host.paths().stateRoot; + establishPassphrase(root, PASSPHRASE); + const addresses = deriveAllAddresses(Buffer.from(SEED_B, 'hex')); + const shieldedAddresses = { preview: 'mn_shield-addr_preview1saved' } as WalletPublic['addresses']; + writeSealedWallet(path.join(root, 'wallets', 'alice.json'), { addresses, shieldedAddresses, createdAt: new Date().toISOString() }, { seed: SEED_B }, PASSPHRASE); + const said: Said[] = []; + + const result = await readWalletBalance(host, { wallet: 'alice' }, { ...endpoints(), network: 'preview', forceFresh: true, onProgress: (event) => said.push(event) }); + + expect(result.address).toBe(addresses.preview); + expect(result.shieldedAddress).toBe('mn_shield-addr_preview1saved'); + expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'preview', address: addresses.preview, shieldedAddress: 'mn_shield-addr_preview1saved' }); + expect(indexer.subscriptions.map((s) => s.address)).toEqual([addresses.preview]); + }); + + it('reads each host\'s own wallet on each host\'s saved network, two hosts in one process', async () => { + const hostA = programHost('a'); + const hostB = programHost('b'); + for (const [host, seed, network] of [[hostA, SEED_A, 'preview'], [hostB, SEED_B, 'preprod']] as const) { + const root = host.paths().stateRoot; + saveWalletConfig({ seed, addresses: deriveAllAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveCliConfig({ network, wallet: 'alice' }, root); + } + + const [a, b] = await Promise.all([ + readWalletBalance(hostA, {}, { ...endpoints(), forceFresh: true }), + readWalletBalance(hostB, {}, { ...endpoints(), forceFresh: true }), + ]); + + expect(a).toMatchObject({ network: 'preview', address: deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'preview'), unshielded: { night: 3_500_000n } }); + expect(b).toMatchObject({ network: 'preprod', address: deriveUnshieldedAddress(Buffer.from(SEED_B, 'hex'), 'preprod'), unshielded: { night: 3_500_000n } }); + }); + + it('refuses a wallet that is not there with WALLET_NOT_FOUND, and a seed of the wrong size with INVALID_ARGS, before reading', async () => { + await expect(readWalletBalance(programHost('a'), { wallet: 'nobody' }, { ...endpoints(), network: 'preview' })).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + await expect(readWalletBalance(programHost('a'), { seed: new Uint8Array(20) }, { ...endpoints(), network: 'preview' })).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + expect(indexer.subscriptions).toEqual([]); + }); + + it('cancelled already: CancelledError, and no wallet unlocked, nothing asked of the indexer or said', async () => { + const host = programHost('a'); + const said: Said[] = []; + await expect(readWalletBalance(host, { wallet: 'alice' }, { ...endpoints(), network: 'preview', signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(host.asked()).toBe(0); + expect(indexer.subscriptions).toEqual([]); + expect(said).toEqual([]); + }); +}); diff --git a/src/__tests__/wallet-dust-lib.test.ts b/src/__tests__/wallet-dust-lib.test.ts new file mode 100644 index 00000000..b6e48d72 --- /dev/null +++ b/src/__tests__/wallet-dust-lib.test.ts @@ -0,0 +1,165 @@ +// readDustStatus, registerDust and exportDustSnapshot, called as a program +// calls them: a host of its own (a temporary state root, its settings given, +// never the environment), plain values in, typed results out, no argv and no +// call context. The indexer is a stand-in run by the test (stand-in-indexer.ts) +// whose NIGHT coins are not registered for Dust; the node and proof server an +// endpoint that refuses every connection. Registering and a snapshot of a +// wallet's Dust need a chain: the scratch chain's live runs cover them. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { deriveAllAddresses, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; +import { exportDustSnapshot, readDustStatus, registerDust } from '../lib/wallet/dust.ts'; +import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const SEED_A = 'c3'.repeat(32); +const SEED_B = 'd4'.repeat(32); + +let home: string; +let indexer: StandInIndexer; +let refusing: { port: number; close(): Promise }; + +beforeEach(async () => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-dust-lib-'))); + indexer = await startStandInIndexer([1_000_000n, 2_000_000n], 5); + refusing = await startRefusingEndpoint(); +}); + +afterEach(async () => { + await indexer.close(); + await refusing.close(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A program's host: its own state root under the test's folder, its passphrase in its settings, and a prompter that counts what it is asked. */ +function programHost(name: string): Host & { asked: () => number } { + let asked = 0; + const prompter: Prompter = { isInteractive: () => true, ask: async () => { asked += 1; return null; }, askSecret: async () => { asked += 1; return PASSPHRASE; } }; + const host = createHost({ + paths: { stateRoot: path.join(home, name, '.midnight'), home: path.join(home, name) }, + settings: settingsFromEnvironment({ [PASSPHRASE_ENV]: PASSPHRASE }), + prompter, + engineLoader: loadInstalledEngine, + }); + return Object.assign(host, { asked: () => asked }); +} + +/** Writes `seed`'s wallet as `alice` under the host's state root, and makes it the active one. */ +function aliceOf(host: Host, seed: string): void { + const root = host.paths().stateRoot; + saveWalletConfig({ seed, addresses: deriveAllAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); +} + +const endpoints = () => ({ network: 'undeployed' as const, indexerWS: indexer.url, node: `ws://127.0.0.1:${refusing.port}`, proofServer: `http://127.0.0.1:${refusing.port}` }); +const refusingEverywhere = () => ({ network: 'undeployed' as const, indexerWS: `ws://127.0.0.1:${refusing.port}/api/v4/graphql/ws`, node: `ws://127.0.0.1:${refusing.port}`, proofServer: `http://127.0.0.1:${refusing.port}` }); + +type Said = ProgressEvent | WalletOpened; + +describe('readDustStatus', () => { + it('a wallet none of whose NIGHT is registered: its coins counted, its Dust not read, each step said', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: Said[] = []; + const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + + const status = await readDustStatus(host, { wallet: 'alice' }, { ...endpoints(), onProgress: (event) => said.push(event) }); + + expect(status).toEqual({ network: 'undeployed', registered: false, registeredUtxos: 0, unregisteredUtxos: 2 }); + expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address }); + expect(said[1]).toEqual({ kind: 'start', message: 'Checking registration on undeployed...' }); + expect(said.at(-1)).toEqual({ kind: 'done', message: 'Registration checked' }); + expect(said.filter((event) => event.kind === 'start')).toHaveLength(1); + expect(indexer.subscriptions.map((s) => s.address)).toEqual([address]); + }); + + it('reads a seed the program holds, at the address derived from it', async () => { + const seed = Buffer.from(SEED_B, 'hex'); + const status = await readDustStatus(programHost('a'), { seed }, endpoints()); + expect(status).toMatchObject({ registered: false, unregisteredUtxos: 2 }); + expect(indexer.subscriptions.map((s) => s.address)).toEqual([deriveUnshieldedAddress(seed, 'undeployed')]); + }); + + it('reads each host\'s own active wallet, two hosts in one process', async () => { + const hostA = programHost('a'); + const hostB = programHost('b'); + aliceOf(hostA, SEED_A); + aliceOf(hostB, SEED_B); + await Promise.all([readDustStatus(hostA, {}, endpoints()), readDustStatus(hostB, {}, endpoints())]); + expect(indexer.subscriptions.map((s) => s.address).sort()).toEqual([ + deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'), + deriveUnshieldedAddress(Buffer.from(SEED_B, 'hex'), 'undeployed'), + ].sort()); + }); + + it('fails with WALLET_NOT_FOUND for a wallet that is not there, and NETWORK_ERROR when the indexer refuses', async () => { + await expect(readDustStatus(programHost('a'), { wallet: 'nobody' }, endpoints())).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + const host = programHost('a'); + aliceOf(host, SEED_A); + await expect(readDustStatus(host, { wallet: 'alice' }, refusingEverywhere())).rejects.toMatchObject({ code: 'NETWORK_ERROR' }); + }); + + it('cancelled already: CancelledError, and no wallet unlocked, nothing asked of the indexer or said', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: Said[] = []; + await expect(readDustStatus(host, { wallet: 'alice' }, { ...endpoints(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(host.asked()).toBe(0); + expect(indexer.subscriptions).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('registerDust', () => { + it('refuses a wallet that is not there with WALLET_NOT_FOUND, and a seed of the wrong size with INVALID_ARGS, saying nothing', async () => { + const said: Said[] = []; + await expect(registerDust(programHost('a'), { wallet: 'nobody' }, { ...endpoints(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + await expect(registerDust(programHost('a'), { seed: new Uint8Array(31) }, endpoints())).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + expect(said).toEqual([]); + }); + + it('cancelled already: CancelledError, and no wallet unlocked, nothing asked or said', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: Said[] = []; + await expect(registerDust(host, { wallet: 'alice' }, { ...endpoints(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(host.asked()).toBe(0); + expect(indexer.subscriptions).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('exportDustSnapshot', () => { + it('refuses a wallet that is not there with WALLET_NOT_FOUND, saying nothing', async () => { + const said: ProgressEvent[] = []; + await expect(exportDustSnapshot(programHost('a'), { wallet: 'nobody' }, { ...endpoints(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + expect(said).toEqual([]); + }); + + it('fails with NETWORK_ERROR when the endpoints refuse, after saying it reads the Dust events', async () => { + const said: ProgressEvent[] = []; + await expect(exportDustSnapshot(programHost('a'), { seed: Buffer.from(SEED_A, 'hex') }, { ...refusingEverywhere(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'NETWORK_ERROR' }); + expect(said[0]).toEqual({ kind: 'start', message: 'Reading dust events from undeployed...' }); + }); + + it('cancelled already: CancelledError, and nothing started', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: ProgressEvent[] = []; + await expect(exportDustSnapshot(host, { wallet: 'alice' }, { ...endpoints(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(host.asked()).toBe(0); + expect(said).toEqual([]); + }); +}); diff --git a/src/commands/balance.ts b/src/commands/balance.ts index ce9cf730..85837974 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -1,20 +1,16 @@ // balance command — check unshielded + shielded balance via full wallet sync -// For positional address: unshielded only (GraphQL, no facade needed) +// For positional address: unshielded only (GraphQL, no facade) -import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { type NetworkName, isValidNetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { saveShieldedAddress, findWalletByAddress } from '../lib/wallet-config.ts'; -import { resolveSeedSource } from '../lib/seed-resolver.ts'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; -import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; +import { type ParsedArgs, hasFlag, isMinimalMode } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { findWalletByAddress } from '../lib/wallet-config.ts'; +import { walletSourceOf } from '../lib/seed-resolver.ts'; +import { networkChoiceFromArgs, networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { isNativeToken } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; -import { createEtaEstimator, formatSyncStatus } from '../lib/sync-eta.ts'; +import { addressNetwork, readAddressBalance, readWalletBalance } from '../lib/wallet/balance.ts'; import { header, keyValue, divider, formatNight, formatAddress, toNight } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; @@ -28,51 +24,19 @@ export default async function balanceCommand(args: ParsedArgs, ctx: CallContext) return walletBalance(args, ctx); } -/** - * Pull the network name out of a Bech32m address HRP. Addresses look like - * `mn_addr_1...` so we slice between the second underscore and the - * `1` separator. Returns null when the format doesn't match a known network. - */ -function inferNetworkFromAddress(address: string): NetworkName | null { - const match = address.match(/^mn_addr_([a-z]+)1/); - if (!match) return null; - const candidate = match[1]; - return isValidNetworkName(candidate) ? candidate : null; -} - // ── Positional address: unshielded only via GraphQL ── async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise { const address = args.subcommand!; ctx.diagnostics.line('balance', `address=${address}`); - - // Bech32m addresses encode the network in their HRP - // (mn_addr_undeployed1..., mn_addr_preprod1..., mn_addr_preview1...). - // When the caller didn't pass --network, infer from the address rather - // than defaulting to whatever the config says — otherwise users hit a - // confusing "expected HRP X, but was Y" error from the indexer. - // When --network is explicit and disagrees with the HRP, fail loudly so - // the mismatch surfaces at the CLI layer instead of as a GraphQL error. - const inferredNetwork = inferNetworkFromAddress(address); - const explicitNetwork = getFlag(args, 'network'); - if (explicitNetwork && inferredNetwork && explicitNetwork !== inferredNetwork) { - throw new UsageError( - `Address belongs to ${inferredNetwork} but --network is ${explicitNetwork}.\n` + - `Drop --network (we'll infer from the address) or pass an address for ${explicitNetwork}.` - ); - } - if (!explicitNetwork && inferredNetwork) { - args = { ...args, flags: { ...args.flags, network: inferredNetwork } }; - } - - const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); + const choice = networkChoiceFromArgs(args); // Shielded balances are private: reading one needs the wallet's secret key, // which an address alone doesn't carry. If this address belongs to one of our // wallets we have the seed → run the full wallet sync (which shows shielded). // Otherwise there's nothing to decrypt with → fail with a clear, actionable error. if (hasFlag(args, 'shielded')) { + const { network: networkName, root } = networkTargetOf(ctx.host, { ...choice, network: addressNetwork(address, choice.network) }); const owned = await findWalletByAddress(root, address, ctx.host.engines); if (owned) { ctx.diagnostics.line('balance', `shielded positional → wallet ${owned.wallet.name} on ${owned.network}`); @@ -90,28 +54,16 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise ); } - applyEndpointOverrides(networkConfig, { - proofServer: getFlag(args, 'proof-server'), - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - }, networkName, root); - - const spinner = ctx.progress.start(`Checking balance on ${networkName}...`); - + const progress = spinnerReporter(ctx.progress, false); try { - const result = await (await ctx.host.engines.for(networkName)).wallet.unshieldedBalance(address, networkConfig, { + const result = await readAddressBalance(ctx.host, address, { + ...choice, forceFresh: hasFlag(args, 'no-cache'), signal: ctx.signal, log: ctx.diagnostics.line, - onProgress: (current, highest) => { - if (highest > 0) { - const pct = Math.round((current / highest) * 100); - spinner.update(`Syncing transactions... ${pct}%`); - } - }, + onProgress: progress.report, }); - - spinner.stop(`Synced ${result.txCount} transactions`); + const networkName = result.network; if (hasFlag(args, 'json')) { const balances: Record = {}; @@ -164,7 +116,7 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise ctx.output.stderr('\n' + divider() + '\n\n'); } catch (err) { - spinner.fail('Failed'); + progress.fail('Failed'); throw err; } } @@ -172,143 +124,53 @@ async function addressBalance(args: ParsedArgs, ctx: CallContext): Promise // ── Wallet-based: full facade sync, both unshielded + shielded ── async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise { - const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); - ctx.diagnostics.line('balance', `network=${networkName} indexerWS=${networkConfig.indexerWS}`); - // Seed source: --seed → MN_SEED → --wallet → active wallet (shared resolver). - const { seed: seedBuffer, walletPath, config } = await resolveSeedSource(args, root, ctx.host); - ctx.diagnostics.line('balance', `wallet path=${walletPath ?? '(from --seed/MN_SEED)'}`); - // Derive the unshielded address from the seed so a --seed/MN_SEED caller (no wallet - // file) behaves identically to a named wallet — for a wallet this equals the stored one. - const engine = await ctx.host.engines.for(networkName); - const address = config?.addresses[networkName] ?? engine.keys.unshieldedAddress(seedBuffer, networkName); - const shieldedAddrStr = config?.shieldedAddresses?.[networkName] ?? ''; - - applyEndpointOverrides(networkConfig, { - proofServer: getFlag(args, 'proof-server'), - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - }, networkName, root); - - // Keep the SDK's transient errors and RPC noise off the terminal while this runs. - const stopListening = ctx.sdkWarnings.listen(undefined); - const noCache = hasFlag(args, 'no-cache'); const isJson = hasFlag(args, 'json'); - const nightToken = engine.ledger.nightTokenId(); - - let activeSpinner: Spinner | null = null; + // --json shows no step on the terminal. + const progress = spinnerReporter(ctx.progress, isJson); try { - - // Header + address chrome (we already have everything except live balances). - if (!isJson) { - ctx.output.stderr('\n' + header('Balance') + '\n\n'); - ctx.output.stderr(keyValue('Address', formatAddress(address)) + '\n'); - if (shieldedAddrStr) { - ctx.output.stderr(keyValue('Shielded', formatAddress(shieldedAddrStr)) + '\n'); - } - ctx.output.stderr(keyValue('Network', networkName) + '\n'); - ctx.output.stderr('\n ' + bold('Unshielded') + '\n'); - } - - // ── Phase 1: fast unshielded via GraphQL (no facade, no proof server) ── - if (!isJson) activeSpinner = ctx.progress.start('Checking unshielded...'); - ctx.diagnostics.line('balance', `phase=unshielded forceFresh=${noCache}`); - const unshieldedResult = await (await ctx.host.engines.for(networkName)).wallet.unshieldedBalance(address, networkConfig, { - forceFresh: noCache, + const result = await readWalletBalance(ctx.host, walletSourceOf(args, ctx.config.settings), { + ...networkChoiceFromArgs(args), + forceFresh: hasFlag(args, 'no-cache'), + forceShielded: hasFlag(args, 'force-shielded'), signal: ctx.signal, log: ctx.diagnostics.line, - // Quiet by design — this finishes in <1s on most networks. + sdkWarnings: ctx.sdkWarnings, + onProgress: (event) => { + if (event.kind === 'wallet-opened') { + // Header + address chrome (everything but the balances, which follow as they are read). + if (isJson) return; + ctx.output.stderr('\n' + header('Balance') + '\n\n'); + ctx.output.stderr(keyValue('Address', formatAddress(event.address)) + '\n'); + if (event.shieldedAddress) { + ctx.output.stderr(keyValue('Shielded', formatAddress(event.shieldedAddress)) + '\n'); + } + ctx.output.stderr(keyValue('Network', event.network) + '\n'); + ctx.output.stderr('\n ' + bold('Unshielded') + '\n'); + } else if (event.kind === 'unshielded-read') { + if (isJson) return; + if (event.night > 0n) { + ctx.output.stderr(keyValue(' NIGHT', bold(formatNight(event.night))) + '\n'); + ctx.output.stderr(keyValue(' UTXOs', event.utxoCount.toString()) + '\n'); + } else { + ctx.output.stderr(` ${dim('No unshielded balance')}\n`); + } + // Pipeable stdout for unshielded — emit immediately so consumers don't + // have to wait for the shielded sync to read the unshielded value. + ctx.output.stdout(`NIGHT=${event.night}\n`); + ctx.output.stderr('\n ' + bold('Shielded') + '\n'); + } else { + progress.report(event); + } + }, }); - const unshieldedBalance = unshieldedResult.balances.get(nightToken) ?? 0n; - const unshieldedUtxos = unshieldedResult.utxoCount; - ctx.diagnostics.line('balance', `unshielded fromCache=${unshieldedResult.fromCache} utxos=${unshieldedUtxos} txs=${unshieldedResult.txCount}`); - - if (activeSpinner) { - activeSpinner.stop('Unshielded ready'); - activeSpinner = null; - if (unshieldedBalance > 0n) { - ctx.output.stderr(keyValue(' NIGHT', bold(formatNight(unshieldedBalance))) + '\n'); - ctx.output.stderr(keyValue(' UTXOs', unshieldedUtxos.toString()) + '\n'); - } else { - ctx.output.stderr(` ${dim('No unshielded balance')}\n`); - } - } - - // Pipeable stdout for unshielded — emit immediately so consumers don't - // have to wait for the shielded sync to read the unshielded value. - if (!isJson) { - ctx.output.stdout(`NIGHT=${unshieldedBalance}\n`); - ctx.output.stderr('\n ' + bold('Shielded') + '\n'); - } - // ── Phase 2: shielded via facade sync (slower — needs ZK keys + WASM state) ── - // Skipped where shielded is unusable (no faucet on preview/preprod) unless - // --force-shielded is passed. This is the slow part of `mn balance`; skipping - // it makes hosted-network balance checks near-instant. - const shieldedEnabled = shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded')); - let liveShieldedAddrStr = shieldedAddrStr; - let shieldedBalance = 0n; - let shieldedCoins = 0; - let pendingCoins = 0; - let shieldedTokens: ReadonlyMap = new Map(); - - if (shieldedEnabled) { - if (!isJson) activeSpinner = ctx.progress.start('Syncing shielded...'); - const eta = createEtaEstimator(); - - // Live shielded address is pure key derivation — no facade sync needed. - liveShieldedAddrStr = engine.keys.shieldedAddress(seedBuffer, networkName); - // Cache the shielded address only when there's a backing wallet file (skip for --seed/MN_SEED). - if (walletPath) saveShieldedAddress(walletPath, networkName, liveShieldedAddrStr); - - // Shielded balance via the indexer-direct zswap-event reader + cache: it - // replays `zswapLedgerEvents` with the full secret keys (reconciling - // receives AND spends), replacing the facade's cold sync — ~50-70s first - // time on hosted nets, incremental after, memory-bounded. chainId - // invalidates the cache on chain reset. - await assertLedgerSupported(networkName, networkConfig, fetchProtocolVersion, ctx.signal); - // Null when the node can't say (the cache check is then skipped); a cancelled call stops here. - const chainId = (await getChainGenesisHash(networkConfig.node, ctx.signal)) ?? undefined; - const shieldedResult = await engine.readers.shieldedBalance( - seedBuffer, - networkName, - networkConfig.indexerWS, - { - root, - forceFresh: noCache, - chainId, - signal: ctx.signal, - onProgress: (applied, highest) => { - if (!activeSpinner) return; - const snap = eta.sample({ applied, highest, t: Date.now() }); - activeSpinner.update(formatSyncStatus(snap, 'Syncing shielded')); - }, - }, - ); - shieldedBalance = shieldedResult.balance; - shieldedCoins = shieldedResult.availableCoins; - shieldedTokens = shieldedResult.tokens; - pendingCoins = 0; // confirmed chain state from events; no in-flight coins - - if (activeSpinner) { - activeSpinner.stop('Shielded ready'); - activeSpinner = null; - if (shieldedBalance > 0n) { - ctx.output.stderr(keyValue(' NIGHT', bold(formatNight(shieldedBalance))) + '\n'); - ctx.output.stderr(keyValue(' Coins', `${shieldedCoins} available, ${pendingCoins} pending`) + '\n'); - } - // Other tokens by their full raw type: what `mn swap` and transfers take. - for (const [tokenType, amount] of shieldedTokens) { - ctx.output.stderr(keyValue(' Token', `${bold(amount.toString())} ${dim(tokenType)}`) + '\n'); - } - if (shieldedBalance === 0n && shieldedTokens.size === 0) { - ctx.output.stderr(` ${dim('No shielded balance')}\n`); - } - } - } else if (!isJson) { - ctx.output.stderr(` ${dim('Skipped — ' + shieldedDisabledReason(networkName))}\n`); - } + const { network: networkName, unshielded, shielded } = result; + const shieldedNight = shielded?.night ?? 0n; + const shieldedCoins = shielded?.availableCoins ?? 0; + // Confirmed chain state from events: no coins in flight. + const pendingCoins = 0; + const shieldedTokens: ReadonlyMap = shielded?.tokens ?? new Map(); if (isJson) { const tokens = Object.fromEntries([...shieldedTokens].map(([tokenType, amount]) => [tokenType, amount.toString()])); @@ -319,32 +181,46 @@ async function walletBalance(args: ParsedArgs, ctx: CallContext): Promise if (isMinimalMode(args)) { ctx.output.result({ network: networkName, - unshielded: { NIGHT: toNight(unshieldedBalance), utxoCount: unshieldedUtxos }, - shielded: { NIGHT: toNight(shieldedBalance), availableCoins: shieldedCoins, pendingCoins, tokens }, - shieldedSynced: shieldedEnabled, + unshielded: { NIGHT: toNight(unshielded.night), utxoCount: unshielded.utxoCount }, + shielded: { NIGHT: toNight(shieldedNight), availableCoins: shieldedCoins, pendingCoins, tokens }, + shieldedSynced: shielded !== null, }); return; } ctx.output.result({ - address, - shieldedAddress: liveShieldedAddrStr, + address: result.address, + shieldedAddress: result.shieldedAddress ?? '', network: networkName, - unshielded: { NIGHT: toNight(unshieldedBalance), utxoCount: unshieldedUtxos }, - shielded: { NIGHT: toNight(shieldedBalance), availableCoins: shieldedCoins, pendingCoins, tokens }, - shieldedSynced: shieldedEnabled, + unshielded: { NIGHT: toNight(unshielded.night), utxoCount: unshielded.utxoCount }, + shielded: { NIGHT: toNight(shieldedNight), availableCoins: shieldedCoins, pendingCoins, tokens }, + shieldedSynced: shielded !== null, }); return; } + if (shielded !== null) { + if (shieldedNight > 0n) { + ctx.output.stderr(keyValue(' NIGHT', bold(formatNight(shieldedNight))) + '\n'); + ctx.output.stderr(keyValue(' Coins', `${shieldedCoins} available, ${pendingCoins} pending`) + '\n'); + } + // Other tokens by their full raw type: what `mn swap` and transfers take. + for (const [tokenType, amount] of shieldedTokens) { + ctx.output.stderr(keyValue(' Token', `${bold(amount.toString())} ${dim(tokenType)}`) + '\n'); + } + if (shieldedNight === 0n && shieldedTokens.size === 0) { + ctx.output.stderr(` ${dim('No shielded balance')}\n`); + } + } else { + ctx.output.stderr(` ${dim('Skipped — ' + shieldedDisabledReason(networkName))}\n`); + } + // When shielded was skipped, say so on stdout too — `=0` would read as a // confirmed zero to a script parsing the pipeable output. - ctx.output.stdout(`SHIELDED_NIGHT=${shieldedEnabled ? shieldedBalance : 'skipped'}\n`); + ctx.output.stdout(`SHIELDED_NIGHT=${shielded !== null ? shieldedNight : 'skipped'}\n`); for (const [tokenType, amount] of shieldedTokens) ctx.output.stdout(`SHIELDED_${tokenType}=${amount}\n`); ctx.output.stderr('\n' + divider() + '\n\n'); } catch (err) { - activeSpinner?.fail('Failed'); + progress.fail('Failed'); throw err; - } finally { - stopListening(); } } diff --git a/src/commands/dust.ts b/src/commands/dust.ts index 8fd95f4b..cb78d88f 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -3,17 +3,19 @@ import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveSeed } from '../lib/seed-resolver.ts'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { walletSourceOf } from '../lib/seed-resolver.ts'; +import { exportDustSnapshot, readDustStatus, registerDust, type DustRegistrationResult, type DustStatus } from '../lib/wallet/dust.ts'; +import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; import { header, keyValue, divider, formatDust, successMessage, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { type Receipt, receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; import { receiptText } from '../ui/receipt.ts'; export default async function dustCommand(args: ParsedArgs, ctx: CallContext): Promise { @@ -29,360 +31,195 @@ export default async function dustCommand(args: ParsedArgs, ctx: CallContext): P ); } - // Resolve network first — independent of the wallet (--network flag / config / fallback). - const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); - - // Apply endpoint overrides: --flag > config > network default - applyEndpointOverrides(networkConfig, { - proofServer: getFlag(args, 'proof-server'), - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - }, networkName, root); - const isJson = hasFlag(args, 'json'); const minimal = isMinimalMode(args); + // The network (--network flag / config / fallback) and its endpoints (--flag > config > network default). + const call = { ...networkChoiceFromArgs(args), signal: ctx.signal, log: ctx.diagnostics.line, sdkWarnings: ctx.sdkWarnings }; + const progress = spinnerReporter(ctx.progress, false); - // export: standalone path. Accepts a raw --seed (so a dApp operator can export a - // snapshot for its own seed with no named wallet) or falls back to a named wallet. - if (subcommand === 'export') { - // The chain-id check connects to the node; keep polkadot-js's RPC-CORE noise off stderr. - const stopListening = ctx.sdkWarnings.listen(undefined); - try { - await dustExport(await resolveSeed(args, root, ctx.host), networkName, networkConfig, isJson, minimal, ctx); - } finally { - stopListening(); + try { + // export: accepts a raw --seed (so a dApp operator can export a snapshot for its + // own seed with no named wallet) or falls back to a named wallet. + if (subcommand === 'export') { + const result = await exportDustSnapshot(ctx.host, walletSourceOf(args, ctx.config.settings), { ...call, onProgress: progress.report }); + printExport(result, isJson, minimal, ctx); + return; } - return; - } - // status / register: named wallet + its stored address (used by the registration pre-check). - const config = await unlockWallet(resolveWalletPath(root, getFlag(args, 'wallet')), { root, host: ctx.host }); - const seedBuffer = Buffer.from(config.seed, 'hex'); - const address = config.addresses[networkName]; - - // status: pre-check registration via the indexer before paying for a full sync. - // If the wallet isn't registered, no point doing anything else — return fast. - if (subcommand === 'status') { - const preCheck = await dustRegistrationPreCheck( - address, - networkName, - networkConfig.indexerWS, - ctx, - ); - if (!preCheck.isRegistered) { - printUnregisteredStatus(networkName, preCheck, isJson, minimal, ctx); + // status / register: a named wallet, the active one when none is given. + const wallet = { wallet: getFlag(args, 'wallet') }; + if (subcommand === 'status') { + const status = await readDustStatus(ctx.host, wallet, { ...call, forceFresh: hasFlag(args, 'no-cache'), onProgress: headed('Dust Status', progress.report, ctx) }); + printStatus(status, isJson, minimal, ctx); return; } - // Registered → read balance directly from indexer (bypasses the dust-wallet - // SDK's `isConnected` hang). No facade needed for a read-only query. - const useCache = !hasFlag(args, 'no-cache'); - await dustStatusDirect(seedBuffer, networkName, networkConfig, preCheck, isJson, minimal, useCache, ctx); - return; - } - // register: full facade flow (requires proof server, keystore, sync). - // The repo's withFacade owns: validate caches, pre-prime dust, build facade, - // sync (with retry), save, invalidate, stop. We just provide the work. - rejectNoCacheForWrites(args); - await dustRegister(seedBuffer, networkName, networkConfig, isJson, ctx); + // register: the full wallet flow (proof server, keystore, sync); writes always use the cache. + rejectNoCacheForWrites(args); + const registration = await registerDust(ctx.host, wallet, { ...call, onProgress: headed('Dust Register', progress.report, ctx) }); + printRegistration(registration, isJson, ctx); + } catch (err) { + progress.fail('Failed'); + throw err; + } } -// export: fast dust-direct sync → emit a facade-restorable snapshot. The snapshot -// (the pipeable data) goes to stdout; a summary goes to stderr; --json bundles it all. -async function dustExport( - seedBuffer: Buffer, - networkName: NetworkName, - networkConfig: NetworkConfig, - jsonMode: boolean, - minimal: boolean, - ctx: CallContext, -): Promise { - const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); - try { - const result = await (await ctx.host.engines.for(networkName)).wallet.exportDust(seedBuffer, networkName, networkConfig, { - root: ctx.config.paths.stateRoot, - notice: ctx.host.notice, - signal: ctx.signal, - log: ctx.diagnostics.line, - onProgress: (applied, maxIdSeen) => spinner.update( - maxIdSeen > 0 - ? `Reading dust events... ${applied}/${maxIdSeen + 1}` - : `Reading dust events... ${applied}`, - ), - }); - spinner.stop( - result.partial - ? 'Dust snapshot ready (incomplete)' - : result.fromCache && result.eventCount === 0 ? 'Cache up to date' : 'Dust snapshot ready', - ); - - if (jsonMode) { - ctx.output.result({ - subcommand: 'export', - network: result.network, - dustPublicKey: result.dustPublicKey, - offset: result.offset, - dustBalance: toDust(result.balance), - eventCount: result.eventCount, - fromCache: result.fromCache, - partial: result.partial, - snapshot: result.snapshot, - }); +/** Shows each step, and heads the output with `title` and the network once the wallet is open. */ +function headed(title: string, report: (event: ProgressEvent) => void, ctx: CallContext): (event: ProgressEvent | WalletOpened) => void { + return (event) => { + if (event.kind !== 'wallet-opened') { + report(event); return; } + ctx.output.stderr('\n' + header(title) + '\n\n'); + ctx.output.stderr(keyValue('Network', event.network) + '\n\n'); + }; +} - ctx.output.stdout(result.snapshot + '\n'); - if (minimal) return; - ctx.output.stderr('\n' + keyValue('Network', result.network) + '\n'); - ctx.output.stderr(keyValue('Dust balance', formatDust(result.balance)) + '\n'); - ctx.output.stderr(keyValue('Snapshot offset', String(result.offset)) + '\n'); - if (result.partial) { - // Loud, because a partial snapshot restores without error and then quietly - // hands the remaining events back to the SDK's cold sync — the exact failure - // this command exists to prevent. - ctx.output.stderr( - '\n' + yellow(bold('⚠ Snapshot is INCOMPLETE — the sync did not reach the chain tip.')) + '\n' + - dim(' Restoring it still beats a cold start, but the wallet has events left to catch up on.') + '\n' + - dim(' Re-run `mn dust export` to resume from this checkpoint and finish.') + '\n', - ); - } - ctx.output.stderr('\n' + dim('Restore with the wallet SDK dustSerializedState to skip the cold dust sync.') + '\n'); - } catch (err) { - spinner.fail('Failed'); - throw err; +// export: the snapshot (the pipeable data) goes to stdout; a summary goes to stderr; --json bundles it all. +function printExport(result: DustExportResult, jsonMode: boolean, minimal: boolean, ctx: CallContext): void { + if (jsonMode) { + ctx.output.result({ + subcommand: 'export', + network: result.network, + dustPublicKey: result.dustPublicKey, + offset: result.offset, + dustBalance: toDust(result.balance), + eventCount: result.eventCount, + fromCache: result.fromCache, + partial: result.partial, + snapshot: result.snapshot, + }); + return; } -} -interface PreCheckResult { - isRegistered: boolean; - registeredUtxos: number; - unregisteredUtxos: number; + ctx.output.stdout(result.snapshot + '\n'); + if (minimal) return; + ctx.output.stderr('\n' + keyValue('Network', result.network) + '\n'); + ctx.output.stderr(keyValue('Dust balance', formatDust(result.balance)) + '\n'); + ctx.output.stderr(keyValue('Snapshot offset', String(result.offset)) + '\n'); + if (result.partial) { + // Loud, because a partial snapshot restores without error and then quietly + // hands the remaining events back to the SDK's cold sync — the exact failure + // this command exists to prevent. + ctx.output.stderr( + '\n' + yellow(bold('⚠ Snapshot is INCOMPLETE — the sync did not reach the chain tip.')) + '\n' + + dim(' Restoring it still beats a cold start, but the wallet has events left to catch up on.') + '\n' + + dim(' Re-run `mn dust export` to resume from this checkpoint and finish.') + '\n', + ); + } + ctx.output.stderr('\n' + dim('Restore with the wallet SDK dustSerializedState to skip the cold dust sync.') + '\n'); } -// Queries the indexer directly for UTXO registration metadata — no facade, no dust sync. -// Used to short-circuit `dust status` when the wallet has no registered UTXOs. -async function dustRegistrationPreCheck( - address: string, - networkName: string, - indexerWS: string, - ctx: CallContext, -): Promise { - ctx.output.stderr('\n' + header('Dust Status') + '\n\n'); - ctx.output.stderr(keyValue('Network', networkName) + '\n\n'); +function printStatus(status: DustStatus, jsonMode: boolean, minimal: boolean, ctx: CallContext): void { + const { network: networkName, registeredUtxos, unregisteredUtxos } = status; - const spinner = ctx.progress.start(`Checking registration on ${networkName}...`); + // Not registered: the Dust was not read. + if (!status.registered) { + const totalUtxos = registeredUtxos + unregisteredUtxos; - try { - const summary = await checkBalance(address, indexerWS, (current, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((current / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Checking registration...' : `Checking registration... ${pct}%`); + if (jsonMode) { + if (minimal) { + ctx.output.result({ + network: networkName, + registered: false, + registeredUtxos, + unregisteredUtxos, + }); + return; } - }, ctx.signal); + ctx.output.result({ + subcommand: 'status', + registered: false, + registeredUtxos, + unregisteredUtxos, + network: networkName, + }); + return; + } - throwIfCancelled(ctx.signal); + // Machine-readable to stdout + ctx.output.stdout('registered=no\n'); + ctx.output.stdout(`registered_utxos=${registeredUtxos}\n`); + ctx.output.stdout(`unregistered_utxos=${unregisteredUtxos}\n`); - const { registeredUtxos, unregisteredUtxos } = summary; - spinner.stop('Registration checked'); + // Formatted to stderr + ctx.output.stderr(keyValue('Registered', bold('no')) + '\n'); + ctx.output.stderr(keyValue('UTXOs', `${registeredUtxos} registered, ${unregisteredUtxos} unregistered`) + '\n'); - return { - isRegistered: registeredUtxos > 0, - registeredUtxos, - unregisteredUtxos, - }; - } catch (err) { - spinner.fail('Failed'); - throw err; - } -} + if (totalUtxos === 0) { + ctx.output.stderr('\n' + dim('No NIGHT UTXOs at this address. Fund the wallet first.') + '\n'); + } else { + ctx.output.stderr('\n' + dim('Not generating dust. Run: midnight dust register') + '\n'); + } -// Prints the "not registered" status and exits. Called only when registeredUtxos === 0. -function printUnregisteredStatus( - networkName: string, - preCheck: PreCheckResult, - jsonMode: boolean, - minimal: boolean, - ctx: CallContext, -): void { - const { registeredUtxos, unregisteredUtxos } = preCheck; - const totalUtxos = registeredUtxos + unregisteredUtxos; + ctx.output.stderr('\n' + divider() + '\n\n'); + return; + } + const dustAvailable = status.availableCoins > 0; if (jsonMode) { + // Slim drops eventsApplied/ownedUtxos/cached/subcommand — internal + // sync details an agent doesn't need to act on. if (minimal) { ctx.output.result({ network: networkName, - registered: false, + registered: true, registeredUtxos, unregisteredUtxos, + dustBalance: toDust(status.dust), + dustAvailable, }); return; } ctx.output.result({ subcommand: 'status', - registered: false, + registered: true, registeredUtxos, unregisteredUtxos, + dustBalance: toDust(status.dust), + dustAvailable, + eventsApplied: status.eventsApplied, + ownedUtxos: status.ownedUtxos, + cached: status.fromCache, network: networkName, }); return; } // Machine-readable to stdout - ctx.output.stdout('registered=no\n'); + ctx.output.stdout('registered=yes\n'); + ctx.output.stdout(`dust=${status.dust}\n`); ctx.output.stdout(`registered_utxos=${registeredUtxos}\n`); ctx.output.stdout(`unregistered_utxos=${unregisteredUtxos}\n`); // Formatted to stderr - ctx.output.stderr(keyValue('Registered', bold('no')) + '\n'); + ctx.output.stderr(keyValue('Registered', bold('yes')) + '\n'); ctx.output.stderr(keyValue('UTXOs', `${registeredUtxos} registered, ${unregisteredUtxos} unregistered`) + '\n'); - - if (totalUtxos === 0) { - ctx.output.stderr('\n' + dim('No NIGHT UTXOs at this address. Fund the wallet first.') + '\n'); - } else { - ctx.output.stderr('\n' + dim('Not generating dust. Run: midnight dust register') + '\n'); + ctx.output.stderr(keyValue('Dust Balance', bold(formatDust(status.dust))) + '\n'); + ctx.output.stderr(keyValue('Dust Available', dustAvailable ? 'yes' : 'no') + '\n'); + ctx.output.stderr(keyValue('Events applied', status.eventsApplied.toString() + (status.fromCache ? ' (delta)' : '')) + '\n'); + if (unregisteredUtxos > 0) { + ctx.output.stderr('\n' + dim(`${unregisteredUtxos} UTXO(s) not yet registered. Run: midnight dust register`) + '\n'); } - ctx.output.stderr('\n' + divider() + '\n\n'); } -async function dustRegister( - seedBuffer: Buffer, - network: NetworkName, - networkConfig: NetworkConfig, - jsonMode: boolean, - ctx: CallContext, -): Promise { - const networkName = networkConfig.networkId.toLowerCase(); - ctx.output.stderr('\n' + header('Dust Register') + '\n\n'); - ctx.output.stderr(keyValue('Network', networkName) + '\n\n'); - - const spinner = ctx.progress.start('Syncing wallet...'); - - try { - const result = await (await ctx.host.engines.for(network)).wallet.registerDust(seedBuffer, networkConfig, { - root: ctx.config.paths.stateRoot, - notice: ctx.host.notice, - signal: ctx.signal, - sdkWarnings: ctx.sdkWarnings, - log: ctx.diagnostics.line, - onStatus: (s) => spinner.update(s), - onSyncProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), - onSyncWarning: (_tag, msg) => spinner.update(`Syncing wallet... (${msg}, retrying)`), - }); - const dustBal = result.dustBalance; - let receipt: Receipt | undefined; - if (result.txHash) { - spinner.update('Waiting for the indexer to list it...'); - receipt = await receiptOf(networkConfig.indexer, result.txHash, ctx.signal); - } - - spinner.stop(result.alreadyAvailable ? 'Dust already available' : 'Dust registration complete'); - - if (jsonMode) { - const json: Record = { subcommand: 'register', dustBalance: toDust(dustBal) }; - if (result.txHash) json.txHash = result.txHash; - if (receipt) Object.assign(json, receiptJson(receipt)); - ctx.output.result(json); - return; - } - - ctx.output.stdout(dustBal.toString() + '\n'); - ctx.output.stderr('\n' + successMessage( - result.alreadyAvailable - ? `Dust tokens already available: ${formatDust(dustBal)}` - : `Dust tokens available: ${formatDust(dustBal)}`, - ) + '\n'); - ctx.output.stderr((receipt && result.txHash ? receiptText(receipt, result.txHash) : '') + '\n'); - } catch (err) { - spinner.fail('Failed'); - throw err; +function printRegistration(result: DustRegistrationResult, jsonMode: boolean, ctx: CallContext): void { + const { dust, txHash, receipt } = result; + if (jsonMode) { + const json: Record = { subcommand: 'register', dustBalance: toDust(dust) }; + if (txHash) json.txHash = txHash; + if (receipt) Object.assign(json, receiptJson(receipt)); + ctx.output.result(json); + return; } -} - -// Registered-status path: indexer-direct dust read via the wallet data -// repository. Repo handles cache load/save, in-memory memo, tip-aware -// invalidation, and force-fresh — see lib/wallet-data-repository.ts. -async function dustStatusDirect( - seedBuffer: Buffer, - network: NetworkName, - networkConfig: NetworkConfig, - preCheck: PreCheckResult, - jsonMode: boolean, - minimal: boolean, - useCache: boolean, - ctx: CallContext, -): Promise { - const networkName = networkConfig.networkId.toLowerCase(); - const spinner = ctx.progress.start(`Reading dust events from ${networkName}...`); - - try { - const view = await (await ctx.host.engines.for(network)).wallet.dustBalance(seedBuffer, networkConfig, { - root: ctx.config.paths.stateRoot, - notice: ctx.host.notice, - forceFresh: !useCache, - signal: ctx.signal, - log: ctx.diagnostics.line, - onStatus: (msg) => spinner.update(msg), - }); - - spinner.stop(view.fromCache && view.eventsApplied === 0 ? 'Cache up to date' : 'Dust events applied'); - - const { registeredUtxos, unregisteredUtxos } = preCheck; - if (jsonMode) { - // Slim drops eventsApplied/ownedUtxos/cached/subcommand — internal - // sync details an agent doesn't need to act on. - if (minimal) { - ctx.output.result({ - network: networkName, - registered: true, - registeredUtxos, - unregisteredUtxos, - dustBalance: toDust(view.balance), - dustAvailable: view.availableCoins > 0, - }); - return; - } - ctx.output.result({ - subcommand: 'status', - registered: true, - registeredUtxos, - unregisteredUtxos, - dustBalance: toDust(view.balance), - dustAvailable: view.availableCoins > 0, - eventsApplied: view.eventsApplied, - ownedUtxos: view.ownedUtxoCount, - cached: view.fromCache, - network: networkName, - }); - return; - } - - // Machine-readable to stdout - ctx.output.stdout('registered=yes\n'); - ctx.output.stdout(`dust=${view.balance}\n`); - ctx.output.stdout(`registered_utxos=${registeredUtxos}\n`); - ctx.output.stdout(`unregistered_utxos=${unregisteredUtxos}\n`); - - // Formatted to stderr - ctx.output.stderr(keyValue('Registered', bold('yes')) + '\n'); - ctx.output.stderr(keyValue('UTXOs', `${registeredUtxos} registered, ${unregisteredUtxos} unregistered`) + '\n'); - ctx.output.stderr(keyValue('Dust Balance', bold(formatDust(view.balance))) + '\n'); - ctx.output.stderr(keyValue('Dust Available', view.availableCoins > 0 ? 'yes' : 'no') + '\n'); - ctx.output.stderr(keyValue('Events applied', view.eventsApplied.toString() + (view.fromCache ? ' (delta)' : '')) + '\n'); - if (unregisteredUtxos > 0) { - ctx.output.stderr('\n' + dim(`${unregisteredUtxos} UTXO(s) not yet registered. Run: midnight dust register`) + '\n'); - } - ctx.output.stderr('\n' + divider() + '\n\n'); - } catch (err) { - spinner.fail('Failed'); - throw err; - } + ctx.output.stdout(dust.toString() + '\n'); + ctx.output.stderr('\n' + successMessage( + result.alreadyAvailable + ? `Dust tokens already available: ${formatDust(dust)}` + : `Dust tokens available: ${formatDust(dust)}`, + ) + '\n'); + ctx.output.stderr((receipt && txHash ? receiptText(receipt, txHash) : '') + '\n'); } diff --git a/src/lib/seed-resolver.ts b/src/lib/seed-resolver.ts index f149e8fb..b017c523 100644 --- a/src/lib/seed-resolver.ts +++ b/src/lib/seed-resolver.ts @@ -5,6 +5,8 @@ import { getFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { Settings } from '@kuiralabs/midnight-cli-core/lib/settings'; import { resolveWalletPath, unlockWallet, type UnlockHost, type WalletConfig } from './wallet-config.ts'; export interface ResolvedSeed { @@ -47,22 +49,33 @@ export function parseSeedHex(input: string, label: string): Buffer { } /** - * Resolve a wallet seed with uniform precedence: + * The wallet a library function acts for: a wallet by name or path (absent: + * the active one), unlocked through the host's passphrase and prompter; or a + * seed the program holds (32 bytes raw, or 64 from a BIP-39 mnemonic). + */ +export type WalletSource = { wallet?: string } | { seed: Uint8Array }; + +/** What a wallet is opened through: unlocked through the host, under its state root. */ +export type SeedHost = UnlockHost & Pick; + +/** + * The seed of the wallet `source` names, with its wallet file and config + * (both null for a seed the program holds). A wallet is one under the host's + * state root, unlocked through its passphrase and prompter. + */ +export function seedOf(host: SeedHost, source: WalletSource): Promise { + return seedUnder(host.paths().stateRoot, host, source); +} + +/** + * Where a command's arguments say its seed comes from, with uniform precedence: * `--seed ` → `MN_SEED` (env, kept off the process list) → `--wallet ` → active wallet. - * Returns the seed plus the backing wallet file/config (both null for a `--seed` / `MN_SEED` - * source), so a caller that caches to the wallet file can skip that when there is none. - * Wallets are the ones under the state root `root`; MN_SEED is the one in `host`'s settings. + * MN_SEED is the one in `settings`. */ -export async function resolveSeedSource(args: ParsedArgs, root: string, host: UnlockHost, opts: ResolveSeedOptions = {}): Promise { +export function walletSourceOf(args: ParsedArgs, settings: Pick, opts: ResolveSeedOptions = {}): WalletSource { const seedFlag = getFlag(args, 'seed'); - const seedSource = seedFlag ?? host.settings().seed; - if (seedSource) { - return { - seed: parseSeedHex(seedSource, seedFlag ? '--seed' : 'MN_SEED'), - walletPath: null, - config: null, - }; - } + const seedSource = seedFlag ?? settings.seed; + if (seedSource) return { seed: parseSeedHex(seedSource, seedFlag ? '--seed' : 'MN_SEED') }; const walletName = getFlag(args, 'wallet'); if (walletName === undefined && opts.requireExplicit) { @@ -73,13 +86,33 @@ export async function resolveSeedSource(args: ParsedArgs, root: string, host: Un ' --wallet derive from a saved wallet', ); } + return walletName === undefined ? {} : { wallet: walletName }; +} - const walletPath = resolveWalletPath(root, walletName); - const { seed, mnemonic: _mnemonic, ...config } = await unlockWallet(walletPath, { root, host }); - return { seed: Buffer.from(seed, 'hex'), walletPath, config }; +/** + * Resolve a wallet seed from a command's arguments (walletSourceOf's precedence). + * Returns the seed plus the backing wallet file/config (both null for a `--seed` / `MN_SEED` + * source), so a caller that caches to the wallet file can skip that when there is none. + * Wallets are the ones under the state root `root`; MN_SEED is the one in `host`'s settings. + */ +export async function resolveSeedSource(args: ParsedArgs, root: string, host: UnlockHost, opts: ResolveSeedOptions = {}): Promise { + return seedUnder(root, host, walletSourceOf(args, host.settings(), opts)); } /** Just the seed — for commands that don't touch the wallet file. */ export async function resolveSeed(args: ParsedArgs, root: string, host: UnlockHost, opts?: ResolveSeedOptions): Promise { return (await resolveSeedSource(args, root, host, opts)).seed; } + +async function seedUnder(root: string, host: UnlockHost, source: WalletSource): Promise { + if ('seed' in source) { + // The two sizes a seed comes in, as parseSeedHex accepts them: any other is a mistake, never a different wallet. + if (source.seed.length !== 32 && source.seed.length !== 64) { + throw new UsageError(`A seed must be 32 or 64 bytes (a raw seed, or a BIP-39 seed); this one is ${source.seed.length}`); + } + return { seed: Buffer.from(source.seed), walletPath: null, config: null }; + } + const walletPath = resolveWalletPath(root, source.wallet); + const { seed, mnemonic: _mnemonic, ...config } = await unlockWallet(walletPath, { root, host }); + return { seed: Buffer.from(seed, 'hex'), walletPath, config }; +} diff --git a/src/lib/wallet/balance.ts b/src/lib/wallet/balance.ts new file mode 100644 index 00000000..08805423 --- /dev/null +++ b/src/lib/wallet/balance.ts @@ -0,0 +1,192 @@ +// What an address or a wallet holds. An address's balance is its unshielded +// tokens, read from the indexer without a wallet; a wallet's adds its shielded +// NIGHT and tokens, read with its secret keys, where the network has a +// shielded faucet (or when asked). + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { isValidNetworkName, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { shieldedSyncEnabled } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; +import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; +import { saveShieldedAddress } from '../wallet-config.ts'; +import { seedOf, type WalletSource } from '../seed-resolver.ts'; +import { createEtaEstimator, formatSyncStatus } from '../sync-eta.ts'; +import { networkChoiceOf, unshieldedAddressOf, type WalletCallOptions, type WalletOpened } from './wallet-call.ts'; + +/** An address's unshielded tokens. */ +export interface AddressBalance { + readonly address: string; + readonly network: NetworkName; + /** Each token's balance by its raw type, in its smallest unit; NIGHT is under the native token's type. */ + readonly balances: ReadonlyMap; + readonly utxoCount: number; + readonly txCount: number; +} + +export interface ReadAddressBalanceOptions extends Omit { + /** Read past every cache, from the indexer. */ + forceFresh?: boolean; +} + +/** + * The network to read `address` on: `network` when given, else the one its + * prefix names (`mn_addr_1…`), else undefined (the saved network). + * Throws UsageError when the two differ: the indexer would refuse the address. + */ +export function addressNetwork(address: string, network?: NetworkName): NetworkName | undefined { + const inferred = inferNetworkFromAddress(address); + if (network && inferred && network !== inferred) { + throw new UsageError( + `Address belongs to ${inferred} but --network is ${network}.\n` + + `Drop --network (we'll infer from the address) or pass an address for ${network}.` + ); + } + return network ?? inferred ?? undefined; +} + +/** The network an address's prefix names, or null when it names none. */ +function inferNetworkFromAddress(address: string): NetworkName | null { + const match = address.match(/^mn_addr_([a-z]+)1/); + if (!match) return null; + const candidate = match[1]; + return isValidNetworkName(candidate) ? candidate : null; +} + +/** + * The unshielded balance of `address`, from the indexer through mn's cache, + * on the network its prefix names unless `options.network` says another + * (refused when they differ). + */ +export async function readAddressBalance(host: Host, address: string, options: ReadAddressBalanceOptions = {}): Promise { + const { signal, log } = options; + throwIfCancelled(signal); + const { network, networkConfig } = networkTargetOf(host, { ...networkChoiceOf(options), network: addressNetwork(address, options.network) }); + const steps = progressSteps(options.onProgress); + steps.start(`Checking balance on ${network}...`); + const result = await (await host.engines.for(network)).wallet.unshieldedBalance(address, networkConfig, { + forceFresh: options.forceFresh, + signal, + log, + onProgress: (current, highest) => { + if (highest > 0) steps.update(`Syncing transactions... ${Math.round((current / highest) * 100)}%`); + }, + }); + steps.done(`Synced ${result.txCount} transactions`); + return { address, network, balances: result.balances, utxoCount: result.utxoCount, txCount: result.txCount }; +} + +/** A wallet's shielded holdings. */ +export interface ShieldedHoldings { + /** NIGHT, in its smallest unit. */ + readonly night: bigint; + /** Spendable NIGHT coins. */ + readonly availableCoins: number; + /** Shielded tokens other than NIGHT, by raw type (sorted), in their smallest units. */ + readonly tokens: ReadonlyMap; +} + +/** What a wallet holds on a network. */ +export interface WalletBalance { + readonly network: NetworkName; + /** Its unshielded address. */ + readonly address: string; + /** Its shielded address: derived when the shielded balance was read, else the one its file saved, if any. */ + readonly shieldedAddress?: string; + readonly unshielded: { readonly night: bigint; readonly utxoCount: number }; + /** Null when the shielded balance was not read: the network has no shielded faucet, and `forceShielded` was not given. */ + readonly shielded: ShieldedHoldings | null; +} + +/** The wallet's unshielded NIGHT is read, before its shielded balance is. */ +export interface UnshieldedRead { + readonly kind: 'unshielded-read'; + /** NIGHT, in its smallest unit. */ + readonly night: bigint; + readonly utxoCount: number; +} + +export interface ReadWalletBalanceOptions extends WalletCallOptions { + /** Read past every cache, from the indexer. */ + forceFresh?: boolean; + /** Read the shielded balance even where the network has no shielded faucet. */ + forceShielded?: boolean; +} + +/** + * What a wallet holds: its unshielded NIGHT from the indexer, then its + * shielded NIGHT and tokens with its secret keys (mn's reader of the + * indexer's events, through its cache), where the network has a shielded + * faucet or `forceShielded` says. A wallet file is given its shielded address. + */ +export async function readWalletBalance(host: Host, source: WalletSource, options: ReadWalletBalanceOptions = {}): Promise { + const { signal, log, onProgress } = options; + const forceFresh = options.forceFresh === true; + throwIfCancelled(signal); + const { network, networkConfig, root } = networkTargetOf(host, networkChoiceOf(options)); + log?.('balance', `network=${network} indexerWS=${networkConfig.indexerWS}`); + const wallet = await seedOf(host, source); + log?.('balance', `wallet path=${wallet.walletPath ?? '(from --seed/MN_SEED)'}`); + const engine = await host.engines.for(network); + const address = await unshieldedAddressOf(wallet, network, host.engines); + const savedShieldedAddress = wallet.config?.shieldedAddresses?.[network] || undefined; + const nightToken = engine.ledger.nightTokenId(); + const steps = progressSteps(onProgress); + + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, async (sdkWarnings) => { + // Keep the SDK's transient errors and RPC noise off the terminal while this runs. + const stopListening = sdkWarnings.listen(undefined); + try { + onProgress?.({ kind: 'wallet-opened', network, address, ...(savedShieldedAddress === undefined ? {} : { shieldedAddress: savedShieldedAddress }) }); + + // Unshielded first, from the indexer alone: no proof server, under a second on most networks. + steps.start('Checking unshielded...'); + log?.('balance', `phase=unshielded forceFresh=${forceFresh}`); + const unshieldedResult = await engine.wallet.unshieldedBalance(address, networkConfig, { forceFresh, signal, log }); + const unshielded = { night: unshieldedResult.balances.get(nightToken) ?? 0n, utxoCount: unshieldedResult.utxoCount }; + log?.('balance', `unshielded fromCache=${unshieldedResult.fromCache} utxos=${unshielded.utxoCount} txs=${unshieldedResult.txCount}`); + steps.done('Unshielded ready'); + onProgress?.({ kind: 'unshielded-read', ...unshielded }); + + // The shielded read is the slow part; skipping it where shielded is + // unusable (no faucet on preview/preprod) makes those reads near-instant. + if (!shieldedSyncEnabled(network, options.forceShielded)) { + return { network, address, ...(savedShieldedAddress === undefined ? {} : { shieldedAddress: savedShieldedAddress }), unshielded, shielded: null }; + } + + steps.start('Syncing shielded...'); + const eta = createEtaEstimator(); + // The shielded address is key derivation alone; a wallet file keeps it for next time. + const shieldedAddress = engine.keys.shieldedAddress(wallet.seed, network); + if (wallet.walletPath) saveShieldedAddress(wallet.walletPath, network, shieldedAddress); + + // mn's reader replays the indexer's zswap events with the full secret + // keys (receives and spends) into a cache: ~50-70 s the first time on a + // hosted network, incremental after. The chain id drops the cache when + // the chain was reset. + await assertLedgerSupported(network, networkConfig, fetchProtocolVersion, signal); + // Null when the node can't say (the cache check is then skipped); a cancelled call stops here. + const chainId = (await getChainGenesisHash(networkConfig.node, signal)) ?? undefined; + const shieldedResult = await engine.readers.shieldedBalance(wallet.seed, network, networkConfig.indexerWS, { + root, + forceFresh, + chainId, + signal, + onProgress: (applied, highest) => steps.update(formatSyncStatus(eta.sample({ applied, highest, t: Date.now() }), 'Syncing shielded')), + }); + steps.done('Shielded ready'); + return { + network, + address, + shieldedAddress, + unshielded, + shielded: { night: shieldedResult.balance, availableCoins: shieldedResult.availableCoins, tokens: shieldedResult.tokens }, + }; + } finally { + stopListening(); + } + }); +} diff --git a/src/lib/wallet/dust.ts b/src/lib/wallet/dust.ts new file mode 100644 index 00000000..6a1607d7 --- /dev/null +++ b/src/lib/wallet/dust.ts @@ -0,0 +1,205 @@ +// A wallet's Dust: whether its NIGHT is registered to generate Dust and how +// much it has, registering it, and a snapshot of its Dust another wallet +// restores from instead of syncing it cold. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { type Receipt, RECEIPT_WAIT_MS, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { seedOf, type WalletSource } from '../seed-resolver.ts'; +import { networkChoiceOf, unshieldedAddressOf, type WalletCallOptions, type WalletOpened } from './wallet-call.ts'; + +/** A wallet's NIGHT coins by whether they generate Dust. */ +export interface DustRegistrationCounts { + readonly network: NetworkName; + /** Unspent NIGHT coins registered to generate Dust. */ + readonly registeredUtxos: number; + /** Unspent NIGHT coins not registered. */ + readonly unregisteredUtxos: number; +} + +/** A wallet none of whose NIGHT generates Dust: its Dust is not read. */ +export interface DustUnregistered extends DustRegistrationCounts { + readonly registered: false; +} + +/** A wallet with NIGHT that generates Dust, and the Dust it has. */ +export interface DustRegistered extends DustRegistrationCounts { + readonly registered: true; + /** Dust, in its smallest unit (specks). */ + readonly dust: bigint; + /** Dust coins that can pay a fee now. */ + readonly availableCoins: number; + /** The wallet's unspent NIGHT coins the Dust reader saw. */ + readonly ownedUtxos: number; + /** Dust events this read applied (0 when its cache was current). */ + readonly eventsApplied: number; + /** Whether a cache took part: the read resumed from it, or it was current. */ + readonly fromCache: boolean; +} + +export type DustStatus = DustUnregistered | DustRegistered; + +export interface ReadDustStatusOptions extends WalletCallOptions { + /** Read the Dust past every cache, from the indexer. */ + forceFresh?: boolean; +} + +/** + * Whether the wallet's NIGHT generates Dust, from the indexer; when some does, + * its Dust, from mn's reader of the indexer's events (through its cache). + */ +export async function readDustStatus(host: Host, source: WalletSource, options: ReadDustStatusOptions = {}): Promise { + const { signal, log, onProgress } = options; + throwIfCancelled(signal); + const { network, networkConfig, root } = networkTargetOf(host, networkChoiceOf(options)); + const wallet = await seedOf(host, source); + const address = await unshieldedAddressOf(wallet, network, host.engines); + const steps = progressSteps(onProgress); + onProgress?.({ kind: 'wallet-opened', network, address }); + + // Registration first, from the indexer's coins alone: a wallet with none registered has no Dust to read. + steps.start(`Checking registration on ${network}...`); + const { registeredUtxos, unregisteredUtxos } = await checkBalance(address, networkConfig.indexerWS, (current, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((current / highest) * 100), 100); + steps.update(pct >= 100 ? 'Checking registration...' : `Checking registration... ${pct}%`); + } + }, signal); + throwIfCancelled(signal); + steps.done('Registration checked'); + if (registeredUtxos === 0) return { network, registered: false, registeredUtxos, unregisteredUtxos }; + + // Read from the indexer directly: the Dust wallet SDK's sync can hang on `isConnected`. + steps.start(`Reading dust events from ${networkConfig.networkId.toLowerCase()}...`); + const view = await (await host.engines.for(network)).wallet.dustBalance(wallet.seed, networkConfig, { + root, + notice: host.notice, + forceFresh: options.forceFresh, + signal, + log, + onStatus: (message) => steps.update(message), + }); + steps.done(view.fromCache && view.eventsApplied === 0 ? 'Cache up to date' : 'Dust events applied'); + return { + network, + registered: true, + registeredUtxos, + unregisteredUtxos, + dust: view.balance, + availableCoins: view.availableCoins, + ownedUtxos: view.ownedUtxoCount, + eventsApplied: view.eventsApplied, + fromCache: view.fromCache, + }; +} + +/** What registering a wallet's NIGHT for Dust did. */ +export interface DustRegistrationResult { + readonly network: NetworkName; + /** The wallet had Dust already: nothing was registered or submitted. */ + readonly alreadyAvailable: boolean; + /** The wallet's Dust once synced, in its smallest unit (specks). */ + readonly dust: bigint; + /** The registration's identifier, when one was submitted. */ + readonly txHash?: string; + /** The submitted registration once the indexer lists it, or why it is missing; absent when none was submitted, or `receiptWaitMs` is 0. */ + readonly receipt?: Receipt; +} + +export interface RegisterDustOptions extends WalletCallOptions { + /** How long to wait for the indexer to list a submitted registration, in milliseconds: RECEIPT_WAIT_MS when not given; 0 does not wait. */ + receiptWaitMs?: number; +} + +/** + * Registers the wallet's NIGHT to generate Dust, unless it has Dust already: + * syncs the wallet (proof server, node and indexer), submits, and waits for + * the indexer to list the registration. + */ +export async function registerDust(host: Host, source: WalletSource, options: RegisterDustOptions = {}): Promise { + const { signal, log, onProgress } = options; + const receiptWaitMs = options.receiptWaitMs ?? RECEIPT_WAIT_MS; + throwIfCancelled(signal); + const { network, networkConfig, root } = networkTargetOf(host, networkChoiceOf(options)); + const wallet = await seedOf(host, source); + const address = await unshieldedAddressOf(wallet, network, host.engines); + const steps = progressSteps(onProgress); + onProgress?.({ kind: 'wallet-opened', network, address }); + + steps.start('Syncing wallet...'); + const result = await withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, async (sdkWarnings) => (await host.engines.for(network)).wallet.registerDust(wallet.seed, networkConfig, { + root, + notice: host.notice, + signal, + sdkWarnings, + log, + onStatus: (status) => steps.update(status), + onSyncProgress: (applied, highest) => { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + steps.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); + } + }, + onSyncDetail: (detail) => steps.update(`Syncing wallet... (waiting on: ${detail})`), + onSyncWarning: (_tag, message) => steps.update(`Syncing wallet... (${message}, retrying)`), + })); + let receipt: Receipt | undefined; + if (result.txHash && receiptWaitMs > 0) { + steps.update('Waiting for the indexer to list it...'); + receipt = await receiptOf(networkConfig.indexer, result.txHash, signal, receiptWaitMs); + } + steps.done(result.alreadyAvailable ? 'Dust already available' : 'Dust registration complete'); + return { + network, + alreadyAvailable: result.alreadyAvailable, + dust: result.dustBalance, + ...(result.txHash ? { txHash: result.txHash } : {}), + ...(receipt === undefined ? {} : { receipt }), + }; +} + +/** + * The wallet's Dust as a snapshot the wallet SDK restores from (its + * `dustSerializedState`), read fast from the indexer's events through mn's + * cache. A partial snapshot stopped short of the chain's tip: still a valid + * checkpoint, but a wallet restored from it has events left to catch up on. + */ +export async function exportDustSnapshot(host: Host, source: WalletSource, options: WalletCallOptions = {}): Promise { + const { signal, log } = options; + throwIfCancelled(signal); + const { network, networkConfig, root } = networkTargetOf(host, networkChoiceOf(options)); + const steps = progressSteps(options.onProgress); + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, async (sdkWarnings) => { + // The chain-id check connects to the node; keep polkadot-js's RPC-CORE noise off the terminal. + const stopListening = sdkWarnings.listen(undefined); + try { + const wallet = await seedOf(host, source); + steps.start(`Reading dust events from ${network}...`); + const result = await (await host.engines.for(network)).wallet.exportDust(wallet.seed, network, networkConfig, { + root, + notice: host.notice, + signal, + log, + onProgress: (applied, maxIdSeen) => steps.update( + maxIdSeen > 0 + ? `Reading dust events... ${applied}/${maxIdSeen + 1}` + : `Reading dust events... ${applied}`, + ), + }); + steps.done( + result.partial + ? 'Dust snapshot ready (incomplete)' + : result.fromCache && result.eventCount === 0 ? 'Cache up to date' : 'Dust snapshot ready', + ); + return result; + } finally { + stopListening(); + } + }); +} diff --git a/src/lib/wallet/wallet-call.ts b/src/lib/wallet/wallet-call.ts new file mode 100644 index 00000000..635cbd4b --- /dev/null +++ b/src/lib/wallet/wallet-call.ts @@ -0,0 +1,42 @@ +// What every wallet operation of src/lib/wallet takes besides its own inputs, +// what it says once its wallet is open, and the wallet's address it acts on. + +import type { NetworkChoice } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { ResolvedSeed } from '../seed-resolver.ts'; + +/** The network, the endpoints and what a call gives a wallet operation; `Event` is what it says beyond its steps. */ +export interface WalletCallOptions extends NetworkChoice { + /** Cancels the operation: a call cancelled already starts nothing; one cancelled later stops with CancelledError. */ + signal?: AbortSignal; + /** Each step, in today's words for a person, and the operation's own events. */ + onProgress?: (event: ProgressEvent | Event) => void; + /** Diagnostic lines, as --verbose shows them. */ + log?: VerboseLog; + /** The call's SDK warnings, kept off the terminal while the SDK runs; a call of the host's own when not given. */ + sdkWarnings?: CallSdkWarnings; +} + +/** The operation's wallet is open and its work on the chain starts. */ +export interface WalletOpened { + readonly kind: 'wallet-opened'; + readonly network: NetworkName; + /** The wallet's unshielded address on the network. */ + readonly address: string; + /** Its shielded address on the network, when the wallet file has it saved. */ + readonly shieldedAddress?: string; +} + +/** The network's pick of the endpoints `options` gives. */ +export function networkChoiceOf(options: NetworkChoice): NetworkChoice { + return { network: options.network, node: options.node, indexerWS: options.indexerWS, proofServer: options.proofServer }; +} + +/** The wallet's unshielded address on `network`: the one its file saved, else derived from its seed. */ +export async function unshieldedAddressOf(wallet: ResolvedSeed, network: NetworkName, engines: HostEngines): Promise { + return wallet.config?.addresses[network] ?? (await engines.for(network)).keys.unshieldedAddress(wallet.seed, network); +} From 89018667504298c7715beba543493658b0eb0a2f Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 14:46:25 -0800 Subject: [PATCH 68/88] Library functions for transfer and airdrop; exact amounts (3E, 4-5 of 8) transferNight and airdropNight in src/lib/wallet/ do what the transfer and airdrop commands did, with plain values, a progress callback and the receipt; the handlers only parse, call and print. transferNight keeps the domain's rule itself: a shielded transfer on preview, preprod or stagenet is refused unless forced, before the wallet unlocks (one check, shared with the CLI and MCP confirmation). Amounts are exact bigints end to end (Y58): parseAmount reads the decimal into the smallest unit without a JS number, and the engine contract's transfer and airdrop amounts are bigint in both engines. An amount that was refused as too many digits to handle exactly is now taken exactly (grant deposit too). The --json amount stays a number, as before. Suite 2838, beta 184; snapshot unchanged; fresh install; scratch chain swap 30/30 and tx 25/25 (transfers and airdrops, shielded and not, with receipts), after the scratch node was restarted when Docker's disk filled. --- packages/cli-core/api-report.md | 6 +- packages/cli-core/src/lib/amount.ts | 42 ++- packages/cli-core/src/lib/engine.ts | 3 +- packages/engine-beta/src/airdrop.ts | 2 +- packages/engine-beta/src/transfer.ts | 10 +- packages/engine-rc/src/airdrop.ts | 2 +- packages/engine-rc/src/transfer.ts | 10 +- src/__tests__/engine-beta-transfer.test.ts | 6 + src/__tests__/engine-transfer.test.ts | 6 + .../helpers/engine-transfer-suite.ts | 86 +++++ src/__tests__/helpers/stand-in-indexer.ts | 37 ++ src/__tests__/transfer-lib.test.ts | 44 ++- src/__tests__/transfer-request.test.ts | 2 +- src/__tests__/wallet-airdrop-lib.test.ts | 148 ++++++++ src/__tests__/wallet-transfer-lib.test.ts | 163 +++++++++ src/commands/airdrop.ts | 329 +++--------------- src/commands/transfer.ts | 211 +++-------- src/lib/dev/provision-wallets.ts | 3 +- src/lib/grant/request.ts | 4 +- src/lib/test/prep-runner.ts | 3 +- src/lib/transfer-request.ts | 16 +- src/lib/wallet/airdrop.ts | 201 +++++++++++ src/lib/wallet/submit-steps.ts | 42 +++ src/lib/wallet/transfer.ts | 127 +++++++ 24 files changed, 1000 insertions(+), 503 deletions(-) create mode 100644 src/__tests__/engine-beta-transfer.test.ts create mode 100644 src/__tests__/engine-transfer.test.ts create mode 100644 src/__tests__/helpers/engine-transfer-suite.ts create mode 100644 src/__tests__/wallet-airdrop-lib.test.ts create mode 100644 src/__tests__/wallet-transfer-lib.test.ts create mode 100644 src/lib/wallet/airdrop.ts create mode 100644 src/lib/wallet/submit-steps.ts create mode 100644 src/lib/wallet/transfer.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index b124243a..9c26e65c 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -305,7 +305,9 @@ export declare function codeGuidancePieces(codes: readonly CodeDefinition[]): Gu ```ts export declare function nightToMicro(amountNight: number): bigint; -export declare function parseAmount(amountStr: string): number; +export declare function parseAmount(amountStr: string): bigint; +export declare function nightAmountText(micro: bigint): string; +export declare function nightAmountJson(micro: bigint): number; ``` ## `@kuiralabs/midnight-cli-core/lib/approval` @@ -1033,7 +1035,7 @@ export interface TransferParams { seedBuffer: Buffer; networkConfig: NetworkConfig; recipientAddress: string; - amountNight: number; + amount: bigint; signal?: AbortSignal; onSync?: (applied: number, highest: number) => void; onSyncDetail?: (walletsStillSyncing: string) => void; diff --git a/packages/cli-core/src/lib/amount.ts b/packages/cli-core/src/lib/amount.ts index 97c8ae04..899977b7 100644 --- a/packages/cli-core/src/lib/amount.ts +++ b/packages/cli-core/src/lib/amount.ts @@ -4,10 +4,11 @@ import { UsageError } from './errors.ts'; /** NIGHT's smallest unit is 10^-6 NIGHT. */ const NIGHT_DECIMALS = 6; +const MICRO_PER_NIGHT = 10n ** BigInt(NIGHT_DECIMALS); /** - * Convert NIGHT amount to micro-NIGHT (bigint). - * Rounds to 6 decimals: amounts from parseAmount never need rounding (it refuses those that would). + * Convert NIGHT amount to micro-NIGHT (bigint), for amounts mn's own code + * holds as numbers (a default, a count from a config). Rounds to 6 decimals. */ export function nightToMicro(amountNight: number): bigint { if (amountNight <= 0) { @@ -29,9 +30,10 @@ export function nightToMicro(amountNight: number): bigint { /** * Parse and validate amount string from CLI input: a plain decimal with at - * most 6 decimals, which a number carries exactly. Returns it in NIGHT. + * most 6 decimals. Returns it exactly, in micro-NIGHT: the digits are read as + * an integer, never through a number, so no amount loses its last digits. */ -export function parseAmount(amountStr: string): number { +export function parseAmount(amountStr: string): bigint { const text = amountStr.trim(); const match = /^(\d*)(?:\.(\d*))?$/.exec(text); if (!match || (match[1] === '' && !match[2])) { @@ -41,14 +43,30 @@ export function parseAmount(amountStr: string): number { if (decimals.length > NIGHT_DECIMALS) { throw new UsageError(`Invalid amount: "${amountStr}" — NIGHT has ${NIGHT_DECIMALS} decimals, this has ${decimals.length}`); } - const amount = Number(text); - if (amount <= 0) { + const micro = BigInt((match[1] || '0') + decimals.padEnd(NIGHT_DECIMALS, '0')); + if (micro <= 0n) { throw new UsageError(`Invalid amount: "${amountStr}" — must be greater than 0`); } - // Amounts travel as numbers; refuse one a number can't carry to the exact smallest unit. - const exact = BigInt((match[1] || '0') + decimals.padEnd(NIGHT_DECIMALS, '0')); - if (nightToMicro(amount) !== exact) { - throw new UsageError(`Invalid amount: "${amountStr}" — too many digits to handle exactly`); - } - return amount; + return micro; +} + +/** + * An amount of micro-NIGHT in NIGHT, as a person writes it: no trailing zeros + * and no point for a whole amount (1500000n is "1.5", 100000000n is "100"). + * The words mn prints for an amount it was given. + */ +export function nightAmountText(micro: bigint): string { + const sign = micro < 0n ? '-' : ''; + const abs = micro < 0n ? -micro : micro; + const fraction = (abs % MICRO_PER_NIGHT).toString().padStart(NIGHT_DECIMALS, '0').replace(/0+$/, ''); + return `${sign}${abs / MICRO_PER_NIGHT}${fraction ? `.${fraction}` : ''}`; +} + +/** + * An amount of micro-NIGHT as a command's `--json` output carries it: a JSON + * number of NIGHT. Exact to the smallest unit up to 2^53 micro-NIGHT (about + * 9e9 NIGHT); past that, the nearest number. + */ +export function nightAmountJson(micro: bigint): number { + return Number(nightAmountText(micro)); } diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index 0bc7bac9..ad0c80a9 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -201,7 +201,8 @@ export interface TransferParams { seedBuffer: Buffer; networkConfig: NetworkConfig; recipientAddress: string; - amountNight: number; + /** In NIGHT's smallest unit; more than 0. */ + amount: bigint; signal?: AbortSignal; onSync?: (applied: number, highest: number) => void; onSyncDetail?: (walletsStillSyncing: string) => void; diff --git a/packages/engine-beta/src/airdrop.ts b/packages/engine-beta/src/airdrop.ts index d153734e..e8944c0d 100644 --- a/packages/engine-beta/src/airdrop.ts +++ b/packages/engine-beta/src/airdrop.ts @@ -11,7 +11,7 @@ import type { WalletDataRepository } from './wallet-data-repository.ts'; export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; -/** Sends `amountNight` NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ +/** Sends `amount` micro-NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ export async function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise { try { return await executeTransfer(repo, { ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index d7196d92..dd097580 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -12,7 +12,7 @@ import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; import { NATIVE_TOKEN_TYPE, TOKEN_MULTIPLIER, @@ -425,7 +425,7 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf seedBuffer, networkConfig, recipientAddress, - amountNight, + amount, signal, onSync, onSyncDetail, @@ -440,7 +440,9 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf notice, } = params; - const amount = nightToMicro(amountNight); + if (amount <= 0n) { + throw new Error('Amount must be greater than 0'); + } const decodedAddress = validateRecipientAddress(recipientAddress, networkConfig); // Suppress SDK transient errors + polkadot-js RPC noise for the duration @@ -462,7 +464,7 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER; throw new InsufficientBalanceError( `Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + - `${amountNight} NIGHT requested` + `${nightAmountText(amount)} NIGHT requested` ); } diff --git a/packages/engine-rc/src/airdrop.ts b/packages/engine-rc/src/airdrop.ts index d153734e..e8944c0d 100644 --- a/packages/engine-rc/src/airdrop.ts +++ b/packages/engine-rc/src/airdrop.ts @@ -11,7 +11,7 @@ import type { WalletDataRepository } from './wallet-data-repository.ts'; export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; -/** Sends `amountNight` NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ +/** Sends `amount` micro-NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ export async function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise { try { return await executeTransfer(repo, { ...params, seedBuffer: Buffer.from(GENESIS_SEED, 'hex') }); diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index abe10525..a038ae52 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -12,7 +12,7 @@ import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; import type { WalletDataRepository } from './wallet-data-repository.ts'; import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; import { NATIVE_TOKEN_TYPE, TOKEN_MULTIPLIER, @@ -424,7 +424,7 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf seedBuffer, networkConfig, recipientAddress, - amountNight, + amount, signal, onSync, onSyncDetail, @@ -439,7 +439,9 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf notice, } = params; - const amount = nightToMicro(amountNight); + if (amount <= 0n) { + throw new Error('Amount must be greater than 0'); + } const decodedAddress = validateRecipientAddress(recipientAddress, networkConfig); // Suppress SDK transient errors + polkadot-js RPC noise for the duration @@ -461,7 +463,7 @@ export async function executeTransfer(repo: WalletDataRepository, params: Transf const haveNight = Number(unshieldedBalance) / TOKEN_MULTIPLIER; throw new InsufficientBalanceError( `Insufficient balance: ${haveNight.toFixed(6)} NIGHT available, ` + - `${amountNight} NIGHT requested` + `${nightAmountText(amount)} NIGHT requested` ); } diff --git a/src/__tests__/engine-beta-transfer.test.ts b/src/__tests__/engine-beta-transfer.test.ts new file mode 100644 index 00000000..983b79fc --- /dev/null +++ b/src/__tests__/engine-beta-transfer.test.ts @@ -0,0 +1,6 @@ +// The beta engine's transfer amounts: helpers/engine-transfer-suite.ts. + +import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; +import { engineTransferSuite } from './helpers/engine-transfer-suite.ts'; + +engineTransferSuite({ set: 'beta', createEngine: createBetaEngine }); diff --git a/src/__tests__/engine-transfer.test.ts b/src/__tests__/engine-transfer.test.ts new file mode 100644 index 00000000..f8df85ea --- /dev/null +++ b/src/__tests__/engine-transfer.test.ts @@ -0,0 +1,6 @@ +// The rc engine's transfer amounts: helpers/engine-transfer-suite.ts. + +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { engineTransferSuite } from './helpers/engine-transfer-suite.ts'; + +engineTransferSuite({ set: 'rc', createEngine: createRcEngine }); diff --git a/src/__tests__/helpers/engine-transfer-suite.ts b/src/__tests__/helpers/engine-transfer-suite.ts new file mode 100644 index 00000000..b3e1cf5e --- /dev/null +++ b/src/__tests__/helpers/engine-transfer-suite.ts @@ -0,0 +1,86 @@ +// What an engine's transfers take: amounts of NIGHT as bigint in its smallest +// unit, refused when not above 0 before anything reaches the chain, and +// carried whole past what a JS number holds (2^53 micro-NIGHT) to where the +// wallet first asks the chain, the repository's protocol-version read, which a +// test stands in for with a ledger-8 chain so the call stops there. A +// submitted transfer needs a chain: the scratch chain's live runs cover it. +// +// This file loads no engine: each test file that runs it passes one. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { Engine, EngineHost, TransferParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; + +/** What the suite takes from an engine: how to make it with its repository's protocol-version read. */ +export interface TransferEngine { + set: string; + createEngine(host: EngineHost, options: { repository: { fetchProtocolVersion: (indexerHttpUrl: string) => Promise } }): Engine; +} + +const NETWORK: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', node: 'ws://test/node', proofServer: 'http://test/proof', networkId: 'Undeployed' }; +const SEED = Buffer.alloc(32, 9); +// 9007199254.740993 NIGHT: one micro-NIGHT past what a JS number carries exactly. +const LARGE = 2n ** 53n + 1n; +// The protocol version of a ledger-8 chain, below the ledger-9 fork. +const LEDGER_8 = 1_000_000n; + +export function engineTransferSuite(engine: TransferEngine): void { + describe(`the ${engine.set} engine's transfer amounts`, () => { + let root: string; + beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'mn-engine-transfer-')); }); + afterAll(() => { rmSync(root, { recursive: true, force: true }); }); + + /** An engine whose chain is on ledger 8, and the indexers it asked for the chain's version. */ + function onLedger8() { + const asked: string[] = []; + const host = createHost({ paths: { stateRoot: root, home: root } }); + const made = engine.createEngine(host, { repository: { fetchProtocolVersion: async (url) => { asked.push(url); return LEDGER_8; } } }); + return { host, wallet: made.wallet, recipient: made.keys.unshieldedAddress(Buffer.alloc(32, 3), 'undeployed'), shieldedRecipient: made.keys.shieldedAddress(Buffer.alloc(32, 3), 'undeployed'), asked }; + } + + /** What `transfer` and `airdrop` take, but the amount. */ + const paramsOf = (host: EngineHost, recipientAddress: string) => (amount: bigint, run: (params: TransferParams) => Promise) => + withCallSdkWarnings(createHost().sdkWarnings, undefined, (sdkWarnings) => run({ seedBuffer: SEED, networkConfig: NETWORK, recipientAddress, amount, sdkWarnings, root, notice: host.notice })); + + it.each([0n, -1n])('refuses %s NIGHT to transfer or airdrop before it asks the chain', async (amount) => { + const { host, wallet, recipient, asked } = onLedger8(); + const call = paramsOf(host, recipient); + await expect(call(amount, (params) => wallet.transfer(params))).rejects.toThrow('Amount must be greater than 0'); + await expect(call(amount, ({ seedBuffer: _genesisPays, ...params }) => wallet.airdrop(params))).rejects.toThrow('Amount must be greater than 0'); + expect(asked).toEqual([]); + }); + + it('carries an amount past what a number holds to the chain: transfer, airdrop and a shielded transfer', async () => { + const { host, wallet, recipient, shieldedRecipient, asked } = onLedger8(); + const call = paramsOf(host, recipient); + await expect(call(LARGE, (params) => wallet.transfer(params))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + await expect(call(LARGE, ({ seedBuffer: _genesisPays, ...params }) => wallet.airdrop(params))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + await expect(wallet.shieldedTransfer({ + seed: SEED, + root, + notice: host.notice, + network: 'undeployed', + networkConfig: NETWORK, + recipient: shieldedRecipient, + amount: LARGE, + progress: silentSpinner(), + insufficient: (available) => `${available} NIGHT available`, + waitForDustToCover: false, + })).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + expect(asked).toEqual([NETWORK.indexer, NETWORK.indexer, NETWORK.indexer]); + }); + + it('refuses a recipient of another network before it asks the chain', async () => { + const { host, wallet, asked } = onLedger8(); + const preprod = engine.createEngine(host, { repository: { fetchProtocolVersion: async () => LEDGER_8 } }).keys.unshieldedAddress(Buffer.alloc(32, 3), 'preprod'); + await expect(paramsOf(host, preprod)(1_000_000n, (params) => wallet.transfer(params))).rejects.toThrow('Expected a bech32m address for network "Undeployed"'); + expect(asked).toEqual([]); + }); + }); +} diff --git a/src/__tests__/helpers/stand-in-indexer.ts b/src/__tests__/helpers/stand-in-indexer.ts index 8633697c..b00bb413 100644 --- a/src/__tests__/helpers/stand-in-indexer.ts +++ b/src/__tests__/helpers/stand-in-indexer.ts @@ -7,8 +7,12 @@ // creating one NIGHT UTXO, `delayMs` apart. // - An endpoint that refuses every connection: it listens (so no other test // can take its port) and drops each connection at once. +// - An indexer of a ledger-8 chain: its HTTP GraphQL endpoint answers every +// query with a protocol version below the ledger-9 fork, which mn refuses +// before a wallet syncs (lib/ledger-guard.ts). import { createServer, type Server, type Socket } from 'node:net'; +import { createServer as createHttpServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { WebSocketServer, type WebSocket } from 'ws'; import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -111,3 +115,36 @@ export async function startRefusingEndpoint(): Promise<{ readonly port: number; }), }; } + +/** A ledger-8 chain's indexer, as its HTTP GraphQL endpoint answers. */ +export interface Ledger8Indexer { + /** Its WebSocket URL, as `--indexer-ws` takes it; mn reads the HTTP endpoint beside it. */ + readonly url: string; + /** The queries it was asked, in order. */ + readonly queries: string[]; + close(): Promise; +} + +/** An indexer whose chain is on ledger 8 (protocol version 1000000): every query is answered with that block. */ +export async function startLedger8Indexer(): Promise { + const queries: string[] = []; + const server = createHttpServer((req, res) => { + let body = ''; + req.on('data', (chunk) => { body += chunk; }); + req.on('end', () => { + queries.push((JSON.parse(body) as { query: string }).query); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ data: { block: { protocolVersion: 1_000_000 } } })); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `ws://127.0.0.1:${port}/api/v4/graphql/ws`, + queries, + close: () => new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} diff --git a/src/__tests__/transfer-lib.test.ts b/src/__tests__/transfer-lib.test.ts index 76ba823b..fadd92d1 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/src/__tests__/transfer-lib.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import { validateRecipientAddress, isDustRelatedError } from '@kuiralabs/midnight-engine-rc/transfer'; -import { nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { nightAmountJson, nightAmountText, nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -54,28 +54,34 @@ describe('parseAmount: exact amounts only (NIGHT has 6 decimals)', () => { expect(() => parseAmount(input)).toThrow(`Invalid amount: "${input}" — must be a positive number, e.g. 1.5`); }); - it('refuses an amount a number cannot carry to the exact smallest unit', () => { - expect(() => parseAmount('24000000000.000001')).toThrow('too many digits to handle exactly'); + it.each([ + ['1.000001', 1_000_001n], ['.5', 500_000n], ['1.', 1_000_000n], [' 2 ', 2_000_000n], ['007', 7_000_000n], ['999999999.999999', 999_999_999_999_999n], + ] as const)('accepts %j as exactly %s micro-NIGHT', (input, micro) => { + expect(parseAmount(input)).toBe(micro); }); + // A JS number carries 2^53 (about 9.007e15 micro-NIGHT, 9.007e9 NIGHT) exactly; the digits are read as an integer instead. it.each([ - ['1.000001', 1_000_001n], ['.5', 500_000n], ['1.', 1_000_000n], [' 2 ', 2_000_000n], ['999999999.999999', 999_999_999_999_999n], - ] as const)('accepts %j as exactly %s micro-NIGHT', (input, micro) => { - expect(nightToMicro(parseAmount(input))).toBe(micro); + ['24000000000.000001', 24_000_000_000_000_001n], + ['9007199254.740993', 9_007_199_254_740_993n], + ['123456789012345678.123456', 123_456_789_012_345_678_123_456n], + ] as const)('accepts %j, above what a number carries, as exactly %s micro-NIGHT', (input, micro) => { + expect(parseAmount(input)).toBe(micro); + expect(nightAmountText(parseAmount(input))).toBe(input); }); }); describe('parseAmount', () => { it('parses integer amounts', () => { - expect(parseAmount('100')).toBe(100); - expect(parseAmount('1')).toBe(1); - expect(parseAmount('1000000')).toBe(1_000_000); + expect(parseAmount('100')).toBe(100_000_000n); + expect(parseAmount('1')).toBe(1_000_000n); + expect(parseAmount('1000000')).toBe(1_000_000_000_000n); }); it('parses decimal amounts', () => { - expect(parseAmount('0.5')).toBe(0.5); - expect(parseAmount('1.23')).toBe(1.23); - expect(parseAmount('0.000001')).toBe(0.000001); + expect(parseAmount('0.5')).toBe(500_000n); + expect(parseAmount('1.23')).toBe(1_230_000n); + expect(parseAmount('0.000001')).toBe(1n); }); it('throws for non-numeric strings', () => { @@ -106,6 +112,20 @@ describe('parseAmount', () => { }); }); +describe('nightAmountText and nightAmountJson: an amount as mn prints it', () => { + // The words the commands printed when amounts were numbers, String(Number(text)), for amounts a number carried exactly (all parseAmount took then). + it.each(['100', '1.5', '0.5', '0.000001', '1.000001', '123.45', '999999999.999999', '4000000000.000001', '8000000000.000011', '7', '0.1'])('%s as written, and as the number --json has always carried', (text) => { + expect(nightAmountText(parseAmount(text))).toBe(String(Number(text))); + expect(nightAmountJson(parseAmount(text))).toBe(Number(text)); + }); + + it('drops trailing zeros and a bare point, as a number did', () => { + expect(nightAmountText(parseAmount('1.50'))).toBe('1.5'); + expect(nightAmountText(parseAmount('2.'))).toBe('2'); + expect(nightAmountText(parseAmount('.25'))).toBe('0.25'); + }); +}); + describe('validateRecipientAddress', () => { const genesisSeed = Buffer.from(GENESIS_SEED, 'hex'); diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index db52cec9..7d9a0436 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -57,7 +57,7 @@ afterEach(() => { describe('resolveTransferRequest', () => { it('takes an address and an amount, on the network asked for', async () => { const r = await request(RECIPIENT.preprod, '1.5', '--wallet', 'sender', '--network', 'preprod'); - expect(r).toMatchObject({ recipientAddress: RECIPIENT.preprod, amountNight: 1.5, shielded: false, networkName: 'preprod' }); + expect(r).toMatchObject({ recipientAddress: RECIPIENT.preprod, amount: 1_500_000n, shielded: false, networkName: 'preprod' }); expect(r.walletPath).toBe(path.join(WALLETS, 'sender.json')); // The request is checked without the passphrase: it carries the wallet's addresses, never its seed. expect(r.walletConfig).not.toHaveProperty('seed'); diff --git a/src/__tests__/wallet-airdrop-lib.test.ts b/src/__tests__/wallet-airdrop-lib.test.ts new file mode 100644 index 00000000..71868085 --- /dev/null +++ b/src/__tests__/wallet-airdrop-lib.test.ts @@ -0,0 +1,148 @@ +// airdropNight, called as a program calls it: a host of its own (a temporary +// state root, its settings given, never the environment), plain values in, +// typed results and codes out, no argv and no call context. The indexer is a +// stand-in for a ledger-8 chain's (stand-in-indexer.ts), which mn refuses +// where the genesis wallet first reaches the chain; the node and proof server +// an endpoint that refuses every connection. A submitted airdrop and its +// receipt need a chain: the scratch chain's live runs cover them. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; +import { airdropNight, type AirdropAddressed, type AirdropNightOptions } from '../lib/wallet/airdrop.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from './helpers/stand-in-indexer.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const SEED = Buffer.from('a7'.repeat(32), 'hex'); +const ADDRESS = deriveAllAddresses(SEED); +const SHIELDED = deriveAllShieldedAddresses(SEED); +// Above what a JS number carries exactly (2^53 micro-NIGHT): 9007199254.740993 NIGHT. +const LARGE = 9_007_199_254_740_993n; + +let home: string; +let indexer: Ledger8Indexer; +let refusing: { port: number; close(): Promise }; + +beforeEach(async () => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-airdrop-lib-'))); + indexer = await startLedger8Indexer(); + refusing = await startRefusingEndpoint(); +}); + +afterEach(async () => { + await indexer.close(); + await refusing.close(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A program's host: its own state root under the test's folder, its passphrase in its settings, and a prompter that counts what it is asked. */ +function programHost(name: string): Host & { asked: () => number } { + let asked = 0; + const prompter: Prompter = { isInteractive: () => true, ask: async () => { asked += 1; return null; }, askSecret: async () => { asked += 1; return PASSPHRASE; } }; + const host = createHost({ + paths: { stateRoot: path.join(home, name, '.midnight'), home: path.join(home, name) }, + settings: settingsFromEnvironment({ [PASSPHRASE_ENV]: PASSPHRASE }), + prompter, + engineLoader: loadInstalledEngine, + }); + return Object.assign(host, { asked: () => asked }); +} + +/** Writes the seed's wallet as `alice` under the host's state root, and makes it the active one. */ +function aliceOf(host: Host): void { + const root = host.paths().stateRoot; + saveWalletConfig({ seed: SEED.toString('hex'), addresses: ADDRESS, shieldedAddresses: SHIELDED, createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); +} + +const endpoints = () => ({ + network: 'undeployed' as const, + indexerWS: indexer.url, + node: `ws://127.0.0.1:${refusing.port}`, + proofServer: `http://127.0.0.1:${refusing.port}`, +}); + +type Said = ProgressEvent | AirdropAddressed; + +function airdrop(extra: Partial = {}): AirdropNightOptions { + return { ...endpoints(), to: {}, amount: LARGE, ...extra }; +} + +describe('airdropNight', () => { + it('funds the active wallet at its address: says where, its first step, and fails with UNSUPPORTED_LEDGER on a ledger-8 chain', async () => { + const host = programHost('a'); + aliceOf(host); + const said: Said[] = []; + + await expect(airdropNight(host, airdrop({ onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + + expect(said[0]).toEqual({ kind: 'airdrop-addressed', network: 'undeployed', recipient: ADDRESS.undeployed, shielded: false }); + expect(said[1]).toEqual({ kind: 'start', message: 'Starting genesis wallet...' }); + expect(said.filter((event) => event.kind === 'done')).toEqual([]); + expect(indexer.queries).toEqual(['{ block { protocolVersion } }']); + expect(host.asked()).toBe(0); + }); + + it('a shielded address makes the airdrop shielded, with no wallet file', async () => { + const said: Said[] = []; + await expect(airdropNight(programHost('a'), airdrop({ to: { address: SHIELDED.undeployed }, onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + expect(said[0]).toEqual({ kind: 'airdrop-addressed', network: 'undeployed', recipient: SHIELDED.undeployed, shielded: true }); + expect(said[1]).toEqual({ kind: 'start', message: 'Syncing genesis wallet...' }); + }); + + it('a shielded airdrop to a wallet goes to the shielded address its file keeps', async () => { + const host = programHost('a'); + aliceOf(host); + const said: Said[] = []; + await expect(airdropNight(host, airdrop({ to: { wallet: 'alice' }, shielded: true, onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + expect(said[0]).toEqual({ kind: 'airdrop-addressed', network: 'undeployed', recipient: SHIELDED.undeployed, shielded: true }); + }); + + it.each([ + ['another network', { network: 'preprod' as const }, 'Airdrop is only available on the "undeployed" network (local devnet).\nCurrent network: "preprod"'], + ['shielded to an unshielded address', { to: { address: ADDRESS.undeployed }, shielded: true }, '--shielded was passed but --wallet is an unshielded address.'], + ['an address of another network', { to: { address: ADDRESS.preprod } }, 'Address does not match network "undeployed".\nExpected prefix: mn_addr_undeployed1'], + ['a malformed shielded address', { to: { address: 'mn_shield-addr_undeployed1nope' } }, 'Invalid shielded address: '], + ])('refuses %s before the genesis wallet starts, saying nothing', async (_case, extra, message) => { + const said: Said[] = []; + await expect(airdropNight(programHost('a'), airdrop({ ...extra, onProgress: (event) => said.push(event) }))).rejects.toThrow(message); + expect(said).toEqual([]); + expect(indexer.queries).toEqual([]); + }); + + it('refuses a wallet that is not there with WALLET_NOT_FOUND, and an amount of 0 with INVALID_ARGS', async () => { + await expect(airdropNight(programHost('a'), airdrop({ to: { wallet: 'nobody' } }))).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + await expect(airdropNight(programHost('a'), airdrop({ to: { address: ADDRESS.undeployed }, amount: 0n }))).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + }); + + it('cancelled already: CancelledError, and nothing asked or said', async () => { + const host = programHost('a'); + aliceOf(host); + const said: Said[] = []; + await expect(airdropNight(host, airdrop({ signal: AbortSignal.abort(), onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(said).toEqual([]); + expect(indexer.queries).toEqual([]); + }); + + it('cancelled once the recipient is known: CancelledError, and nothing more said', async () => { + const controller = new AbortController(); + const said: Said[] = []; + const onProgress = (event: Said) => { + said.push(event); + if (event.kind === 'airdrop-addressed') controller.abort(); + }; + await expect(airdropNight(programHost('a'), airdrop({ to: { address: ADDRESS.undeployed }, signal: controller.signal, onProgress }))).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(said.map((event) => event.kind)).toEqual(['airdrop-addressed', 'start']); + expect(indexer.queries).toEqual([]); + }); +}); diff --git a/src/__tests__/wallet-transfer-lib.test.ts b/src/__tests__/wallet-transfer-lib.test.ts new file mode 100644 index 00000000..bef081fe --- /dev/null +++ b/src/__tests__/wallet-transfer-lib.test.ts @@ -0,0 +1,163 @@ +// transferNight, called as a program calls it: a host of its own (a temporary +// state root, its settings given, never the environment), plain values in, +// typed results and codes out, no argv and no call context. The indexer is a +// stand-in for a ledger-8 chain's (stand-in-indexer.ts), which mn refuses +// where the wallet first reaches the chain; the node and proof server an +// endpoint that refuses every connection. A submitted transfer and its receipt +// need a chain: the scratch chain's live runs cover them. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { deriveAllAddresses, deriveAllShieldedAddresses, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; +import { transferNight, type TransferNightOptions } from '../lib/wallet/transfer.ts'; +import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from './helpers/stand-in-indexer.ts'; + +const PASSPHRASE = 'correct horse battery staple'; +const SEED_A = 'e5'.repeat(32); +const RECIPIENT_SEED = Buffer.from('f6'.repeat(32), 'hex'); +const RECIPIENT = deriveAllAddresses(RECIPIENT_SEED).undeployed; +const RECIPIENT_SHIELDED = deriveAllShieldedAddresses(RECIPIENT_SEED).undeployed; +// Above what a JS number carries exactly (2^53 micro-NIGHT): 9007199254.740993 NIGHT. +const LARGE = 9_007_199_254_740_993n; + +let home: string; +let indexer: Ledger8Indexer; +let refusing: { port: number; close(): Promise }; + +beforeEach(async () => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-transfer-lib-'))); + indexer = await startLedger8Indexer(); + refusing = await startRefusingEndpoint(); +}); + +afterEach(async () => { + await indexer.close(); + await refusing.close(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A program's host: its own state root under the test's folder, its passphrase in its settings, and a prompter that counts what it is asked. */ +function programHost(name: string): Host & { asked: () => number } { + let asked = 0; + const prompter: Prompter = { isInteractive: () => true, ask: async () => { asked += 1; return null; }, askSecret: async () => { asked += 1; return PASSPHRASE; } }; + const host = createHost({ + paths: { stateRoot: path.join(home, name, '.midnight'), home: path.join(home, name) }, + settings: settingsFromEnvironment({ [PASSPHRASE_ENV]: PASSPHRASE }), + prompter, + engineLoader: loadInstalledEngine, + }); + return Object.assign(host, { asked: () => asked }); +} + +/** Writes `seed`'s wallet as `alice` under the host's state root, and makes it the active one; returns its file. */ +function aliceOf(host: Host, seed: string): string { + const root = host.paths().stateRoot; + const file = path.join(root, 'wallets', 'alice.json'); + saveWalletConfig({ seed, addresses: deriveAllAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, file); + saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); + return file; +} + +const endpoints = () => ({ + network: 'undeployed' as const, + indexerWS: indexer.url, + node: `ws://127.0.0.1:${refusing.port}`, + proofServer: `http://127.0.0.1:${refusing.port}`, +}); + +type Said = ProgressEvent | WalletOpened; + +function transfer(extra: Partial = {}): TransferNightOptions { + return { ...endpoints(), recipient: RECIPIENT, amount: LARGE, ...extra }; +} + +describe('transferNight', () => { + it('opens the wallet, says its first step, and fails with UNSUPPORTED_LEDGER on a ledger-8 chain, before the wallet syncs', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: Said[] = []; + + await expect(transferNight(host, { wallet: 'alice' }, transfer({ onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + + expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address: deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed') }); + expect(said[1]).toEqual({ kind: 'start', message: 'Starting wallet...' }); + expect(said.filter((event) => event.kind === 'done')).toEqual([]); + expect(indexer.queries).toEqual(['{ block { protocolVersion } }']); + }); + + it('a shielded transfer from a seed the program holds says it syncs, and fails with UNSUPPORTED_LEDGER on a ledger-8 chain', async () => { + const seed = Buffer.from(SEED_A, 'hex'); + const said: Said[] = []; + await expect(transferNight(programHost('a'), { seed }, transfer({ recipient: RECIPIENT_SHIELDED, shielded: true, onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address: deriveUnshieldedAddress(seed, 'undeployed') }); + expect(said[1]).toEqual({ kind: 'start', message: 'Syncing wallet...' }); + }); + + it('refuses a wallet that is not there with WALLET_NOT_FOUND, a seed of the wrong size and an amount of 0 with INVALID_ARGS, saying nothing', async () => { + const said: Said[] = []; + const onProgress = (event: Said) => said.push(event); + await expect(transferNight(programHost('a'), { wallet: 'nobody' }, transfer({ onProgress }))).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + await expect(transferNight(programHost('a'), { seed: new Uint8Array(31) }, transfer({ onProgress }))).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + await expect(transferNight(programHost('a'), { seed: Buffer.from(SEED_A, 'hex') }, transfer({ amount: 0n, onProgress }))).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + expect(said).toEqual([]); + }); + + it('refuses a shielded transfer where the network has no shielded faucet with INVALID_ARGS, before the wallet unlocks, unless forced', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: Said[] = []; + const preprod = { ...transfer({ recipient: deriveAllShieldedAddresses(RECIPIENT_SEED).preprod, shielded: true }), network: 'preprod' as const, onProgress: (event: Said) => said.push(event) }; + const refused = transferNight(host, { wallet: 'alice' }, preprod); + await expect(refused).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + await expect(refused).rejects.toThrow('Shielded is unavailable on preprod (no faucet). Use --force-shielded to sync anyway, or --network undeployed.'); + expect(host.asked()).toBe(0); + expect(said).toEqual([]); + expect(indexer.queries).toEqual([]); + + // Forced, it goes on to the chain (the stand-in's ledger 8 stops it there). + await expect(transferNight(host, { wallet: 'alice' }, { ...preprod, forceShielded: true })).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); + expect(said[0]).toMatchObject({ kind: 'wallet-opened', network: 'preprod' }); + }); + + it('refuses a network that is not one, naming the networks, before the wallet unlocks', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + await expect(transferNight(host, { wallet: 'alice' }, transfer({ network: 'moonnet' as never }))).rejects.toThrow('Invalid network: "moonnet"'); + expect(host.asked()).toBe(0); + }); + + it('cancelled already: CancelledError, and no wallet unlocked, nothing asked or said', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const said: Said[] = []; + await expect(transferNight(host, { wallet: 'alice' }, transfer({ signal: AbortSignal.abort(), onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(host.asked()).toBe(0); + expect(said).toEqual([]); + expect(indexer.queries).toEqual([]); + }); + + it('cancelled once the wallet is open: CancelledError, and nothing more said', async () => { + const host = programHost('a'); + aliceOf(host, SEED_A); + const controller = new AbortController(); + const said: Said[] = []; + const onProgress = (event: Said) => { + said.push(event); + if (event.kind === 'wallet-opened') controller.abort(); + }; + await expect(transferNight(host, { wallet: 'alice' }, transfer({ signal: controller.signal, onProgress }))).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(said.map((event) => event.kind)).toEqual(['wallet-opened', 'start']); + expect(indexer.queries).toEqual([]); + }); +}); diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index bb78250a..73905f93 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -9,18 +9,16 @@ // file required, useful for funding externally-generated addresses. // A shielded address implies --shielded; the flag is optional there. -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAddress, type UnlockHost } from '../lib/wallet-config.ts'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { applyEndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { parseAmount, nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { nightAmountJson, nightAmountText, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { airdropNight, type AirdropAddressed, type AirdropRecipient, type NightAirdrop } from '../lib/wallet/airdrop.ts'; import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; import { receiptText } from '../ui/receipt.ts'; export default async function airdropCommand(args: ParsedArgs, ctx: CallContext): Promise { @@ -36,293 +34,62 @@ export default async function airdropCommand(args: ParsedArgs, ctx: CallContext) ); } - const amountNight = parseAmount(amountStr); - const root = ctx.config.paths.stateRoot; - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); - - applyEndpointOverrides(networkConfig, { - proofServer: getFlag(args, 'proof-server'), - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - }, networkName, root); - - if (networkName !== 'undeployed') { - throw new Error( - `Airdrop is only available on the "undeployed" network (local devnet).\n` + - `Current network: "${networkName}"\n` + - `On preprod/preview, use a faucet or transfer from another wallet.` - ); - } - - // A shielded address prefix is unambiguous — infer --shielded instead of - // making the user repeat what the address already says. The reverse - // (--shielded with an unshielded address) stays an error: that's a real - // contradiction, resolved in resolveAddressDestination. - const walletFlag = getFlag(args, 'wallet'); - const isShielded = hasFlag(args, 'shielded') || - (walletFlag !== undefined && walletFlag.startsWith('mn_shield-addr_')); - const destination = await resolveDestination(args, root, networkName, networkConfig, isShielded, ctx.host); - - if (isShielded) { - return shieldedAirdrop(args, destination as ShieldedDestination, amountNight, networkName, networkConfig, ctx); - } - - return unshieldedAirdrop(args, destination as UnshieldedDestination, amountNight, networkName, networkConfig, ctx); -} - -// ── Destination resolution ── -// -// `--wallet` accepts a name, a file path, or a raw bech32m address. -// Resolution is uniform for the entry point; the helpers receive a -// pre-resolved destination so they don't reach back into wallet files -// when funding an external address. - -type UnshieldedDestination = { kind: 'address'; address: string }; - -type ShieldedDestination = - | { kind: 'address'; bech32m: string } - | { kind: 'wallet'; bech32m: string; walletPath: string }; - -function looksLikeBech32mAddress(value: string): boolean { - return value.startsWith('mn_addr_') || value.startsWith('mn_shield-addr_'); -} - -async function resolveDestination( - args: ParsedArgs, - root: string, - networkName: NetworkName, - networkConfig: NetworkConfig, - isShielded: boolean, - host: UnlockHost, -): Promise { - const walletFlag = getFlag(args, 'wallet'); - - if (walletFlag !== undefined && looksLikeBech32mAddress(walletFlag)) { - return resolveAddressDestination(walletFlag, host.engines, networkName, isShielded); - } - - // Fall back to wallet file (name, path, or active wallet) - const walletPath = resolveWalletPath(root, walletFlag); - - if (isShielded) { - // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase - // (unless the network was added after the wallet was written). - const stored = await walletShieldedAddress(walletPath, networkName, root, host); - if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${networkName}.`); - const decoded = await resolveAddressDestination(stored, host.engines, networkName, true) as ShieldedDestination; - return { kind: 'wallet', bech32m: decoded.bech32m, walletPath }; - } - - return { kind: 'address', address: await walletAddress(walletPath, networkName, root, host) }; -} - -async function resolveAddressDestination( - address: string, - engines: HostEngines, - networkName: NetworkName, - isShielded: boolean, -): Promise { - const looksShielded = address.startsWith('mn_shield-addr_'); - - // The inverse mismatch (shielded address without --shielded) never - // reaches here: the entry point infers --shielded from the prefix. - if (isShielded && !looksShielded) { - throw new Error( - `--shielded was passed but --wallet is an unshielded address.\n` + - `Pass a shielded address (mn_shield-addr_...) or drop --shielded.\n` + - `Got: ${address}` - ); - } - - const expectedPrefix = isShielded - ? `mn_shield-addr_${networkName}1` - : `mn_addr_${networkName}1`; - - if (!address.startsWith(expectedPrefix)) { - throw new Error( - `Address does not match network "${networkName}".\n` + - `Expected prefix: ${expectedPrefix}\n` + - `Got: ${address}` - ); - } - - if (isShielded) { - try { - (await engines.for(networkName)).keys.assertAddress(address, 'shielded', networkName); - } catch (err: any) { - throw new Error(`Invalid shielded address: ${err.message}`); - } - return { kind: 'address', bech32m: address }; - } - - return { kind: 'address', address }; -} - -// ── Unshielded airdrop (existing flow) ── - -async function unshieldedAirdrop( - args: ParsedArgs, - destination: UnshieldedDestination, - amountNight: number, - networkName: NetworkName, - networkConfig: NetworkConfig, - ctx: CallContext, -): Promise { - const recipientAddress = destination.address; - - ctx.output.stderr('\n' + header('Airdrop') + '\n\n'); - ctx.output.stderr(keyValue('Network', networkName) + '\n'); - ctx.output.stderr(keyValue('From', dim('genesis (seed 0x01)')) + '\n'); - ctx.output.stderr(keyValue('To', formatAddress(recipientAddress, true)) + '\n'); - ctx.output.stderr(keyValue('Amount', bold(amountNight + ' NIGHT')) + '\n'); - ctx.output.stderr('\n'); - - const spinner = ctx.progress.start('Starting genesis wallet...'); - + const amount = parseAmount(amountStr); + const progress = spinnerReporter(ctx.progress, false); try { - const result = await (await ctx.host.engines.for(networkName)).wallet.airdrop({ - root: ctx.config.paths.stateRoot, - notice: ctx.host.notice, - networkConfig, - recipientAddress, - amountNight, + const result = await airdropNight(ctx.host, { + ...networkChoiceFromArgs(args), + to: recipientOf(getFlag(args, 'wallet')), + amount, + shielded: hasFlag(args, 'shielded'), signal: ctx.signal, log: ctx.diagnostics.line, sdkWarnings: ctx.sdkWarnings, - onSync(applied, highest) { - if (highest > 0) { - const pct = Math.round((applied / highest) * 100); - spinner.update(`Syncing genesis wallet... ${pct}%`); - } - }, - onDust(status) { - spinner.update(`Dust: ${status}`); - }, - onProving() { - spinner.update('Generating ZK proof (this may take a few minutes)...'); - }, - onSubmitting() { - spinner.update('Submitting and waiting for finalization (typically 12 to 30s)...'); - }, - onSubmittingTick(elapsedMs: number) { - const s = Math.floor(elapsedMs / 1000); - const mm = Math.floor(s / 60).toString().padStart(2, '0'); - const ss = (s % 60).toString().padStart(2, '0'); - spinner.update(`Submitting and waiting for finalization... ${mm}:${ss} elapsed (typically 12 to 30s)`); - }, - onSyncWarning(_tag, msg) { - spinner.update(`Syncing genesis wallet... (${msg}, retrying)`); - }, + onProgress: (event) => (event.kind === 'airdrop-addressed' ? printHeading(event, amount, ctx) : progress.report(event)), }); - - spinner.update('Waiting for the indexer to list it...'); - const receipt = await receiptOf(networkConfig.indexer, result.txHash, ctx.signal); - spinner.stop('Transaction submitted'); - - if (hasFlag(args, 'json')) { - ctx.output.result({ - txHash: result.txHash, - amount: amountNight, - recipient: recipientAddress, - network: networkName, - ...receiptJson(receipt), - }); - return; - } - - ctx.output.stdout(result.txHash + '\n'); - - ctx.output.stderr('\n' + successMessage( - `Airdropped ${amountNight} NIGHT to your wallet`, - result.txHash, - ) + '\n'); - ctx.output.stderr(receiptText(receipt, result.txHash)); - ctx.output.stderr('\n' + divider() + '\n'); - ctx.output.stderr(dim(' Verify: midnight balance') + '\n'); - ctx.output.stderr(dim(' Register dust: midnight dust register') + '\n'); - ctx.output.stderr(dim(' Note: registering pays its fee from Dust this NIGHT generates, so it waits longer the less NIGHT') - + '\n' + dim(' there is (about a minute for 1000 NIGHT). dust register says how long.') + '\n\n'); + printAirdrop(result, amount, hasFlag(args, 'json'), ctx); } catch (err) { - spinner.fail('Failed'); + progress.fail('Failed'); throw err; } } -// ── Shielded airdrop (genesis shielded → user shielded) ── - -async function shieldedAirdrop( - args: ParsedArgs, - destination: ShieldedDestination, - amountNight: number, - networkName: NetworkName, - networkConfig: NetworkConfig, - ctx: CallContext, -): Promise { - const amount = nightToMicro(amountNight); - - const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); - - const userShieldedAddrStr = destination.bech32m; - // Cache the shielded address into the wallet file so subsequent reads - // can short-circuit. Only meaningful when the destination came from a - // managed wallet — for a raw address there's nothing to cache. - if (destination.kind === 'wallet') { - saveShieldedAddress(destination.walletPath, networkName, userShieldedAddrStr); - } +/** `--wallet`: a bech32m address is funded as given; anything else names a wallet file (absent: the active wallet). */ +function recipientOf(walletFlag: string | undefined): AirdropRecipient { + return walletFlag !== undefined && (walletFlag.startsWith('mn_addr_') || walletFlag.startsWith('mn_shield-addr_')) + ? { address: walletFlag } + : { wallet: walletFlag }; +} - ctx.output.stderr('\n' + header('Shielded Airdrop') + '\n\n'); - ctx.output.stderr(keyValue('Network', networkName) + '\n'); - ctx.output.stderr(keyValue('From', dim('genesis shielded (seed 0x01)')) + '\n'); - ctx.output.stderr(keyValue('To', formatAddress(userShieldedAddrStr, true)) + '\n'); - ctx.output.stderr(keyValue('Amount', bold(amountNight + ' NIGHT (shielded)')) + '\n'); +/** Heads the output once the recipient is known, before the genesis wallet syncs. */ +function printHeading({ network, recipient, shielded }: AirdropAddressed, amount: bigint, ctx: CallContext): void { + ctx.output.stderr('\n' + header(shielded ? 'Shielded Airdrop' : 'Airdrop') + '\n\n'); + ctx.output.stderr(keyValue('Network', network) + '\n'); + ctx.output.stderr(keyValue('From', dim(shielded ? 'genesis shielded (seed 0x01)' : 'genesis (seed 0x01)')) + '\n'); + ctx.output.stderr(keyValue('To', formatAddress(recipient, true)) + '\n'); + ctx.output.stderr(keyValue('Amount', bold(nightAmountText(amount) + (shielded ? ' NIGHT (shielded)' : ' NIGHT'))) + '\n'); ctx.output.stderr('\n'); +} - // Keep the SDK's transient errors and RPC noise off the terminal while this runs. - const stopListening = ctx.sdkWarnings.listen(undefined); - const spinner = ctx.progress.start('Syncing genesis wallet...'); - - try { - const txHash = await (await ctx.host.engines.for(networkName)).wallet.shieldedTransfer({ - seed: genesisSeedBuffer, - root: ctx.config.paths.stateRoot, - notice: ctx.host.notice, - network: networkName, - networkConfig, - recipient: userShieldedAddrStr, - amount, - progress: spinner, - waitForDustToCover: false, - insufficient: (available) => - `Genesis wallet has insufficient shielded balance: ${available} NIGHT available, ${amountNight} NIGHT requested`, - log: ctx.diagnostics.line, - signal: ctx.signal, - onStatus: (s) => spinner.update(s), - onSyncProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing genesis wallet...' : `Syncing genesis wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => spinner.update(`Syncing genesis wallet... (waiting on: ${detail})`), - }); - - spinner.update('Waiting for the indexer to list it...'); - const receipt = await receiptOf(networkConfig.indexer, txHash, ctx.signal); - spinner.stop('Transaction submitted'); +function printAirdrop({ network, txHash, recipient, shielded, receipt }: NightAirdrop, amount: bigint, jsonMode: boolean, ctx: CallContext): void { + const receiptFields = receipt ? receiptJson(receipt) : {}; + if (jsonMode) { + ctx.output.result(shielded + ? { txHash, amount: nightAmountJson(amount), shieldedAddress: recipient, network, type: 'shielded', ...receiptFields } + : { txHash, amount: nightAmountJson(amount), recipient, network, ...receiptFields }); + return; + } - if (hasFlag(args, 'json')) { - ctx.output.result({ txHash, amount: amountNight, shieldedAddress: userShieldedAddrStr, network: networkName, type: 'shielded', ...receiptJson(receipt) }); - return; - } - ctx.output.stdout(txHash + '\n'); - ctx.output.stderr('\n' + successMessage(`Airdropped ${amountNight} shielded NIGHT to your wallet`, txHash) + '\n'); - ctx.output.stderr(receiptText(receipt, txHash)); - ctx.output.stderr('\n' + divider() + '\n'); + ctx.output.stdout(txHash + '\n'); + ctx.output.stderr('\n' + successMessage(`Airdropped ${nightAmountText(amount)} ${shielded ? 'shielded NIGHT' : 'NIGHT'} to your wallet`, txHash) + '\n'); + if (receipt) ctx.output.stderr(receiptText(receipt, txHash)); + ctx.output.stderr('\n' + divider() + '\n'); + if (shielded) { ctx.output.stderr(dim(' Verify: midnight balance --shielded') + '\n\n'); - } catch (err) { - spinner.fail('Failed'); - throw err; - } finally { - stopListening(); + return; } + ctx.output.stderr(dim(' Verify: midnight balance') + '\n'); + ctx.output.stderr(dim(' Register dust: midnight dust register') + '\n'); + ctx.output.stderr(dim(' Note: registering pays its fee from Dust this NIGHT generates, so it waits longer the less NIGHT') + + '\n' + dim(' there is (about a minute for 1000 NIGHT). dust register says how long.') + '\n\n'); } diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index ef8995a6..da0acdb0 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -1,200 +1,69 @@ // transfer command — send NIGHT from my wallet to another address // Usage: midnight transfer [--shielded] -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { saveShieldedAddress, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; +import { type ParsedArgs, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { nightAmountJson, nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; import { resolveTransferRequest, type TransferRequest } from '../lib/transfer-request.ts'; -import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { transferNight, type NightTransfer } from '../lib/wallet/transfer.ts'; +import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { receiptJson, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; import { receiptText } from '../ui/receipt.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); const request = await resolveTransferRequest(args, ctx.config.paths.stateRoot, ctx.host); - return request.shielded ? shieldedTransfer(args, request, ctx) : unshieldedTransfer(args, request, ctx); -} - -// ── Unshielded transfer (existing flow) ── - -async function unshieldedTransfer( - args: ParsedArgs, - { walletPath, walletConfig: config, recipientAddress, amountNight }: TransferRequest, - ctx: CallContext, -): Promise { - const root = ctx.config.paths.stateRoot; - const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root, host: ctx.host })).seed, 'hex'); - - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); - const address = config.addresses[networkName]; - - applyEndpointOverrides(networkConfig, { - proofServer: getFlag(args, 'proof-server'), - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - }, networkName, root); - - ctx.output.stderr('\n' + header('Transfer') + '\n\n'); - ctx.output.stderr(keyValue('Network', networkName) + '\n'); - ctx.output.stderr(keyValue('From', formatAddress(address, true)) + '\n'); - ctx.output.stderr(keyValue('To', formatAddress(recipientAddress, true)) + '\n'); - ctx.output.stderr(keyValue('Amount', bold(amountNight + ' NIGHT')) + '\n'); - ctx.output.stderr('\n'); - - const spinner = ctx.progress.start('Starting wallet...'); - + const progress = spinnerReporter(ctx.progress, false); try { - const result = await (await ctx.host.engines.for(networkName)).wallet.transfer({ - root, - notice: ctx.host.notice, - seedBuffer, - networkConfig, - recipientAddress, - amountNight, + const result = await transferNight(ctx.host, { wallet: request.walletPath }, { + ...networkChoiceFromArgs(args), + recipient: request.recipientAddress, + amount: request.amount, + shielded: request.shielded, + forceShielded: hasFlag(args, 'force-shielded'), signal: ctx.signal, log: ctx.diagnostics.line, sdkWarnings: ctx.sdkWarnings, - onSync(applied, highest) { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); - } - }, - onSyncDetail(detail) { - spinner.update(`Syncing wallet... (waiting on: ${detail})`); - }, - onDust(status) { - spinner.update(`Dust: ${status}`); - }, - onProving() { - spinner.update('Generating ZK proof (this may take a few minutes)...'); - }, - onSubmitting() { - spinner.update('Submitting and waiting for finalization (typically 12 to 30s)...'); - }, - onSubmittingTick(elapsedMs: number) { - const s = Math.floor(elapsedMs / 1000); - const mm = Math.floor(s / 60).toString().padStart(2, '0'); - const ss = (s % 60).toString().padStart(2, '0'); - spinner.update(`Submitting and waiting for finalization... ${mm}:${ss} elapsed (typically 12 to 30s)`); - }, - onSyncWarning(_tag, msg) { - spinner.update(`Syncing wallet... (${msg}, retrying)`); - }, + onProgress: (event) => (event.kind === 'wallet-opened' ? printHeading(event, request, ctx) : progress.report(event)), }); - - spinner.update('Waiting for the indexer to list it...'); - const receipt = await receiptOf(networkConfig.indexer, result.txHash, ctx.signal); - spinner.stop('Transaction submitted'); - - if (hasFlag(args, 'json')) { - ctx.output.result({ - txHash: result.txHash, - amount: amountNight, - recipient: recipientAddress, - network: networkName, - ...receiptJson(receipt), - }); - return; - } - - ctx.output.stdout(result.txHash + '\n'); - - ctx.output.stderr('\n' + successMessage( - `Transferred ${amountNight} NIGHT`, - result.txHash, - ) + '\n'); - ctx.output.stderr(receiptText(receipt, result.txHash)); - ctx.output.stderr('\n' + divider() + '\n'); - ctx.output.stderr(dim(' Verify: midnight balance') + '\n\n'); + printTransfer(result, request, hasFlag(args, 'json'), ctx); } catch (err) { - spinner.fail('Failed'); + progress.fail('Failed'); throw err; } } -// ── Shielded transfer ── - -async function shieldedTransfer( - args: ParsedArgs, - { walletPath, walletConfig: config, recipientAddress, amountNight }: TransferRequest, - ctx: CallContext, -): Promise { - const amount = nightToMicro(amountNight); - const root = ctx.config.paths.stateRoot; - const seedBuffer = Buffer.from((await unlockWallet(walletPath, { root, host: ctx.host })).seed, 'hex'); - - const { name: networkName, config: networkConfig } = resolveNetwork({ args, configDir: root }, ctx.config.settings); - - applyEndpointOverrides(networkConfig, { - proofServer: getFlag(args, 'proof-server'), - node: getFlag(args, 'node'), - indexerWS: getFlag(args, 'indexer-ws'), - }, networkName, root); - - ctx.output.stderr('\n' + header('Shielded Transfer') + '\n\n'); - ctx.output.stderr(keyValue('Network', networkName) + '\n'); +/** Heads the output once the wallet is open: what goes where, before the wallet syncs. */ +function printHeading(opened: WalletOpened, { recipientAddress, amount, shielded }: TransferRequest, ctx: CallContext): void { + const text = nightAmountText(amount); + ctx.output.stderr('\n' + header(shielded ? 'Shielded Transfer' : 'Transfer') + '\n\n'); + ctx.output.stderr(keyValue('Network', opened.network) + '\n'); + if (!shielded) ctx.output.stderr(keyValue('From', formatAddress(opened.address, true)) + '\n'); ctx.output.stderr(keyValue('To', formatAddress(recipientAddress, true)) + '\n'); - ctx.output.stderr(keyValue('Amount', bold(amountNight + ' NIGHT (shielded)')) + '\n'); + ctx.output.stderr(keyValue('Amount', bold(text + (shielded ? ' NIGHT (shielded)' : ' NIGHT'))) + '\n'); ctx.output.stderr('\n'); +} - - // Keep the SDK's transient errors and RPC noise off the terminal while this runs. - const stopListening = ctx.sdkWarnings.listen(undefined); - const spinner = ctx.progress.start('Syncing wallet...'); - - try { - const txHash = await (await ctx.host.engines.for(networkName)).wallet.shieldedTransfer({ - seed: seedBuffer, - root, - notice: ctx.host.notice, - network: networkName, - networkConfig, +function printTransfer({ network, txHash, receipt }: NightTransfer, { recipientAddress, amount, shielded }: TransferRequest, jsonMode: boolean, ctx: CallContext): void { + if (jsonMode) { + ctx.output.result({ + txHash, + amount: nightAmountJson(amount), recipient: recipientAddress, - amount, - progress: spinner, - // Right after another payment the wallet's Dust can be short of this - // fee: wait when the rest is moments away, else say how long it takes. - waitForDustToCover: true, - // Cache shielded address in wallet file - onSenderShieldedAddress: (address) => saveShieldedAddress(walletPath, networkName, address), - insufficient: (available) => - `Insufficient shielded balance: ${available} NIGHT available, ${amountNight} NIGHT requested.\n` + - `Fund shielded balance: midnight airdrop ${amountNight} --shielded`, - log: ctx.diagnostics.line, - signal: ctx.signal, - onStatus: (s) => spinner.update(s), - onSyncProgress: (applied, highest) => { - if (highest > 0) { - const pct = Math.min(Math.round((applied / highest) * 100), 100); - spinner.update(pct >= 100 ? 'Syncing wallet...' : `Syncing wallet... ${pct}%`); - } - }, - onSyncDetail: (detail) => spinner.update(`Syncing wallet... (waiting on: ${detail})`), + network, + ...(shielded ? { type: 'shielded' } : {}), + ...(receipt ? receiptJson(receipt) : {}), }); - - spinner.update('Waiting for the indexer to list it...'); - const receipt = await receiptOf(networkConfig.indexer, txHash, ctx.signal); - spinner.stop('Transaction submitted'); - - if (hasFlag(args, 'json')) { - ctx.output.result({ txHash, amount: amountNight, recipient: recipientAddress, network: networkName, type: 'shielded', ...receiptJson(receipt) }); - return; - } - ctx.output.stdout(txHash + '\n'); - ctx.output.stderr('\n' + successMessage(`Transferred ${amountNight} shielded NIGHT`, txHash) + '\n'); - ctx.output.stderr(receiptText(receipt, txHash)); - ctx.output.stderr('\n' + divider() + '\n'); - ctx.output.stderr(dim(' Verify: midnight balance --shielded') + '\n\n'); - } catch (err) { - spinner.fail('Failed'); - throw err; - } finally { - stopListening(); + return; } + + ctx.output.stdout(txHash + '\n'); + ctx.output.stderr('\n' + successMessage(`Transferred ${nightAmountText(amount)} ${shielded ? 'shielded NIGHT' : 'NIGHT'}`, txHash) + '\n'); + if (receipt) ctx.output.stderr(receiptText(receipt, txHash)); + ctx.output.stderr('\n' + divider() + '\n'); + ctx.output.stderr(dim(shielded ? ' Verify: midnight balance --shielded' : ' Verify: midnight balance') + '\n\n'); } diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 84765424..569082a0 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -13,6 +13,7 @@ import { resolveNetwork, type NetworkSettings } from '@kuiralabs/midnight-cli-co import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; /** Default dev wallet names — one per common test persona. */ export const DEFAULT_DEV_WALLET_NAMES = ['dev-alice', 'dev-bob', 'dev-carol'] as const; @@ -157,7 +158,7 @@ async function generateWallet(root: string, host: UnlockHost, name: string, sign async function airdropToWallet(root: string, host: UnlockHost, network: NetworkConfig, name: string, amountNight: number, signal: AbortSignal | undefined, sdkWarnings: CallSdkWarnings): Promise { const recipientAddress = (await loadWalletConfig(resolveWalletPath(root, name), host.engines)).addresses.undeployed; // dev's wallets live on the local chain. - await (await host.engines.load(sdkSetOf('undeployed', root))).wallet.airdrop({ networkConfig: network, recipientAddress, amountNight, signal, sdkWarnings, root, notice: host.notice }); + await (await host.engines.load(sdkSetOf('undeployed', root))).wallet.airdrop({ networkConfig: network, recipientAddress, amount: nightToMicro(amountNight), signal, sdkWarnings, root, notice: host.notice }); } async function walletNeedsDust(root: string, host: UnlockHost, network: NetworkConfig, name: string, signal: AbortSignal | undefined): Promise { diff --git a/src/lib/grant/request.ts b/src/lib/grant/request.ts index 4b52ae96..21a60eef 100644 --- a/src/lib/grant/request.ts +++ b/src/lib/grant/request.ts @@ -5,7 +5,7 @@ import { parseDeviceCode } from './device-code.ts'; import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; export const GRANT_SUBCOMMANDS = ['deploy', 'deposit', 'status', 'list', 'issue', 'revoke', 'revoke-all', 'export', 'import', 'device'] as const; @@ -95,7 +95,7 @@ export function resolveGrantRequest(args: ParsedArgs): GrantRequest { case 'deposit': { const [amount] = positionalsFor(args, subcommand, 1, 'one amount of NIGHT'); if (amount === undefined) throw new UsageError('Missing the amount of NIGHT to deposit.\nUsage: midnight grant deposit '); - return { subcommand, amount, value: nightToMicro(parseAmount(amount)).toString() }; + return { subcommand, amount, value: parseAmount(amount).toString() }; } case 'status': case 'list': diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index 6e40f34a..e1cd03bf 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -14,6 +14,7 @@ import { OWN_COMMAND_DUST_WAIT_MS } from '@kuiralabs/midnight-cli-core/lib/dust- import { startBuild } from './build-manager.ts'; import { DustRequiredError, InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; /** A prep step failed: the step's own error is its cause, and its code (DUST_REQUIRED, …) is this one's. */ export class PrepStepFailedError extends Error { @@ -159,7 +160,7 @@ async function stepBalance(amount: number, config: DappTestConfig, ctx: PrepCont await engine.wallet.airdrop({ networkConfig, recipientAddress: address, - amountNight: amount, + amount: nightToMicro(amount), onSync(_applied, _highest) {}, onDust(status) { callbacks.onMessage(`Dust: ${status}`); }, onProving() { callbacks.onMessage('Generating ZK proof...'); }, diff --git a/src/lib/transfer-request.ts b/src/lib/transfer-request.ts index 0b594714..b25c2489 100644 --- a/src/lib/transfer-request.ts +++ b/src/lib/transfer-request.ts @@ -7,8 +7,8 @@ import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { loadWalletConfig, resolveWalletPath, walletAddress, walletShieldedAddress, type UnlockHost, type WalletConfig } from './wallet-config.ts'; import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { sdkSetOf, type EngineKeys } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; import { parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { assertShieldedTransferAllowed } from './wallet/transfer.ts'; import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; export interface TransferRequest { @@ -17,7 +17,8 @@ export interface TransferRequest { networkName: NetworkName; /** The recipient's bech32m address; a wallet name given as the recipient is resolved to it. */ recipientAddress: string; - amountNight: number; + /** In NIGHT's smallest unit, exactly as written. */ + amount: bigint; shielded: boolean; } @@ -45,19 +46,16 @@ export async function resolveTransferRequest(args: ParsedArgs, root: string, hos const shielded = hasFlag(args, 'shielded'); const recipientAddress = await resolveRecipient(recipientInput, args, shielded, root, host); - const amountNight = parseAmount(amountStr); + const amount = parseAmount(amountStr); const walletPath = resolveWalletPath(root, getFlag(args, 'wallet')); const walletConfig = await loadWalletConfig(walletPath, host.engines); const networkName = resolveNetworkName({ args, configDir: root }); - if (shielded) { - if (!shieldedSyncEnabled(networkName, hasFlag(args, 'force-shielded'))) { - throw new UsageError(shieldedDisabledReason(networkName)); - } - } + // transferNight refuses it too; refused here before the wallet is opened, and before MCP issues a confirmation. + if (shielded) assertShieldedTransferAllowed(networkName, hasFlag(args, 'force-shielded')); assertRecipient((await host.engines.load(sdkSetOf(networkName, root))).keys, recipientAddress, shielded, networkName); - return { walletPath, walletConfig, networkName, recipientAddress, amountNight, shielded }; + return { walletPath, walletConfig, networkName, recipientAddress, amount, shielded }; } /** Refuses, as a usage mistake, a recipient that is not an address of that kind on the network. */ diff --git a/src/lib/wallet/airdrop.ts b/src/lib/wallet/airdrop.ts new file mode 100644 index 00000000..419a9ce7 --- /dev/null +++ b/src/lib/wallet/airdrop.ts @@ -0,0 +1,201 @@ +// Funding a wallet or an address from the genesis wallet (seed 0x01) of a +// local devnet: unshielded NIGHT from its unshielded coins, or shielded NIGHT +// from its shielded ones. Only the undeployed network has such a wallet; on +// preprod and preview a faucet or another wallet funds one. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { type Receipt, RECEIPT_WAIT_MS } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { resolveWalletPath, saveShieldedAddress, walletAddress, walletShieldedAddress, type UnlockHost } from '../wallet-config.ts'; +import { receiptOfSubmitted, saySyncPercent, submitSteps } from './submit-steps.ts'; +import { networkChoiceOf, type WalletCallOptions } from './wallet-call.ts'; + +/** + * Who an airdrop funds: a wallet by name or path (absent: the active one), at + * its own address on the network; or an address (mn_addr_…, or + * mn_shield-addr_…, which makes the airdrop shielded), no wallet file needed. + */ +export type AirdropRecipient = { wallet?: string } | { address: string }; + +/** The airdrop's recipient is resolved, and its work on the chain starts. */ +export interface AirdropAddressed { + readonly kind: 'airdrop-addressed'; + readonly network: NetworkName; + /** The address it funds: shielded when the airdrop is. */ + readonly recipient: string; + readonly shielded: boolean; +} + +export interface AirdropNightOptions extends WalletCallOptions { + to: AirdropRecipient; + /** NIGHT to send, in its smallest unit; more than 0. */ + amount: bigint; + /** Send shielded NIGHT, to the wallet's shielded address (implied by a shielded address in `to`). */ + shielded?: boolean; + /** How long to wait for the indexer to list the transaction, in milliseconds: RECEIPT_WAIT_MS when not given; 0 does not wait. */ + receiptWaitMs?: number; +} + +/** A submitted airdrop. */ +export interface NightAirdrop { + readonly network: NetworkName; + /** The transaction's identifier (`midnight tx status` takes it). */ + readonly txHash: string; + /** The address it funded: shielded when the airdrop was. */ + readonly recipient: string; + readonly shielded: boolean; + /** The transaction once the indexer lists it, or why it is missing; absent when `receiptWaitMs` is 0. */ + readonly receipt?: Receipt; +} + +/** + * Sends `amount` NIGHT from the local devnet's genesis wallet to `to`: syncs + * the genesis wallet, submits, and waits for the indexer to list the + * transaction. Refused on any network but undeployed. A wallet file given a + * shielded airdrop keeps its shielded address. + */ +export async function airdropNight(host: Host, options: AirdropNightOptions): Promise { + const { signal, onProgress, amount } = options; + const receiptWaitMs = options.receiptWaitMs ?? RECEIPT_WAIT_MS; + throwIfCancelled(signal); + if (amount <= 0n) throw new UsageError(`Invalid amount: ${nightAmountText(amount)} NIGHT — must be greater than 0`); + const { network, networkConfig, root } = networkTargetOf(host, networkChoiceOf(options)); + + if (network !== 'undeployed') { + throw new Error( + `Airdrop is only available on the "undeployed" network (local devnet).\n` + + `Current network: "${network}"\n` + + `On preprod/preview, use a faucet or transfer from another wallet.` + ); + } + + // A shielded address prefix is unambiguous: it makes the airdrop shielded + // without being asked twice. The reverse (shielded with an unshielded + // address) is a real contradiction, refused in addressDestination. + const shielded = options.shielded === true || ('address' in options.to && options.to.address.startsWith('mn_shield-addr_')); + const destination = await resolveDestination(host, root, network, options.to, shielded); + // A wallet file keeps the shielded address it is funded at, so later reads skip deriving it. + if (destination.walletPath !== undefined) saveShieldedAddress(destination.walletPath, network, destination.address); + const recipient = destination.address; + onProgress?.({ kind: 'airdrop-addressed', network, recipient, shielded }); + + const steps = progressSteps(onProgress); + const text = nightAmountText(amount); + const txHash = await withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, async (sdkWarnings) => { + if (!shielded) { + steps.start('Starting genesis wallet...'); + return (await (await host.engines.for(network)).wallet.airdrop({ + root, + notice: host.notice, + networkConfig, + recipientAddress: recipient, + amount, + signal, + log: options.log, + sdkWarnings, + onSync: (applied, highest) => { + if (highest > 0) steps.update(`Syncing genesis wallet... ${Math.round((applied / highest) * 100)}%`); + }, + onDust: (status) => steps.update(`Dust: ${status}`), + ...submitSteps(steps), + onSyncWarning: (_tag, message) => steps.update(`Syncing genesis wallet... (${message}, retrying)`), + })).txHash; + } + + // Keep the SDK's transient errors and RPC noise off the terminal while this runs. + const stopListening = sdkWarnings.listen(undefined); + try { + steps.start('Syncing genesis wallet...'); + return await (await host.engines.for(network)).wallet.shieldedTransfer({ + seed: Buffer.from(GENESIS_SEED, 'hex'), + root, + notice: host.notice, + network, + networkConfig, + recipient, + amount, + progress: silentSpinner(steps.update), + waitForDustToCover: false, + insufficient: (available) => + `Genesis wallet has insufficient shielded balance: ${available} NIGHT available, ${text} NIGHT requested`, + log: options.log, + signal, + onStatus: (status) => steps.update(status), + onSyncProgress: (applied, highest) => saySyncPercent(steps, 'Syncing genesis wallet', applied, highest), + onSyncDetail: (detail) => steps.update(`Syncing genesis wallet... (waiting on: ${detail})`), + }); + } finally { + stopListening(); + } + }); + + const receipt = await receiptOfSubmitted(networkConfig.indexer, txHash, steps, signal, receiptWaitMs); + return { network, txHash, recipient, shielded, ...(receipt === undefined ? {} : { receipt }) }; +} + +/** Where an airdrop goes: its address, and the wallet file to keep it when it is a wallet's shielded address. */ +interface Destination { + readonly address: string; + readonly walletPath?: string; +} + +async function resolveDestination(host: UnlockHost, root: string, network: NetworkName, to: AirdropRecipient, shielded: boolean): Promise { + if ('address' in to) return { address: await addressDestination(to.address, host.engines, network, shielded) }; + + // A wallet file: by name, by path, or the active one. + const walletPath = resolveWalletPath(root, to.wallet); + + if (shielded) { + // The wallet's own shielded address, as its file keeps it: receiving needs no passphrase + // (unless the network was added after the wallet was written). + const stored = await walletShieldedAddress(walletPath, network, root, host); + if (stored === undefined) throw new Error(`Wallet ${walletPath} keeps no shielded address for ${network}.`); + return { address: await addressDestination(stored, host.engines, network, true), walletPath }; + } + + return { address: await walletAddress(walletPath, network, root, host) }; +} + +/** `address`, checked to be one of the airdrop's kind on the network. */ +async function addressDestination(address: string, engines: HostEngines, network: NetworkName, shielded: boolean): Promise { + const looksShielded = address.startsWith('mn_shield-addr_'); + + // The inverse mismatch (a shielded address, not asked for shielded) never + // reaches here: airdropNight infers shielded from the prefix. + if (shielded && !looksShielded) { + throw new Error( + `--shielded was passed but --wallet is an unshielded address.\n` + + `Pass a shielded address (mn_shield-addr_...) or drop --shielded.\n` + + `Got: ${address}` + ); + } + + const expectedPrefix = shielded + ? `mn_shield-addr_${network}1` + : `mn_addr_${network}1`; + + if (!address.startsWith(expectedPrefix)) { + throw new Error( + `Address does not match network "${network}".\n` + + `Expected prefix: ${expectedPrefix}\n` + + `Got: ${address}` + ); + } + + if (shielded) { + try { + (await engines.for(network)).keys.assertAddress(address, 'shielded', network); + } catch (err: any) { + throw new Error(`Invalid shielded address: ${err.message}`); + } + } + return address; +} diff --git a/src/lib/wallet/submit-steps.ts b/src/lib/wallet/submit-steps.ts new file mode 100644 index 00000000..9eeb1063 --- /dev/null +++ b/src/lib/wallet/submit-steps.ts @@ -0,0 +1,42 @@ +// What a wallet operation that pays says while the engine syncs, proves and +// submits, in the words mn has always shown, and its receipt after. + +import type { ProgressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { type Receipt, receiptOf } from '@kuiralabs/midnight-chain/lib/tx-receipt'; + +/** Says a sync's progress as "`label`... N%", and "`label`..." once it reaches the tip. */ +export function saySyncPercent(steps: ProgressSteps, label: string, applied: number, highest: number): void { + if (highest > 0) { + const pct = Math.min(Math.round((applied / highest) * 100), 100); + steps.update(pct >= 100 ? `${label}...` : `${label}... ${pct}%`); + } +} + +/** The engine's proving and submitting hooks, said as steps: the submit's wait shows its elapsed time. */ +export function submitSteps(steps: ProgressSteps): { onProving(): void; onSubmitting(): void; onSubmittingTick(elapsedMs: number): void } { + return { + onProving: () => steps.update('Generating ZK proof (this may take a few minutes)...'), + onSubmitting: () => steps.update('Submitting and waiting for finalization (typically 12 to 30s)...'), + onSubmittingTick: (elapsedMs) => { + const s = Math.floor(elapsedMs / 1000); + const mm = Math.floor(s / 60).toString().padStart(2, '0'); + const ss = (s % 60).toString().padStart(2, '0'); + steps.update(`Submitting and waiting for finalization... ${mm}:${ss} elapsed (typically 12 to 30s)`); + }, + }; +} + +/** + * The submitted transaction `txHash` once the indexer at `indexer` lists it, + * or why it is missing; undefined, without asking, when `waitMs` is 0. Then + * the step is done: "Transaction submitted". + */ +export async function receiptOfSubmitted(indexer: string, txHash: string, steps: ProgressSteps, signal: AbortSignal | undefined, waitMs: number): Promise { + let receipt: Receipt | undefined; + if (waitMs > 0) { + steps.update('Waiting for the indexer to list it...'); + receipt = await receiptOf(indexer, txHash, signal, waitMs); + } + steps.done('Transaction submitted'); + return receipt; +} diff --git a/src/lib/wallet/transfer.ts b/src/lib/wallet/transfer.ts new file mode 100644 index 00000000..4d83a6ec --- /dev/null +++ b/src/lib/wallet/transfer.ts @@ -0,0 +1,127 @@ +// Sending NIGHT from a wallet: unshielded, from its unshielded coins to an +// unshielded address, or shielded, from its shielded coins to a shielded +// address. The call syncs the wallet, proves, submits, and waits for the +// indexer to list the transaction. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { shieldedDisabledReason, shieldedSyncEnabled } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { type Receipt, RECEIPT_WAIT_MS } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { saveShieldedAddress } from '../wallet-config.ts'; +import { seedOf, type WalletSource } from '../seed-resolver.ts'; +import { receiptOfSubmitted, saySyncPercent, submitSteps } from './submit-steps.ts'; +import { networkChoiceOf, unshieldedAddressOf, type WalletCallOptions, type WalletOpened } from './wallet-call.ts'; + +export interface TransferNightOptions extends WalletCallOptions { + /** The recipient's address on the network: unshielded (mn_addr_…), or shielded (mn_shield-addr_…) when `shielded`. */ + recipient: string; + /** NIGHT to send, in its smallest unit; more than 0. */ + amount: bigint; + /** Send from the wallet's shielded NIGHT to a shielded address. */ + shielded?: boolean; + /** Allow a shielded transfer where the network has no shielded faucet (preview, preprod, stagenet). */ + forceShielded?: boolean; + /** How long to wait for the indexer to list the transaction, in milliseconds: RECEIPT_WAIT_MS when not given; 0 does not wait. */ + receiptWaitMs?: number; +} + +/** A submitted transfer. */ +export interface NightTransfer { + readonly network: NetworkName; + /** The transaction's identifier (`midnight tx status` takes it). */ + readonly txHash: string; + /** The transaction once the indexer lists it, or why it is missing; absent when `receiptWaitMs` is 0. */ + readonly receipt?: Receipt; +} + +/** + * Refuses, as a usage mistake, a shielded transfer on a network with no + * shielded faucet (no wallet holds shielded NIGHT there), unless `force`. + */ +export function assertShieldedTransferAllowed(network: NetworkName, force = false): void { + if (!shieldedSyncEnabled(network, force)) throw new UsageError(shieldedDisabledReason(network)); +} + +/** + * Sends `amount` NIGHT from the wallet to `recipient`: syncs the wallet + * (proof server, node and indexer), pays the fee from its Dust, submits, and + * waits for the indexer to list the transaction. A shielded transfer is + * refused where the network has no shielded faucet, unless `forceShielded`; + * it gives a wallet file its shielded address. + */ +export async function transferNight(host: Host, source: WalletSource, options: TransferNightOptions): Promise { + const { signal, onProgress, amount } = options; + const receiptWaitMs = options.receiptWaitMs ?? RECEIPT_WAIT_MS; + throwIfCancelled(signal); + if (amount <= 0n) throw new UsageError(`Invalid amount: ${nightAmountText(amount)} NIGHT — must be greater than 0`); + const { network, networkConfig, root } = networkTargetOf(host, networkChoiceOf(options)); + if (options.shielded) assertShieldedTransferAllowed(network, options.forceShielded); + const wallet = await seedOf(host, source); + const address = await unshieldedAddressOf(wallet, network, host.engines); + const steps = progressSteps(onProgress); + onProgress?.({ kind: 'wallet-opened', network, address }); + + const txHash = await withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, async (sdkWarnings) => { + if (!options.shielded) { + steps.start('Starting wallet...'); + return (await (await host.engines.for(network)).wallet.transfer({ + root, + notice: host.notice, + seedBuffer: wallet.seed, + networkConfig, + recipientAddress: options.recipient, + amount, + signal, + log: options.log, + sdkWarnings, + onSync: (applied, highest) => saySyncPercent(steps, 'Syncing wallet', applied, highest), + onSyncDetail: (detail) => steps.update(`Syncing wallet... (waiting on: ${detail})`), + onDust: (status) => steps.update(`Dust: ${status}`), + ...submitSteps(steps), + onSyncWarning: (_tag, message) => steps.update(`Syncing wallet... (${message}, retrying)`), + })).txHash; + } + + // Keep the SDK's transient errors and RPC noise off the terminal while this runs. + const stopListening = sdkWarnings.listen(undefined); + try { + steps.start('Syncing wallet...'); + const text = nightAmountText(amount); + const walletPath = wallet.walletPath; + return await (await host.engines.for(network)).wallet.shieldedTransfer({ + seed: wallet.seed, + root, + notice: host.notice, + network, + networkConfig, + recipient: options.recipient, + amount, + progress: silentSpinner(steps.update), + // Right after another payment the wallet's Dust can be short of this + // fee: wait when the rest is moments away, else say how long it takes. + waitForDustToCover: true, + // A wallet file keeps its shielded address for the next read. + ...(walletPath === null ? {} : { onSenderShieldedAddress: (shieldedAddress: string) => saveShieldedAddress(walletPath, network, shieldedAddress) }), + insufficient: (available) => + `Insufficient shielded balance: ${available} NIGHT available, ${text} NIGHT requested.\n` + + `Fund shielded balance: midnight airdrop ${text} --shielded`, + log: options.log, + signal, + onStatus: (status) => steps.update(status), + onSyncProgress: (applied, highest) => saySyncPercent(steps, 'Syncing wallet', applied, highest), + onSyncDetail: (detail) => steps.update(`Syncing wallet... (waiting on: ${detail})`), + }); + } finally { + stopListening(); + } + }); + + const receipt = await receiptOfSubmitted(networkConfig.indexer, txHash, steps, signal, receiptWaitMs); + return { network, txHash, ...(receipt === undefined ? {} : { receipt }) }; +} From 982fde2dfc3208b25a67192ed740f760d4fc1e41 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 15:41:10 -0800 Subject: [PATCH 69/88] Library functions for contracts and swaps; one per handler (3E, 6-8 of 8) deployContract, callContract and readContractState take the host, a plain request (contractDeployRequest / contractCallRequest; no library reads the working directory), a payer and a progress callback, and do the runtime check themselves; mn dev deploys through the same builders instead of a made-up argv. makeSwapOffer, inspectSwapOffer, takeSwapOffer, cancelSwapOffer and listSwapOffers take offer text and give file text; take and cancel wait for the receipt. The session-level makeOffer, takeOffer and cancelOffer stay public. A test holds every in-scope handler to its library calls, with no engine, payer or receipt calls of its own. Edge cases that changed: a bad --args JSON is reported before a missing contract; in swap, a bad network after bad terms or a missing offer file, and NO_PAYER before the heading; dev deploy refuses a contract built for another runtime before checking the wallet; the swap's "Opening the wallet" step ends with its tick line; --json and MCP progress include each step's first message. Suite 2892, beta 184; snapshot unchanged; fresh install; scratch chain final pass 84/84 in a clean runner, mn dev 8/8, swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads. --- src/__tests__/command-flags.test.ts | 4 + src/__tests__/contract-deploy.test.ts | 41 ++- src/__tests__/contract-lib.test.ts | 201 ++++++++++++++ src/__tests__/contract-request.test.ts | 39 ++- src/__tests__/handler-library-calls.test.ts | 72 +++++ src/__tests__/swap-lib.test.ts | 279 ++++++++++++++++++++ src/commands/contract.definition.ts | 4 +- src/commands/contract.ts | 210 +++++++-------- src/commands/dev.ts | 2 +- src/commands/swap.ts | 188 ++++++------- src/lib/contract/call.ts | 87 +++--- src/lib/contract/deploy.ts | 81 +++--- src/lib/contract/request.ts | 105 ++++++-- src/lib/contract/runtime-check.ts | 6 + src/lib/contract/state.ts | 106 ++++++++ src/lib/dev/deploy.ts | 32 +-- src/lib/swap/cancel.ts | 64 +++++ src/lib/swap/inspect.ts | 57 ++++ src/lib/swap/list.ts | 43 +++ src/lib/swap/make.ts | 65 +++++ src/lib/swap/request.ts | 38 ++- src/lib/swap/swap-session.ts | 34 +++ src/lib/swap/take.ts | 79 ++++++ src/lib/wallet/paid-call.ts | 65 +++++ src/lib/wallet/submit-steps.ts | 6 +- 25 files changed, 1532 insertions(+), 376 deletions(-) create mode 100644 src/__tests__/contract-lib.test.ts create mode 100644 src/__tests__/handler-library-calls.test.ts create mode 100644 src/__tests__/swap-lib.test.ts create mode 100644 src/lib/contract/state.ts create mode 100644 src/lib/swap/cancel.ts create mode 100644 src/lib/swap/inspect.ts create mode 100644 src/lib/swap/list.ts create mode 100644 src/lib/swap/make.ts create mode 100644 src/lib/swap/swap-session.ts create mode 100644 src/lib/swap/take.ts create mode 100644 src/lib/wallet/paid-call.ts diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 3c5446f3..015abe12 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -108,6 +108,9 @@ describe('the accepted flags match the code', () => { // The swap request's terms and expiry, and the network and endpoints. 'prepareMake(': ['give', 'give-token', 'want', 'want-token', 'expires-in', 'out', 'network', 'node', 'indexer-ws', 'proof-server'], 'prepareTake(': ['give', 'give-token', 'want', 'want-token', 'network', 'node', 'indexer-ws', 'proof-server'], + // The same, without the network: the handler gives it to the library function. + 'makeTermsOf(': ['give', 'give-token', 'want', 'want-token', 'expires-in', 'out'], + 'termsOf(': ['give', 'give-token', 'want', 'want-token'], 'resolveSeedSource(': ['seed', 'wallet'], 'resolveSeed(': ['seed', 'wallet'], 'walletSourceOf(': ['seed', 'wallet'], @@ -117,6 +120,7 @@ describe('the accepted flags match the code', () => { 'rejectNoCacheForWrites(': ['no-cache'], 'resolveTransferRequest(': ['shielded', 'force-shielded', 'wallet', 'network'], 'resolveScanDir(': ['managed', 'path'], + 'resolveDappDir(': ['path'], 'resolveContractDeployRequest(': ['path', 'managed', 'name', 'args', 'secret-key'], 'resolveContractCallRequest(': ['path', 'managed', 'name', 'address', 'circuit', 'args'], }; diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index c87aab7b..5ca80e70 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -6,21 +6,18 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { resolveContractDeployRequest } from '../lib/contract/request.ts'; +import { contractDeployRequest } from '../lib/contract/request.ts'; import { deployContract } from '../lib/contract/deploy.ts'; -import { resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; import { servePayerAt } from '../lib/serve-payer.ts'; -import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); - -const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; +const ENDPOINTS = { network: 'undeployed' as const, node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', proofServer: 'http://localhost:26300' }; +// The host the tests' calls run in: its state root under the test's home, the engines the CLI ships, nobody to ask, notices dropped. +let host: Host; let home: string; let originalHome: string | undefined; @@ -29,6 +26,7 @@ beforeEach(() => { originalHome = process.env.HOME; home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-contract-deploy-'))); process.env.HOME = home; + host = createHost({ paths: { stateRoot: stateRootIn(home), home }, engineLoader: loadInstalledEngine }); const compiler = path.join(home, 'dapp', 'managed', 'counter', 'compiler'); fs.mkdirSync(compiler, { recursive: true }); fs.writeFileSync(path.join(compiler, 'contract-info.json'), JSON.stringify({ @@ -45,15 +43,14 @@ afterEach(() => { describe('deployContract', () => { it('stops at the funds check when the paying wallet is not there, before anything is served', async () => { - const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'nobody', ...ENDPOINTS]); const said: string[] = []; - await expect(deployContract({ - request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host), + await expect(deployContract(host, { + ...ENDPOINTS, + request: contractDeployRequest({ dappDir: path.join(home, 'dapp') }), wallet: 'nobody', // Never reached: serving would be the step after the funds check. payer: servePayerAt(1), - progress: (message) => { said.push(message); return silentSpinner((later) => said.push(later)); }, + onProgress: (event) => { if ('message' in event) said.push(event.message); }, sdkWarnings: createSdkWarningRouter().openCall().warnings, })).rejects.toThrow(path.join(home, '.midnight', 'wallets', 'nobody.json')); expect(said).toEqual(['Checking wallet...']); @@ -67,13 +64,11 @@ describe('deployContract', () => { serve: async () => { asked.push('serve'); throw new Error('served by the program'); }, connect: async () => { throw new Error('not used'); }, }; - const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); - await expect(deployContract({ - request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host), + await expect(deployContract(host, { + ...ENDPOINTS, + request: contractDeployRequest({ dappDir: path.join(home, 'dapp') }), wallet: 'external', payer: ownPayer, - progress: () => silentSpinner(), sdkWarnings: createSdkWarningRouter().openCall().warnings, })).rejects.toThrow('served by the program'); expect(asked).toEqual(['assertCanPay external', 'serve']); @@ -92,13 +87,11 @@ describe('deployContract', () => { serve: async () => { asked.push('serve'); throw new Error('must not be served'); }, connect: async () => { throw new Error('not used'); }, }; - const args = parseArgs(['contract', 'deploy', '--path', path.join(home, 'dapp'), '--wallet', 'external', ...ENDPOINTS]); - await expect(deployContract({ - request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', stateRootIn(home), host), + await expect(deployContract(host, { + ...ENDPOINTS, + request: contractDeployRequest({ dappDir: path.join(home, 'dapp') }), wallet: 'external', payer: ownPayer, - progress: () => silentSpinner(), sdkWarnings: createSdkWarningRouter().openCall().warnings, signal: controller.signal, })).rejects.toBeInstanceOf(CancelledError); diff --git a/src/__tests__/contract-lib.test.ts b/src/__tests__/contract-lib.test.ts new file mode 100644 index 00000000..ad09a0b4 --- /dev/null +++ b/src/__tests__/contract-lib.test.ts @@ -0,0 +1,201 @@ +// deployContract, callContract and readContractState, called as a program +// calls them: a host of its own (a temporary state root, the engines the CLI +// ships), plain values in, typed results and codes out, no argv and no call +// context. The payer is the program's own (the injection the Payer interface +// exists for); the indexer a contract's raw state is read from is a stand-in +// HTTP endpoint (local-indexer.ts). A deploy or call that reaches a chain +// needs one: the scratch chain's live runs cover them. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { InsufficientBalanceError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { contractCallRequest, contractDeployRequest } from '../lib/contract/request.ts'; +import { deployContract } from '../lib/contract/deploy.ts'; +import { callContract } from '../lib/contract/call.ts'; +import { readContractState } from '../lib/contract/state.ts'; +import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; + +const ADDRESS = 'cb5230e1ac98e07520d3b330016743a05fec38dd8fe894ae5b9ac3f71cac5190'; +const ENDPOINTS = { network: 'undeployed' as const, node: 'ws://127.0.0.1:29944', indexerWS: 'ws://127.0.0.1:28088/api/v4/graphql/ws', proofServer: 'http://127.0.0.1:26300' }; + +let home: string; +let dapp: string; +let host: Host; + +/** A compiled contract as compactc lays it out, for compact-runtime `runtimeVersion`. */ +function compiledContract(runtimeVersion: string): void { + const compiler = path.join(dapp, 'managed', 'counter', 'compiler'); + fs.mkdirSync(compiler, { recursive: true }); + fs.writeFileSync(path.join(compiler, 'contract-info.json'), JSON.stringify({ + 'compiler-version': '0.35.0', 'language-version': '0.27.0', 'runtime-version': runtimeVersion, + circuits: [{ name: 'increment', pure: false, proof: true, arguments: [], 'result-type': { 'type-name': 'Tuple', types: [] } }], + witnesses: [], + })); +} + +beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-contract-lib-'))); + dapp = path.join(home, 'dapp'); + host = createHost({ paths: { stateRoot: path.join(home, '.midnight'), home }, engineLoader: loadInstalledEngine }); + compiledContract('0.20.0'); +}); + +afterEach(() => fs.rmSync(home, { recursive: true, force: true })); + +/** A program's payer that records what it is asked: its wallet has `night` NIGHT, and serving fails as `serveFails` says. */ +function programPayer(night: bigint, serveFails = 'served by the program') { + const asked: { step: string; target: PayingTarget; wallet: string | undefined; signal: AbortSignal | undefined }[] = []; + const payer: Payer = { + assertCanPay: async (target, wallet, progress, signal) => { + asked.push({ step: 'assertCanPay', target, wallet, signal }); + progress.update('Reading the balance...'); + if (night === 0n) { + progress.fail('No NIGHT balance'); + throw new InsufficientBalanceError('Wallet has 0 NIGHT'); + } + progress.stop('Wallet OK'); + return { nightBalance: night, dustBalance: 1n }; + }, + serve: async (target, wallet, _progress, _sdkWarnings, signal) => { + asked.push({ step: 'serve', target, wallet, signal }); + throw new Error(serveFails); + }, + connect: async () => { throw new Error('not used'); }, + }; + return { payer, asked }; +} + +describe('deployContract', () => { + it('says the contract suits the network, then each payer step; a failed step says so, and the payer\'s code comes out', async () => { + const { payer, asked } = programPayer(0n); + const said: unknown[] = []; + await expect(deployContract(host, { ...ENDPOINTS, request: contractDeployRequest({ dappDir: dapp }), payer, wallet: 'alice', onProgress: (event) => said.push(event) })) + .rejects.toMatchObject({ code: 'INSUFFICIENT_BALANCE' }); + expect(said).toEqual([ + { kind: 'contract-checked', network: 'undeployed' }, + { kind: 'start', message: 'Checking wallet...' }, + { kind: 'update', message: 'Reading the balance...' }, + { kind: 'step-failed', message: 'No NIGHT balance' }, + ]); + expect(asked.map(({ step, wallet }) => [step, wallet])).toEqual([['assertCanPay', 'alice']]); + // The payer pays on the network and endpoints the call chose. + expect(asked[0]!.target).toMatchObject({ network: 'undeployed', root: path.join(home, '.midnight'), endpoints: { node: ENDPOINTS.node, indexerWS: ENDPOINTS.indexerWS, proofServer: ENDPOINTS.proofServer } }); + expect(asked[0]!.target.networkConfig.node).toBe(ENDPOINTS.node); + }); + + it('ends the wallet check\'s step with its words and starts serving, which fails as the payer says', async () => { + const { payer, asked } = programPayer(5n); + const said: unknown[] = []; + await expect(deployContract(host, { ...ENDPOINTS, request: contractDeployRequest({ dappDir: dapp }), payer, onProgress: (event) => said.push(event) })) + .rejects.toThrow('served by the program'); + expect(said).toEqual([ + { kind: 'contract-checked', network: 'undeployed' }, + { kind: 'start', message: 'Checking wallet...' }, + { kind: 'update', message: 'Reading the balance...' }, + { kind: 'done', message: 'Wallet OK' }, + { kind: 'start', message: 'Starting mn serve...' }, + ]); + // No wallet given: the payer pays from its active one. + expect(asked.map(({ step, wallet }) => [step, wallet])).toEqual([['assertCanPay', undefined], ['serve', undefined]]); + }); + + it('refuses a contract compiled for another runtime with INVALID_ARGS, before the payer is asked or anything said', async () => { + compiledContract('0.16.0'); + const { payer, asked } = programPayer(5n); + const said: unknown[] = []; + await expect(deployContract(host, { ...ENDPOINTS, request: contractDeployRequest({ dappDir: dapp }), payer, onProgress: (event) => said.push(event) })) + .rejects.toMatchObject({ code: 'INVALID_ARGS', message: expect.stringContaining('compiled by compactc 0.35.0 for compact-runtime 0.16.0') }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); + + it('refuses a network that is not one, before the payer is asked', async () => { + const { payer, asked } = programPayer(5n); + await expect(deployContract(host, { ...ENDPOINTS, network: 'moonnet' as never, request: contractDeployRequest({ dappDir: dapp }), payer })).rejects.toThrow('Invalid network: "moonnet"'); + expect(asked).toEqual([]); + }); + + it('cancelled already: CancelledError, and nothing asked of the payer or said', async () => { + const { payer, asked } = programPayer(5n); + const said: unknown[] = []; + await expect(deployContract(host, { ...ENDPOINTS, request: contractDeployRequest({ dappDir: dapp }), payer, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })) + .rejects.toMatchObject({ code: 'CANCELLED' }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('callContract', () => { + const request = () => contractCallRequest({ dappDir: dapp, address: ADDRESS, circuit: 'increment' }); + + it('says the contract suits the network and checks the payer\'s wallet, handing it the call\'s wallet and cancellation', async () => { + const { payer, asked } = programPayer(0n); + const controller = new AbortController(); + const said: unknown[] = []; + await expect(callContract(host, { ...ENDPOINTS, request: request(), payer, wallet: 'bob', signal: controller.signal, onProgress: (event) => said.push(event) })) + .rejects.toMatchObject({ code: 'INSUFFICIENT_BALANCE' }); + expect(said[0]).toEqual({ kind: 'contract-checked', network: 'undeployed' }); + expect(said.at(-1)).toEqual({ kind: 'step-failed', message: 'No NIGHT balance' }); + expect(asked.map(({ step, wallet, signal }) => [step, wallet, signal === controller.signal])).toEqual([['assertCanPay', 'bob', true]]); + }); + + it('refuses a contract compiled for another runtime with INVALID_ARGS, before the payer is asked', async () => { + compiledContract('0.16.0'); + const { payer, asked } = programPayer(5n); + await expect(callContract(host, { ...ENDPOINTS, request: request(), payer })).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + expect(asked).toEqual([]); + }); + + it('cancelled already: CancelledError, and nothing asked of the payer or said', async () => { + const { payer, asked } = programPayer(5n); + const said: unknown[] = []; + await expect(callContract(host, { ...ENDPOINTS, request: request(), payer, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })) + .rejects.toMatchObject({ code: 'CANCELLED' }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('readContractState', () => { + let indexer: LocalIndexer; + // An indexer that holds no contract at any address. + beforeEach(async () => { indexer = await startLocalIndexer(() => JSON.stringify({ data: { contract: null, block: null } })); }); + afterEach(() => indexer.close()); + + const at = () => ({ ...ENDPOINTS, indexerWS: indexer.url.replace('http', 'ws') + '/ws' }); + + it('without a compiled contract in the dApp, falls back to the raw state after saying why; no contract at the address fails', async () => { + const said: unknown[] = []; + const empty = path.join(home, 'empty'); + fs.mkdirSync(empty); + await expect(readContractState(host, { ...at(), dappDir: empty, address: ADDRESS, onProgress: (event) => said.push(event) })) + .rejects.toThrow(`No contract found at address ${ADDRESS} on undeployed`); + expect(said).toEqual([ + { kind: 'state-reading', network: 'undeployed' }, + { kind: 'start', message: 'Querying contract state...' }, + { kind: 'fallback', reason: expect.stringContaining(`No compiled contract found in ${empty}`) }, + ]); + expect(indexer.requests).toHaveLength(1); + expect(indexer.requests[0]!.variables).toMatchObject({ address: ADDRESS }); + }); + + it('refuses an address that is not 64 hex characters with INVALID_ARGS, saying nothing and asking no indexer', async () => { + const said: unknown[] = []; + await expect(readContractState(host, { ...at(), dappDir: dapp, address: 'deadbeef', onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + expect(said).toEqual([]); + expect(indexer.requests).toEqual([]); + }); + + it('cancelled already: CancelledError, nothing said and no indexer asked', async () => { + const said: unknown[] = []; + await expect(readContractState(host, { ...at(), dappDir: dapp, address: ADDRESS, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })) + .rejects.toMatchObject({ code: 'CANCELLED' }); + expect(said).toEqual([]); + expect(indexer.requests).toEqual([]); + }); +}); diff --git a/src/__tests__/contract-request.test.ts b/src/__tests__/contract-request.test.ts index 97ff314f..6501e35b 100644 --- a/src/__tests__/contract-request.test.ts +++ b/src/__tests__/contract-request.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; -import { resolveContractCallRequest, resolveContractDeployRequest } from '../lib/contract/request.ts'; +import { contractCallRequest, contractDeployRequest, resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; @@ -27,8 +27,9 @@ function compiledContract(name: string, witnesses: { name: string }[] = []): voi })); } -const call = (...flags: string[]) => resolveContractCallRequest(parseArgs(['contract', 'call', '--path', dir, ...flags])); -const deploy = (...flags: string[]) => resolveContractDeployRequest(parseArgs(['contract', 'deploy', '--path', dir, ...flags])); +// The working directory the readers are given is not the dApp: --path names it. +const call = (...flags: string[]) => resolveContractCallRequest(parseArgs(['contract', 'call', '--path', dir, ...flags]), tmpdir()); +const deploy = (...flags: string[]) => resolveContractDeployRequest(parseArgs(['contract', 'deploy', '--path', dir, ...flags]), tmpdir()); beforeEach(() => { dir = join(tmpdir(), `mn-contract-request-${process.pid}-${Date.now()}`); @@ -84,3 +85,35 @@ describe('resolveContractDeployRequest', () => { expect(deploy().info.name).toBe('owned'); }); }); + +describe('the plain builders', () => { + it('build the same request from plain values a program holds, with no flags and no working directory', () => { + expect(contractCallRequest({ dappDir: dir, address: ADDRESS, circuit: 'add', args: [1, 2] })) + .toEqual(call('--address', ADDRESS, '--circuit', 'add', '--args', '[1,2]')); + const key = 'ab'.repeat(32); + expect(contractDeployRequest({ dappDir: dir, args: [7], secretKey: key })).toEqual(deploy('--args', '[7]', '--secret-key', key)); + expect(contractDeployRequest({ dappDir: dir })).toMatchObject({ constructorArgs: [], privateStateSecretKey: undefined }); + }); + + it('look for the compiled contract in managedDir when given, and pick one by name', () => { + compiledContract('token'); + const managedDir = join(dir, 'managed', 'token'); + expect(contractDeployRequest({ dappDir: tmpdir(), managedDir }).info.name).toBe('token'); + expect(contractDeployRequest({ dappDir: dir, name: 'token' }).info.name).toBe('token'); + expect(contractDeployRequest({ dappDir: dir }).info.name).toBe('counter'); + }); + + it('refuse a call\'s bad address, unknown circuit and wrong count of arguments as usage mistakes', () => { + expect(() => contractCallRequest({ dappDir: dir, address: 'deadbeef', circuit: 'increment' })).toThrow(UsageError); + expect(() => contractCallRequest({ dappDir: dir, address: ADDRESS, circuit: 'decrement' })).toThrow('counter has no circuit "decrement"'); + expect(() => contractCallRequest({ dappDir: dir, address: ADDRESS, circuit: 'add', args: [1] })).toThrow('add takes 2 arguments (x, y); --args gave 1.'); + }); +}); + +describe('the argument readers\' working directory', () => { + it('is where the contract is looked for when neither --path nor --managed is given', () => { + expect(resolveContractDeployRequest(parseArgs(['contract', 'deploy']), dir)).toMatchObject({ dappDir: dir, info: { name: 'counter' } }); + expect(resolveScanDir(parseArgs(['contract', 'inspect']), dir)).toBe(dir); + expect(resolveScanDir(parseArgs(['contract', 'inspect', '--managed', 'managed/counter']), dir)).toBe(join(dir, 'managed', 'counter')); + }); +}); diff --git a/src/__tests__/handler-library-calls.test.ts b/src/__tests__/handler-library-calls.test.ts new file mode 100644 index 00000000..948e3735 --- /dev/null +++ b/src/__tests__/handler-library-calls.test.ts @@ -0,0 +1,72 @@ +// What a command does is one library function a program can call too; its +// handler parses the arguments, calls it, and prints. For the commands whose +// work became library functions (part 3E), each handler calls the function of +// each of its operations once, imported from a library module, and reaches +// nothing below it: no engine (`engines.for(`, an engine's wallet or other +// part), no payer (its connect, serve or funds check), no receipt read. Read +// from the source with strings and comments blanked. + +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { codeOnly } from '../../scripts/check-process-safety.mjs'; + +const ROOT = join(import.meta.dirname, '..', '..'); + +/** Each handler in scope, and the library function of each of its operations. */ +const HANDLERS: Record = { + 'src/commands/balance.ts': ['readAddressBalance', 'readWalletBalance'], + 'src/commands/transfer.ts': ['transferNight'], + 'src/commands/airdrop.ts': ['airdropNight'], + 'src/commands/dust.ts': ['readDustStatus', 'registerDust', 'exportDustSnapshot'], + 'src/commands/contract.ts': ['deployContract', 'callContract', 'readContractState'], + 'src/commands/swap.ts': ['makeSwapOffer', 'inspectSwapOffer', 'takeSwapOffer', 'cancelSwapOffer', 'listSwapOffers'], + 'packages/chain/src/commands/tx.ts': ['transactionStatus'], +}; + +/** What only a library function may call, by what it looks like in the code. */ +const BELOW_A_HANDLER: Record = { + 'the host\'s engines': /\bengines\s*\.\s*(for|load|any)\s*\(/, + 'an engine\'s wallet': /\.\s*wallet\s*\.\s*\w+\s*\(/, + 'an engine\'s keys, ledger, contracts or readers': /\.\s*(keys|ledger|contracts|readers)\s*\.\s*\w+/, + 'a payer\'s wallet session': /\.\s*connect\s*\(/, + 'a payer\'s served wallet': /\.\s*serve\s*\(/, + 'a payer\'s funds check': /\.\s*assertCanPay\s*\(/, + 'a receipt': /\breceiptOf\s*\(/, +}; + +const sourceOf = (file: string): string => readFileSync(join(ROOT, file), 'utf8'); + +describe.each(Object.entries(HANDLERS))('%s', (file, functions) => { + const source = sourceOf(file); + const code = codeOnly(source); + + it.each(functions)('calls %s once, imported from a library module', (name) => { + expect(code.match(new RegExp(`\\b${name}\\s*\\(`, 'g')) ?? []).toHaveLength(1); + const imported = [...source.matchAll(/^import\s+(?:type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'/gm)] + .filter(([, names]) => names!.split(',').some((each) => each.trim() === name)) + .map(([, , from]) => from); + expect(imported).toHaveLength(1); + expect(imported[0]).toMatch(/\/lib\//); + }); + + it('reaches nothing below a library function', () => { + const found = Object.entries(BELOW_A_HANDLER).filter(([, site]) => site.test(code)).map(([what]) => what); + expect(found).toEqual([]); + }); +}); + +describe('the check', () => { + it('finds each kind of call below a library function', () => { + const below = [ + 'await (await ctx.host.engines.for(network)).wallet.transfer(options);', + 'const session = await payerFor("swap make", ctx).connect(target, wallet, spinner, warnings, signal);', + 'await payer.serve(target, wallet, spinner, warnings, signal);', + 'await payer.assertCanPay(target, wallet, spinner, signal);', + 'const receipt = await receiptOf(indexer, txHash, signal);', + 'const raw = await engine.contracts.rawState(config, address);', + ]; + for (const line of below) expect(Object.values(BELOW_A_HANDLER).some((site) => site.test(line)), line).toBe(true); + expect(Object.values(BELOW_A_HANDLER).some((site) => site.test('const { network } = networkChoiceFromArgs(args); ctx.output.result(receiptJson(receipt));'))).toBe(false); + }); +}); diff --git a/src/__tests__/swap-lib.test.ts b/src/__tests__/swap-lib.test.ts new file mode 100644 index 00000000..88ad2bae --- /dev/null +++ b/src/__tests__/swap-lib.test.ts @@ -0,0 +1,279 @@ +// makeSwapOffer, inspectSwapOffer, takeSwapOffer, cancelSwapOffer and +// listSwapOffers, called as a program calls them: a host of its own (a +// temporary state root, the engines the CLI ships), plain values in (the +// offer file's text, not its path), typed results and codes out, no argv and +// no call context. The indexer is a stand-in answering the tip query over +// HTTP and the spend check over graphql-transport-ws, as offer-liveness.ts +// asks them; the offer is a real one (fixtures/swap-offer.ts). The payer is +// the program's own: it records what it is asked and opens no wallet, so a +// make, take or cancel stops where its wallet would open; the scratch chain's +// live runs cover them past it. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { WebSocketServer } from 'ws'; +import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import type { ConnectOptions, Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { encodeOfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; +import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { makeSwapOffer } from '../lib/swap/make.ts'; +import { inspectSwapOffer } from '../lib/swap/inspect.ts'; +import { takeSwapOffer } from '../lib/swap/take.ts'; +import { cancelSwapOffer } from '../lib/swap/cancel.ts'; +import { listSwapOffers } from '../lib/swap/list.ts'; +import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; + +const NOW = new Date('2026-11-02T12:00:00.000Z'); +const SEED = 'c4'.repeat(32); +const ADDRESS = deriveAllAddresses(Buffer.from(SEED, 'hex')).undeployed; +const TERMS = { give: { token: OFFER_GIVE, amount: 10n }, want: { token: OFFER_WANT, amount: 7n } }; +const OFFER = readOffer(SWAP_OFFER_HEX); +const SPENT_IN = 'cd'.repeat(32); + +/** The stand-in indexer: the chain's tip over HTTP, and the spends of the coins it is told are spent over WebSocket, on one port. */ +interface OfferIndexer { + readonly url: string; + /** The nullifier prefixes each spend check asked about. */ + readonly asked: string[][]; + close(): Promise; +} + +async function startOfferIndexer(spent: readonly string[]): Promise { + const asked: string[][] = []; + const server: Server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ data: { block: { height: 812 } } })); + }); + }); + const wss = new WebSocketServer({ server }); + wss.on('connection', (ws) => ws.on('message', (raw) => { + const msg = JSON.parse(raw.toString()); + if (msg.type === 'connection_init') ws.send(JSON.stringify({ type: 'connection_ack' })); + else if (msg.type === 'subscribe') { + const prefixes = msg.payload.variables.prefixes as string[]; + asked.push(prefixes); + for (const nullifier of prefixes.filter((n) => spent.includes(n))) { + ws.send(JSON.stringify({ id: msg.id, type: 'next', payload: { data: { shieldedNullifierTransactions: { nullifier, transactionHash: SPENT_IN, blockHeight: 800 } } } })); + } + ws.send(JSON.stringify({ id: msg.id, type: 'complete' })); + } + })); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `ws://127.0.0.1:${port}/api/v4/graphql/ws`, + asked, + close: () => new Promise((resolve) => { + for (const client of wss.clients) client.terminate(); + wss.close(); + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +let home: string; +let host: Host; +let root: string; +let indexer: OfferIndexer | undefined; + +beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-swap-lib-'))); + root = path.join(home, '.midnight'); + host = createHost({ paths: { stateRoot: root, home }, engineLoader: loadInstalledEngine }); +}); + +afterEach(async () => { + await indexer?.close(); + indexer = undefined; + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** The network and its endpoints, the indexer the stand-in; nothing else is reached. */ +const on = () => ({ network: 'undeployed' as const, indexerWS: indexer?.url ?? 'ws://127.0.0.1:1/api/v4/graphql/ws', node: 'ws://127.0.0.1:1', proofServer: 'http://127.0.0.1:1' }); + +/** The real offer's file text, for `network`, expiring at `expiresAt`. */ +const offerText = (expiresAt = new Date(NOW.getTime() + 60_000), network = 'undeployed') => + encodeOfferEnvelope({ network: network as 'undeployed', id: OFFER.id, terms: OFFER.terms, expiresAt, tx: SWAP_OFFER_HEX }); + +/** mn's wallet `alice` under the host's state root, the active one. */ +function alice(): void { + saveWalletConfig({ seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: NOW.toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); +} + +/** A program's payer whose wallet won't open: it records what it is asked, and what its step said. */ +function programPayer() { + const asked: { target: PayingTarget; wallet: string | undefined; options: ConnectOptions | undefined; signal: AbortSignal | undefined }[] = []; + const payer: Payer = { + assertCanPay: async () => { throw new Error('not used'); }, + serve: async () => { throw new Error('not used'); }, + connect: async (target, wallet, progress, _sdkWarnings, signal, options) => { + asked.push({ target, wallet, options, signal }); + progress.update('Syncing...'); + throw new Error('no wallet here'); + }, + }; + return { payer, asked }; +} + +const openOffer = (id: string, nullifier: string): OpenOffer => ({ id, terms: TERMS, nullifiers: [nullifier], madeAt: NOW, expiresAt: new Date(NOW.getTime() + 60_000) }); + +describe('inspectSwapOffer', () => { + it('reads the offer\'s text and finds it live: its terms as its bytes state them, not expired', async () => { + indexer = await startOfferIndexer([]); + const said: unknown[] = []; + const standing = await inspectSwapOffer(host, { ...on(), offer: offerText(), now: NOW, onProgress: (event) => said.push(event) }); + expect(standing).toEqual({ network: 'undeployed', id: OFFER.id, terms: TERMS, expiresAt: new Date(NOW.getTime() + 60_000), expired: false, live: true, spends: [] }); + expect(said).toEqual([{ kind: 'start', message: 'Asking the indexer whether it is still live...' }, { kind: 'done', message: 'Live' }]); + expect(indexer.asked).toEqual([OFFER.nullifiers]); + }); + + it('finds it taken when a coin of its is spent, and expired past its expiry', async () => { + indexer = await startOfferIndexer([OFFER.nullifiers[0]!]); + const said: unknown[] = []; + const standing = await inspectSwapOffer(host, { ...on(), offer: offerText(NOW), now: NOW, onProgress: (event) => said.push(event) }); + expect(standing).toMatchObject({ live: false, expired: true, spends: [{ nullifier: OFFER.nullifiers[0], transactionHash: SPENT_IN, blockHeight: 800 }] }); + expect(said.at(-1)).toEqual({ kind: 'done', message: 'Taken' }); + }); + + it('refuses an offer for another network, and text that is not an offer with NOT_AN_OFFER, asking no indexer', async () => { + indexer = await startOfferIndexer([]); + await expect(inspectSwapOffer(host, { ...on(), offer: offerText(undefined, 'preview'), now: NOW })).rejects.toThrow('The offer is for preview, not undeployed'); + await expect(inspectSwapOffer(host, { ...on(), offer: '{"not":"an offer"}', now: NOW })).rejects.toMatchObject({ code: 'NOT_AN_OFFER' }); + expect(indexer.asked).toEqual([]); + }); + + it('cancelled already: CancelledError, nothing said and no indexer asked', async () => { + indexer = await startOfferIndexer([]); + const said: unknown[] = []; + await expect(inspectSwapOffer(host, { ...on(), offer: offerText(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(said).toEqual([]); + expect(indexer.asked).toEqual([]); + }); +}); + +describe('takeSwapOffer', () => { + it('says the checked offer, then opens the payer\'s wallet with its shielded side synced, with the call\'s wallet and cancellation', async () => { + const { payer, asked } = programPayer(); + const controller = new AbortController(); + const said: unknown[] = []; + await expect(takeSwapOffer(host, { ...on(), offer: offerText(), agreed: TERMS, now: NOW, payer, wallet: 'bob', signal: controller.signal, onProgress: (event) => said.push(event) })) + .rejects.toThrow('no wallet here'); + expect(said).toEqual([ + { kind: 'offer-checked', network: 'undeployed', id: OFFER.id, terms: TERMS }, + { kind: 'start', message: 'Opening the wallet...' }, + { kind: 'update', message: 'Syncing...' }, + ]); + expect(asked.map(({ wallet, options, signal }) => [wallet, options, signal === controller.signal])).toEqual([['bob', { shielded: true }, true]]); + expect(asked[0]!.target).toMatchObject({ network: 'undeployed', root }); + }); + + it('refuses other terms with TERMS_MISMATCH and an expired offer with OFFER_EXPIRED, before the wallet opens or anything is said', async () => { + const { payer, asked } = programPayer(); + const said: unknown[] = []; + const onProgress = (event: unknown) => said.push(event); + await expect(takeSwapOffer(host, { ...on(), offer: offerText(), agreed: { ...TERMS, want: { token: OFFER_WANT, amount: 8n } }, now: NOW, payer, onProgress })).rejects.toMatchObject({ code: 'TERMS_MISMATCH' }); + await expect(takeSwapOffer(host, { ...on(), offer: offerText(NOW), agreed: TERMS, now: NOW, payer, onProgress })).rejects.toMatchObject({ code: 'OFFER_EXPIRED' }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); + + it('cancelled already: CancelledError, and nothing asked of the payer or said', async () => { + const { payer, asked } = programPayer(); + const said: unknown[] = []; + await expect(takeSwapOffer(host, { ...on(), offer: offerText(), agreed: TERMS, now: NOW, payer, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('makeSwapOffer', () => { + it('says its network, then opens the payer\'s wallet with its shielded side synced', async () => { + alice(); + const { payer, asked } = programPayer(); + const said: unknown[] = []; + await expect(makeSwapOffer(host, { ...on(), terms: TERMS, expiresAt: new Date(NOW.getTime() + 60_000), now: NOW, payer, onProgress: (event) => said.push(event) })).rejects.toThrow('no wallet here'); + expect(said.slice(0, 2)).toEqual([{ kind: 'swap-network', network: 'undeployed' }, { kind: 'start', message: 'Opening the wallet...' }]); + expect(asked.map(({ wallet, options }) => [wallet, options])).toEqual([[undefined, { shielded: true }]]); + }); + + it('refuses a wallet mn has no file for with WALLET_NOT_FOUND, before the payer is asked', async () => { + const { payer, asked } = programPayer(); + await expect(makeSwapOffer(host, { ...on(), terms: TERMS, expiresAt: NOW, payer, wallet: 'nobody' })).rejects.toMatchObject({ code: 'WALLET_NOT_FOUND' }); + expect(asked).toEqual([]); + }); + + it('cancelled already: CancelledError, and nothing asked of the payer or said', async () => { + alice(); + const { payer, asked } = programPayer(); + const said: unknown[] = []; + await expect(makeSwapOffer(host, { ...on(), terms: TERMS, expiresAt: NOW, payer, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('cancelSwapOffer', () => { + it('opens the payer\'s wallet with its shielded side synced, for the wallet named', async () => { + alice(); + const { payer, asked } = programPayer(); + await expect(cancelSwapOffer(host, { ...on(), id: OFFER.id.slice(0, 8), payer, wallet: 'alice' })).rejects.toThrow('no wallet here'); + expect(asked.map(({ wallet, options }) => [wallet, options])).toEqual([['alice', { shielded: true }]]); + }); + + it('cancelled already: CancelledError, and nothing asked of the payer or said', async () => { + alice(); + const { payer, asked } = programPayer(); + const said: unknown[] = []; + await expect(cancelSwapOffer(host, { ...on(), id: OFFER.id, payer, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(asked).toEqual([]); + expect(said).toEqual([]); + }); +}); + +describe('listSwapOffers', () => { + it('lists the wallet\'s open offers, each asked of the indexer; one taken since is listed taken and closed in mn\'s record', async () => { + alice(); + const live = openOffer('a1'.repeat(32), 'b1'.repeat(32)); + const taken = openOffer('a2'.repeat(32), 'b2'.repeat(32)); + recordOpenOffer(root, 'undeployed', ADDRESS, live); + recordOpenOffer(root, 'undeployed', ADDRESS, taken); + indexer = await startOfferIndexer(['b2'.repeat(32)]); + const said: unknown[] = []; + + const listed = await listSwapOffers(host, { ...on(), now: NOW, onProgress: (event) => said.push(event) }); + + expect(listed).toEqual({ network: 'undeployed', offers: [{ offer: live, expired: false, taken: false }, { offer: taken, expired: false, taken: true }] }); + expect(said).toEqual([{ kind: 'start', message: 'Asking the indexer about each open offer...' }, { kind: 'done', message: '2 offers' }]); + expect(readOpenOffers(root, 'undeployed', ADDRESS).map((o) => o.id)).toEqual([live.id]); + }); + + it('lists none for a wallet with no open offers, asking no indexer', async () => { + alice(); + indexer = await startOfferIndexer([]); + expect(await listSwapOffers(host, { ...on(), wallet: 'alice' })).toEqual({ network: 'undeployed', offers: [] }); + expect(indexer.asked).toEqual([]); + }); + + it('cancelled already: CancelledError, nothing said and no indexer asked', async () => { + alice(); + recordOpenOffer(root, 'undeployed', ADDRESS, openOffer('a1'.repeat(32), 'b1'.repeat(32))); + indexer = await startOfferIndexer([]); + const said: unknown[] = []; + await expect(listSwapOffers(host, { ...on(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); + expect(said).toEqual([]); + expect(indexer.asked).toEqual([]); + }); +}); diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index c6a5f01b..5b8cb573 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -220,7 +220,7 @@ export const contractDefinition: CommandDefinition = { async check(params, call) { const { resolveContractDeployRequest } = await import('../lib/contract/request.ts'); const args = call.argv(); - const { info } = resolveContractDeployRequest(args); + const { info } = resolveContractDeployRequest(args, process.cwd()); const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; @@ -255,7 +255,7 @@ export const contractDefinition: CommandDefinition = { async check(params, call) { const { resolveContractCallRequest } = await import('../lib/contract/request.ts'); const args = call.argv(); - const { info } = resolveContractCallRequest(args); + const { info } = resolveContractCallRequest(args, process.cwd()); const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 68fda833..0a639853 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -1,20 +1,20 @@ // Contract commands — inspect, deploy, call, and query state for compiled Midnight contracts. -import { resolve } from 'node:path'; import { type ParsedArgs, getFlag, hasFlag, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { CancelledError, UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { untilCancelled } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; import { header, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; import { bold, dim, teal, yellow, green } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import { type Payer, payerFor, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { type Payer, payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; -import { validateContractAddress } from '../lib/contract/validate.ts'; +import { readContractState } from '../lib/contract/state.ts'; +import { showPaidStep } from '../lib/wallet/paid-call.ts'; import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; -import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; +import { resolveContractCallRequest, resolveContractDeployRequest, resolveDappDir, resolveScanDir } from '../lib/contract/request.ts'; import { findContractInfo, formatCircuitSignature, @@ -60,7 +60,7 @@ export default async function contractCommand(args: ParsedArgs, ctx: CallContext async function handleInspect(args: ParsedArgs, ctx: CallContext): Promise { const jsonMode = hasFlag(args, 'json'); - const startDir = resolveScanDir(args); + const startDir = resolveScanDir(args, process.cwd()); const contractName = getFlag(args, 'name'); const { info } = findContractInfo(startDir, contractName); @@ -111,34 +111,31 @@ async function handleInspect(args: ParsedArgs, ctx: CallContext): Promise async function handleDeploy(args: ParsedArgs, payer: Payer, ctx: CallContext): Promise { const jsonMode = hasFlag(args, 'json'); - const request = resolveContractDeployRequest(args); + const request = resolveContractDeployRequest(args, process.cwd()); const { info, constructorArgs } = request; if (!jsonMode) { ctx.output.stderr('\n' + header('Contract Deploy') + '\n\n'); } - const target = resolvePayingTarget(args, 'contract', 'deploy', ctx.config.paths.stateRoot, ctx.host); - const { network } = target; - await assertContractRunsOn(info, network, target.root, ctx.host.engines); - - if (!jsonMode) { - ctx.output.stderr(keyValue('Contract', info.name) + '\n'); - ctx.output.stderr(keyValue('Network', network) + '\n'); - if (constructorArgs.length > 0) { - ctx.output.stderr(keyValue('Constructor args', String(constructorArgs.length)) + '\n'); - } - ctx.output.stderr('\n'); - } - - const deployed = await deployContract({ + const progress = spinnerReporter(ctx.progress, jsonMode); + const deployed = await deployContract(ctx.host, { + ...networkChoiceFromArgs(args), request, - target, - wallet: getFlag(args, 'wallet'), payer, - progress: (message) => jsonMode ? ctx.progress.silent() : ctx.progress.start(message), + wallet: getFlag(args, 'wallet'), sdkWarnings: ctx.sdkWarnings, signal: ctx.signal, + onProgress: (event) => { + if (event.kind !== 'contract-checked') return showPaidStep(progress, event); + if (jsonMode) return; + ctx.output.stderr(keyValue('Contract', info.name) + '\n'); + ctx.output.stderr(keyValue('Network', event.network) + '\n'); + if (constructorArgs.length > 0) { + ctx.output.stderr(keyValue('Constructor args', String(constructorArgs.length)) + '\n'); + } + ctx.output.stderr('\n'); + }, }); if (jsonMode) { @@ -149,13 +146,13 @@ async function handleDeploy(args: ParsedArgs, payer: Payer, ctx: CallContext): P subcommand: 'deploy', contractName: deployed.contractName, address: deployed.address, - network, + network: deployed.network, }); } else { ctx.output.stderr('\n'); ctx.output.stderr(keyValue('Address', deployed.address) + '\n'); ctx.output.stderr('\n' + green(' ✓ Deploy successful') + '\n'); - writeNextStepsHint(ctx.output, deployed.address, info.circuits, network); + writeNextStepsHint(ctx.output, deployed.address, info.circuits, deployed.network); // Pipeable address on stdout for shell composition (e.g. `addr=$(mn contract deploy)`). ctx.output.stdout(deployed.address + '\n'); } @@ -185,31 +182,28 @@ function writeNextStepsHint(output: CallOutput, address: string, circuits: { nam async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Promise { const jsonMode = hasFlag(args, 'json'); - const request = resolveContractCallRequest(args); + const request = resolveContractCallRequest(args, process.cwd()); const { info, address, circuit } = request; if (!jsonMode) { ctx.output.stderr('\n' + header('Contract Call') + '\n\n'); } - const target = resolvePayingTarget(args, 'contract', 'call', ctx.config.paths.stateRoot, ctx.host); - const { network } = target; - await assertContractRunsOn(info, network, target.root, ctx.host.engines); - - if (!jsonMode) { - ctx.output.stderr(keyValue('Contract', info.name) + '\n'); - ctx.output.stderr(keyValue('Circuit', circuit) + '\n'); - ctx.output.stderr(keyValue('Address', address.slice(0, 20) + '...') + '\n\n'); - } - - const called = await callContract({ + const progress = spinnerReporter(ctx.progress, jsonMode); + const called = await callContract(ctx.host, { + ...networkChoiceFromArgs(args), request, - target, - wallet: getFlag(args, 'wallet'), payer, - progress: (message) => jsonMode ? ctx.progress.silent() : ctx.progress.start(message), + wallet: getFlag(args, 'wallet'), sdkWarnings: ctx.sdkWarnings, signal: ctx.signal, + onProgress: (event) => { + if (event.kind !== 'contract-checked') return showPaidStep(progress, event); + if (jsonMode) return; + ctx.output.stderr(keyValue('Contract', info.name) + '\n'); + ctx.output.stderr(keyValue('Circuit', circuit) + '\n'); + ctx.output.stderr(keyValue('Address', address.slice(0, 20) + '...') + '\n\n'); + }, }); if (jsonMode) { @@ -218,7 +212,7 @@ async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Pro contractName: called.contractName, circuit, address, - network, + network: called.network, status: called.status, }); } else { @@ -230,90 +224,66 @@ async function handleCall(args: ParsedArgs, payer: Payer, ctx: CallContext): Pro async function handleState(args: ParsedArgs, ctx: CallContext): Promise { const jsonMode = hasFlag(args, 'json'); - const dappDir = resolve(getFlag(args, 'path') ?? process.cwd()); - const scanDir = resolveScanDir(args); - const contractName = getFlag(args, 'name'); + const cwd = process.cwd(); + const dappDir = resolveDappDir(args, cwd); + const scanDir = resolveScanDir(args, cwd); const address = requireFlag(args, 'address', 'contract address'); - validateContractAddress(address); - - const { runState } = await import('../lib/contract/runner.ts'); - - const { network, root, networkConfig } = resolvePayingTarget(args, 'contract', 'state', ctx.config.paths.stateRoot, ctx.host); - - if (!jsonMode) { - ctx.output.stderr('\n' + header('Contract State') + '\n\n'); - ctx.output.stderr(keyValue('Address', address.slice(0, 20) + '...') + '\n'); - ctx.output.stderr(keyValue('Network', network) + '\n\n'); - } - // Try parsed ledger state via runner (needs compiled contract in dApp) - const spinner = jsonMode ? ctx.progress.silent() : ctx.progress.start('Querying contract state...'); - - try { - const { info } = findContractInfo(scanDir, contractName); - - const result = await runState({ - dappDir, - network, - root, - engines: ctx.host.engines, - networkConfig, - managedDir: info.managedDir, - contractName: info.name, - contractAddress: address, - onMessage: (msg) => spinner.update(msg), - signal: ctx.signal, - }); - - spinner.stop('State retrieved'); - - if (jsonMode) { - ctx.output.result({ - subcommand: 'state', - address, - network, - ...result, - }); - } else { - // Display scalar fields - const hasFields = Object.keys(result.fields).length > 0; - const hasMaps = Object.keys(result.maps).length > 0; - - if (hasFields || hasMaps) { - ctx.output.stderr(bold(' Ledger State') + '\n'); - for (const [key, value] of Object.entries(result.fields)) { - ctx.output.stderr(` ${key}: ${teal(value)}` + '\n'); - } - for (const [key, info] of Object.entries(result.maps)) { - ctx.output.stderr(` ${key}: ${dim(`Map (${(info as any).size} entries)`)}` + '\n'); - } + const progress = spinnerReporter(ctx.progress, jsonMode); + const state = await readContractState(ctx.host, { + ...networkChoiceFromArgs(args), + dappDir, + scanDir, + name: getFlag(args, 'name'), + address, + signal: ctx.signal, + onProgress: (event) => { + if (event.kind === 'state-reading') { + if (jsonMode) return; + ctx.output.stderr('\n' + header('Contract State') + '\n\n'); + ctx.output.stderr(keyValue('Address', address.slice(0, 20) + '...') + '\n'); + ctx.output.stderr(keyValue('Network', event.network) + '\n\n'); + } else if (event.kind === 'fallback') { + progress.report({ kind: 'done', message: yellow('⚠') + ' Parsed state unavailable, showing raw' }); } else { - ctx.output.stderr(dim(' (no ledger fields found)') + '\n'); + progress.report(event); } - ctx.output.stderr('\n'); - } - } catch (err) { - // A cancelled call stops here; it doesn't fall back to the raw state. - if (err instanceof CancelledError) throw err; - throwIfCancelled(ctx.signal); - // If runner fails (no compiled contract in cwd), fall back to raw state - spinner.stop(yellow('⚠') + ' Parsed state unavailable, showing raw'); - - // The engine's query takes no signal: the call stops waiting for it when cancelled. - const raw = await untilCancelled((await ctx.host.engines.for(network)).contracts.rawState(networkConfig, address), ctx.signal); - - if (!raw) { - throw new Error(`No contract found at address ${address} on ${network}`); - } + }, + }); + if (state.kind === 'parsed') { + const { network, fields, maps } = state; if (jsonMode) { - ctx.output.result({ subcommand: 'state', address, network, raw }); + ctx.output.result({ subcommand: 'state', address, network, fields, maps }); + return; + } + // Display scalar fields + const hasFields = Object.keys(fields).length > 0; + const hasMaps = Object.keys(maps).length > 0; + + if (hasFields || hasMaps) { + ctx.output.stderr(bold(' Ledger State') + '\n'); + for (const [key, value] of Object.entries(fields)) { + ctx.output.stderr(` ${key}: ${teal(value)}` + '\n'); + } + for (const [key, info] of Object.entries(maps)) { + ctx.output.stderr(` ${key}: ${dim(`Map (${info.size} entries)`)}` + '\n'); + } } else { - ctx.output.stderr(bold(' Raw State') + '\n'); - ctx.output.stderr(dim(' (run from dApp root for parsed ledger fields)') + '\n'); - for (const line of rawStateLines(raw, ' ')) ctx.output.stderr(line + '\n'); - ctx.output.stderr('\n'); + ctx.output.stderr(dim(' (no ledger fields found)') + '\n'); } + ctx.output.stderr('\n'); + return; + } + + const { network, raw } = state; + if (jsonMode) { + ctx.output.result({ subcommand: 'state', address, network, raw }); + } else { + ctx.output.stderr(bold(' Raw State') + '\n'); + ctx.output.stderr(dim(' (run from dApp root for parsed ledger fields)') + '\n'); + for (const line of rawStateLines(raw, ' ')) ctx.output.stderr(line + '\n'); + ctx.output.stderr('\n'); } } diff --git a/src/commands/dev.ts b/src/commands/dev.ts index 28bbb356..01f8f464 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -247,7 +247,7 @@ async function deployContract(project: ProjectInfo, ctx: CallContext): Promise ({ token, amount: amount.toString() }); const termsJson = ({ give, want }: SwapTerms) => ({ give: legJson(give), want: legJson(want) }); const legText = ({ token, amount }: SwapLeg) => `${amount} of ${token}`; -// A swap spends shielded coins only: its wallet syncs the shielded side on every network, stagenet included. -const SHIELDED: ConnectOptions = { shielded: true }; export default async function swapCommand(args: ParsedArgs, ctx: CallContext): Promise { const jsonMode = hasFlag(args, 'json'); - const spinnerFor = (label: string): Spinner => (jsonMode ? ctx.progress.silent() : ctx.progress.start(label)); + const progress = spinnerReporter(ctx.progress, jsonMode); const walletFlag = getFlag(args, 'wallet'); - const root = ctx.config.paths.stateRoot; const now = new Date(); + const call = { ...networkChoiceFromArgs(args), signal: ctx.signal }; + const paid = { ...call, wallet: walletFlag, sdkWarnings: ctx.sdkWarnings }; switch (args.subcommand) { case 'make': { - const { target, terms, expiresAt, out } = prepareMake(args, root, ctx.host, now); + const { terms, expiresAt, out } = makeTermsOf(args, now); if (out !== undefined && existsSync(out)) throw new UsageError(`${out} already exists; an offer file is never written over another`); - if (!jsonMode) { - ctx.output.stderr('\n' + header('Swap: make an offer') + '\n\n'); - ctx.output.stderr(keyValue('Network', target.network) + '\n'); - ctx.output.stderr(keyValue('Gives', legText(terms.give)) + '\n'); - ctx.output.stderr(keyValue('Wants', legText(terms.want)) + '\n\n'); - } - const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root, ctx.host); - const session = await payerFor('swap make', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); - try { - const spinner = spinnerFor('Making the offer (proving its half)...'); - const made = await makeOffer(session, await ctx.host.engines.for(session.network), root, address, terms, expiresAt, now); - const file = out ?? `offer-${made.envelope.id.slice(0, 16)}.json`; - writeFileSync(file, made.file, { flag: 'wx' }); - spinner.stop('Offer made'); - if (jsonMode) { - ctx.output.result({ subcommand: 'make', network: target.network, id: made.envelope.id, file, terms: termsJson(made.envelope.terms), expiresAt: expiresAt.toISOString() }); - return; - } - ctx.output.stdout(file + '\n'); - ctx.output.stderr('\n' + keyValue('Offer', made.envelope.id) + '\n'); - ctx.output.stderr(keyValue('File', file) + '\n'); - ctx.output.stderr(keyValue('Expires', expiresAt.toISOString()) + '\n'); - ctx.output.stderr('\n' + dim(' Hand the file to the taker. Its coins stay committed until it is taken.') + '\n\n'); - } finally { - await session.close(); + const made = await makeSwapOffer(ctx.host, { + ...paid, + payer: payerFor('swap make', ctx), + terms, + expiresAt, + now, + onProgress: (event) => { + if (event.kind !== 'swap-network') return showPaidStep(progress, event); + if (jsonMode) return; + ctx.output.stderr('\n' + header('Swap: make an offer') + '\n\n'); + ctx.output.stderr(keyValue('Network', event.network) + '\n'); + ctx.output.stderr(keyValue('Gives', legText(terms.give)) + '\n'); + ctx.output.stderr(keyValue('Wants', legText(terms.want)) + '\n\n'); + }, + }); + const file = out ?? `offer-${made.id.slice(0, 16)}.json`; + writeFileSync(file, made.file, { flag: 'wx' }); + if (jsonMode) { + ctx.output.result({ subcommand: 'make', network: made.network, id: made.id, file, terms: termsJson(made.terms), expiresAt: made.expiresAt.toISOString() }); + return; } + ctx.output.stdout(file + '\n'); + ctx.output.stderr('\n' + keyValue('Offer', made.id) + '\n'); + ctx.output.stderr(keyValue('File', file) + '\n'); + ctx.output.stderr(keyValue('Expires', made.expiresAt.toISOString()) + '\n'); + ctx.output.stderr('\n' + dim(' Hand the file to the taker. Its coins stay committed until it is taken.') + '\n\n'); return; } case 'inspect': { - const target = resolvePayingTarget(args, 'swap', 'inspect', root, ctx.host); - const offer = await readOfferArg(args, target); - const spinner = spinnerFor('Asking the indexer whether it is still live...'); - const { expired, spends } = await standingOf(offer, target.networkConfig, now, ctx.signal); - spinner.stop(spends.length === 0 ? 'Live' : 'Taken'); - const { envelope } = offer; + const standing = await inspectSwapOffer(ctx.host, { ...call, offer: readOfferText(args), now, onProgress: (event) => progress.report(event) }); if (jsonMode) { - ctx.output.result({ subcommand: 'inspect', network: target.network, id: envelope.id, terms: termsJson(envelope.terms), expiresAt: envelope.expiresAt.toISOString(), live: spends.length === 0, expired }); + ctx.output.result({ subcommand: 'inspect', network: standing.network, id: standing.id, terms: termsJson(standing.terms), expiresAt: standing.expiresAt.toISOString(), live: standing.live, expired: standing.expired }); return; } ctx.output.stderr('\n' + header('Swap offer') + '\n\n'); - ctx.output.stderr(keyValue('Offer', envelope.id) + '\n'); - ctx.output.stderr(keyValue('Network', envelope.network) + '\n'); - ctx.output.stderr(keyValue('Maker gives', legText(envelope.terms.give)) + '\n'); - ctx.output.stderr(keyValue('Maker wants', legText(envelope.terms.want)) + '\n'); - ctx.output.stderr(keyValue('Expires', `${envelope.expiresAt.toISOString()}${expired ? ' (expired)' : ''}`) + '\n'); - ctx.output.stderr(keyValue('Live', spends.length === 0 ? 'yes' : `no: taken in ${spends[0]!.transactionHash}`) + '\n\n'); + ctx.output.stderr(keyValue('Offer', standing.id) + '\n'); + ctx.output.stderr(keyValue('Network', standing.network) + '\n'); + ctx.output.stderr(keyValue('Maker gives', legText(standing.terms.give)) + '\n'); + ctx.output.stderr(keyValue('Maker wants', legText(standing.terms.want)) + '\n'); + ctx.output.stderr(keyValue('Expires', `${standing.expiresAt.toISOString()}${standing.expired ? ' (expired)' : ''}`) + '\n'); + ctx.output.stderr(keyValue('Live', standing.live ? 'yes' : `no: taken in ${standing.spends[0]!.transactionHash}`) + '\n\n'); return; } case 'take': { - const { target, offer, agreed } = await prepareTake(args, root, ctx.host, now); - if (!jsonMode) { - ctx.output.stderr('\n' + header('Swap: take an offer') + '\n\n'); - ctx.output.stderr(keyValue('Offer', offer.envelope.id) + '\n'); - ctx.output.stderr(keyValue('You pay', legText(agreed.want)) + '\n'); - ctx.output.stderr(keyValue('You get', legText(agreed.give)) + '\n\n'); - } - const session = await payerFor('swap take', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); - try { - const spinner = spinnerFor('Checking the offer, adding this half and proving the swap...'); - const txHash = await takeOffer(session, offer, agreed, target.networkConfig, now, ctx.signal); - spinner.update('Waiting for the indexer to list it...'); - const receipt = await receiptOf(target.networkConfig.indexer, txHash, ctx.signal); - spinner.stop('Swap submitted'); - if (jsonMode) { - ctx.output.result({ subcommand: 'take', network: target.network, id: offer.envelope.id, txHash, ...receiptJson(receipt) }); - return; - } - ctx.output.stdout(txHash + '\n'); - ctx.output.stderr('\n' + receiptText(receipt, txHash)); - ctx.output.stderr('\n' + dim(' Verify: midnight balance --shielded') + '\n\n'); - } finally { - await session.close(); + const agreed = termsOf(args); + const taken = await takeSwapOffer(ctx.host, { + ...paid, + payer: payerFor('swap take', ctx), + offer: readOfferText(args), + agreed, + now, + onProgress: (event) => { + if (event.kind !== 'offer-checked') return showPaidStep(progress, event); + if (jsonMode) return; + ctx.output.stderr('\n' + header('Swap: take an offer') + '\n\n'); + ctx.output.stderr(keyValue('Offer', event.id) + '\n'); + ctx.output.stderr(keyValue('You pay', legText(agreed.want)) + '\n'); + ctx.output.stderr(keyValue('You get', legText(agreed.give)) + '\n\n'); + }, + }); + const { txHash, receipt } = taken; + if (jsonMode) { + ctx.output.result({ subcommand: 'take', network: taken.network, id: taken.id, txHash, ...(receipt === undefined ? {} : receiptJson(receipt)) }); + return; } + ctx.output.stdout(txHash + '\n'); + if (receipt !== undefined) ctx.output.stderr('\n' + receiptText(receipt, txHash)); + ctx.output.stderr('\n' + dim(' Verify: midnight balance --shielded') + '\n\n'); return; } case 'cancel': { const id = args.positionals[0]; if (id === undefined) throw new UsageError('swap cancel needs the offer\'s id (8 characters of it at least): midnight swap cancel '); - const target = resolvePayingTarget(args, 'swap', 'cancel', root, ctx.host); - const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root, ctx.host); - const session = await payerFor('swap cancel', ctx).connect(target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, SHIELDED); - try { - const spinner = spinnerFor('Spending the offer\'s coins back to this wallet...'); - const outcome = await cancelOffer(session, root, target.networkConfig, address, id, ctx.signal); - if (outcome.txHash !== undefined) spinner.update('Waiting for the indexer to list it...'); - const receipt = outcome.txHash === undefined ? undefined : await receiptOf(target.networkConfig.indexer, outcome.txHash, ctx.signal); - spinner.stop(outcome.txHash === undefined ? 'It was taken already' : 'Offer cancelled'); - const offer = [...outcome.cancelled, ...outcome.alreadyTaken][0]!; - if (jsonMode) { - ctx.output.result({ subcommand: 'cancel', network: target.network, id: offer.id, cancelled: outcome.txHash !== undefined, txHash: outcome.txHash ?? null, ...(receipt === undefined ? {} : receiptJson(receipt)) }); - return; - } - if (outcome.txHash !== undefined) { - ctx.output.stdout(outcome.txHash + '\n'); - if (receipt !== undefined) ctx.output.stderr('\n' + receiptText(receipt, outcome.txHash) + '\n'); - } - else ctx.output.stderr('\n' + dim(` ${offer.id.slice(0, 16)}… was taken before it could be cancelled; it is closed.`) + '\n\n'); - } finally { - await session.close(); + const outcome = await cancelSwapOffer(ctx.host, { ...paid, payer: payerFor('swap cancel', ctx), id, onProgress: (event) => showPaidStep(progress, event) }); + const { txHash, receipt } = outcome; + if (jsonMode) { + ctx.output.result({ subcommand: 'cancel', network: outcome.network, id: outcome.id, cancelled: outcome.cancelled, txHash: txHash ?? null, ...(receipt === undefined ? {} : receiptJson(receipt)) }); + return; + } + if (txHash !== undefined) { + ctx.output.stdout(txHash + '\n'); + if (receipt !== undefined) ctx.output.stderr('\n' + receiptText(receipt, txHash) + '\n'); } + else ctx.output.stderr('\n' + dim(` ${outcome.id.slice(0, 16)}… was taken before it could be cancelled; it is closed.`) + '\n\n'); return; } case 'list': { - const target = resolvePayingTarget(args, 'swap', 'list', root, ctx.host); - const address = await walletAddress(resolveWalletPath(root, walletFlag), target.network, root, ctx.host); - const spinner = spinnerFor('Asking the indexer about each open offer...'); - const listed = await listOffers(root, target.network, target.networkConfig, address, now, ctx.signal); - spinner.stop(`${listed.length} offer${listed.length === 1 ? '' : 's'}`); + const { network, offers } = await listSwapOffers(ctx.host, { ...call, wallet: walletFlag, now, onProgress: (event) => progress.report(event) }); if (jsonMode) { ctx.output.result({ subcommand: 'list', - network: target.network, - offers: listed.map(({ offer, expired, taken }) => ({ id: offer.id, terms: termsJson(offer.terms), madeAt: offer.madeAt.toISOString(), expiresAt: offer.expiresAt.toISOString(), expired, taken })), + network, + offers: offers.map(({ offer, expired, taken }) => ({ id: offer.id, terms: termsJson(offer.terms), madeAt: offer.madeAt.toISOString(), expiresAt: offer.expiresAt.toISOString(), expired, taken })), }); return; } ctx.output.stderr('\n' + header('Swap offers') + '\n\n'); - if (listed.length === 0) ctx.output.stderr(dim(' No open offers.') + '\n\n'); - for (const { offer, expired, taken } of listed) { + if (offers.length === 0) ctx.output.stderr(dim(' No open offers.') + '\n\n'); + for (const { offer, expired, taken } of offers) { const status = taken ? 'taken' : expired ? 'expired (still takeable on chain until cancelled)' : 'open'; ctx.output.stderr(keyValue(offer.id.slice(0, 16) + '…', `${legText(offer.terms.give)} for ${legText(offer.terms.want)}, ${status}`) + '\n'); } diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index 67c49038..0172bf66 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -1,53 +1,66 @@ // Calling a circuit of a deployed contract: the call script, run against the // wallet the payer serves (served-wallet.ts). `mn contract call` calls through here. -import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; import { withServedWallet } from './served-wallet.ts'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { assertContractRunsOn, type ContractChecked } from './runtime-check.ts'; import type { ContractCallRequest } from './request.ts'; -export interface CallContractParams { +export interface CallContractOptions extends PaidCallOptions { + /** The circuit to call, on which contract (contractCallRequest). */ request: ContractCallRequest; - target: PayingTarget; - /** The wallet that pays; the active wallet when undefined. */ - wallet: string | undefined; - payer: Payer; - /** Starts the progress line for each step, given its first message. */ - progress: (message: string) => Spinner; - /** The paying call's SDK warnings, which a wallet served in this process keeps to. */ - sdkWarnings: CallSdkWarnings; - signal?: AbortSignal; } +/** A circuit called. */ export interface CalledCircuit { - contractName: string; - circuit: string; - address: string; - network: string; - status: string; + readonly network: NetworkName; + readonly contractName: string; + readonly circuit: string; + readonly address: string; + /** What the call script reports of the transaction (the SDK's status, e.g. "SucceedEntirely"). */ + readonly status: string; } -export async function callContract({ request, target, wallet, payer, progress, sdkWarnings, signal }: CallContractParams): Promise { +/** + * Calls the request's circuit on its deployed contract, paid by the payer's + * wallet: refuses a contract compiled for another runtime than the network's, + * then the payer checks its wallet has NIGHT and Dust, serves it, and the call + * script runs against it in the dApp's folder; the wallet stops being served + * whatever happens. + */ +export async function callContract(host: Host, options: CallContractOptions): Promise { + const { request, payer, wallet, signal, onProgress } = options; const { dappDir, info, address, circuit, callArgs } = request; + throwIfCancelled(signal); + const target = networkTargetOf(host, networkChoiceOf(options)); + const { network } = target; + await assertContractRunsOn(info, network, target.root, host.engines); + onProgress?.({ kind: 'contract-checked', network }); const { runCall } = await import('./runner.ts'); - return withServedWallet({ target, wallet, payer, progress, sdkWarnings, signal }, { running: `Calling ${circuit}...`, done: `${circuit} called`, failed: 'Call failed' }, async (servePort, spinner) => { - const result = await runCall({ - dappDir, - network: target.network, - root: target.root, - engines: target.host.engines, - networkConfig: target.networkConfig, - managedDir: info.managedDir, - contractName: info.name, - contractAddress: address, - circuit, - args: callArgs, - servePort, - onMessage: (msg) => spinner.update(msg), - signal, - }); - return { contractName: info.name, circuit, address, network: target.network, status: result.status }; - }); + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, (sdkWarnings) => + withServedWallet({ target, wallet, payer, progress: (message) => stepSpinner(onProgress, message), sdkWarnings, signal }, { running: `Calling ${circuit}...`, done: `${circuit} called`, failed: 'Call failed' }, async (servePort, spinner) => { + const result = await runCall({ + dappDir, + network, + root: target.root, + engines: host.engines, + networkConfig: target.networkConfig, + managedDir: info.managedDir, + contractName: info.name, + contractAddress: address, + circuit, + args: callArgs, + servePort, + onMessage: (msg) => spinner.update(msg), + signal, + }); + return { network, contractName: info.name, circuit, address, status: result.status }; + })); } diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index 9d56225d..5aa42e4c 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -1,50 +1,63 @@ // Deploying a compiled contract: the deploy script, run against the wallet // the payer serves (served-wallet.ts). `mn contract deploy` and `mn dev` both deploy through here. -import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; import { withServedWallet } from './served-wallet.ts'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { assertContractRunsOn, type ContractChecked } from './runtime-check.ts'; import type { ContractDeployRequest } from './request.ts'; -export interface DeployContractParams { +export interface DeployContractOptions extends PaidCallOptions { + /** What to deploy (contractDeployRequest). */ request: ContractDeployRequest; - target: PayingTarget; - /** The wallet that pays; the active wallet when undefined. */ - wallet: string | undefined; - payer: Payer; - /** Starts the progress line for each step, given its first message. */ - progress: (message: string) => Spinner; - /** The paying call's SDK warnings, which a wallet served in this process keeps to. */ - sdkWarnings: CallSdkWarnings; - signal?: AbortSignal; } +/** A deployed contract. */ export interface DeployedContract { - contractName: string; - address: string; - network: string; + readonly network: NetworkName; + readonly contractName: string; + /** The contract's address on the network, 64 hex characters. */ + readonly address: string; } -export async function deployContract({ request, target, wallet, payer, progress, sdkWarnings, signal }: DeployContractParams): Promise { +/** + * Deploys the request's contract on the network, paid by the payer's wallet: + * refuses a contract compiled for another runtime than the network's, then + * the payer checks its wallet has NIGHT and Dust, serves it, and the deploy + * script runs against it in the dApp's folder; the wallet stops being served + * whatever happens. + */ +export async function deployContract(host: Host, options: DeployContractOptions): Promise { + const { request, payer, wallet, signal, onProgress } = options; const { dappDir, info, constructorArgs, privateStateSecretKey } = request; + throwIfCancelled(signal); + const target = networkTargetOf(host, networkChoiceOf(options)); + const { network } = target; + await assertContractRunsOn(info, network, target.root, host.engines); + onProgress?.({ kind: 'contract-checked', network }); const { runDeploy } = await import('./runner.ts'); - return withServedWallet({ target, wallet, payer, progress, sdkWarnings, signal }, { running: 'Deploying contract...', done: 'Contract deployed', failed: 'Deploy failed' }, async (servePort, spinner) => { - const result = await runDeploy({ - dappDir, - network: target.network, - root: target.root, - engines: target.host.engines, - networkConfig: target.networkConfig, - managedDir: info.managedDir, - contractName: info.name, - servePort, - args: constructorArgs, - privateStateSecretKey, - onMessage: (msg) => spinner.update(msg), - signal, - }); - return { contractName: info.name, address: result.contractAddress, network: target.network }; - }); + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, (sdkWarnings) => + withServedWallet({ target, wallet, payer, progress: (message) => stepSpinner(onProgress, message), sdkWarnings, signal }, { running: 'Deploying contract...', done: 'Contract deployed', failed: 'Deploy failed' }, async (servePort, spinner) => { + const result = await runDeploy({ + dappDir, + network, + root: target.root, + engines: host.engines, + networkConfig: target.networkConfig, + managedDir: info.managedDir, + contractName: info.name, + servePort, + args: constructorArgs, + privateStateSecretKey, + onMessage: (msg) => spinner.update(msg), + signal, + }); + return { network, contractName: info.name, address: result.contractAddress }; + })); } diff --git a/src/lib/contract/request.ts b/src/lib/contract/request.ts index 0ef22669..ebd2e1c9 100644 --- a/src/lib/contract/request.ts +++ b/src/lib/contract/request.ts @@ -1,6 +1,8 @@ -// A contract deploy or call, read from its arguments and checked against the +// A contract deploy or call, built from plain values and checked against the // compiled contract before anything starts: the CLI checks it before the -// wallet syncs, the MCP server before it issues a confirmation token. +// wallet syncs, the MCP server before it issues a confirmation token. The +// argument readers below build the same from a command's flags, with the +// working directory the caller gives as their default folder. import { resolve } from 'node:path'; import { type ParsedArgs, getFlag, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; @@ -26,21 +28,25 @@ export interface ContractCallRequest { callArgs: unknown[]; } -/** - * Where contract-info.json is looked for: --managed (a managed// dir), - * else --path (the dApp root), else the working directory. --managed wins as - * the more specific of the two. - */ -export function resolveScanDir(args: ParsedArgs): string { - return resolve(getFlag(args, 'managed') ?? getFlag(args, 'path') ?? process.cwd()); +/** Where a contract is: its dApp, and the compiled contract in it. */ +export interface ContractLocation { + /** The dApp's root, where witnesses.js and the runner's cache are. */ + dappDir: string; + /** Where contract-info.json is looked for, when not in `dappDir`: a managed// folder, or a folder above one. */ + managedDir?: string; + /** Which of the dApp's compiled contracts, when it has more than one; the first by name when not given. */ + name?: string; } -/** `deploy [--args ] [--secret-key ]` for the contract found from --managed/--path. */ -export function resolveContractDeployRequest(args: ParsedArgs): ContractDeployRequest { - // --managed only says where contract-info.json lives; the runner still - // needs the project root (--path or cwd) for witnesses.js. - const dappDir = resolve(getFlag(args, 'path') ?? process.cwd()); - const { info } = findContractInfo(resolveScanDir(args), getFlag(args, 'name')); +/** + * A deploy of the compiled contract at `location`, its constructor given + * `args` in order. Refuses a contract that declares witnesses without a + * compiled witnesses.js in the dApp, and a `secretKey` that is not 32 bytes + * of hex. + */ +export function contractDeployRequest(location: ContractLocation & { args?: unknown[]; secretKey?: string }): ContractDeployRequest { + const { dappDir } = location; + const { info } = findContractInfo(location.managedDir ?? dappDir, location.name); // A contract that declares witnesses needs its compiled witnesses.js: without // it the SDK fails mid-deploy, after a long wait, with "first (witnesses) @@ -50,30 +56,77 @@ export function resolveContractDeployRequest(args: ParsedArgs): ContractDeployRe throw new Error(buildMissingWitnessError({ projectRoot: dappDir, witnessNames: declaredWitnesses })); } - const constructorArgs = parseArgsJson(getFlag(args, 'args')); - // For a contract whose constructor derives its owner from a witness // (owner = public_key(secret_key())); without it the owner comes from the deploy wallet. - const privateStateSecretKey = getFlag(args, 'secret-key'); + const privateStateSecretKey = location.secretKey; if (privateStateSecretKey !== undefined && !/^[0-9a-fA-F]{64}$/.test(privateStateSecretKey)) { throw new UsageError('--secret-key must be 32 bytes of hex (64 chars)'); } - return { dappDir, info, constructorArgs, privateStateSecretKey }; + return { dappDir, info, constructorArgs: location.args ?? [], privateStateSecretKey }; } -/** `call --address --circuit [--args ]` for the contract found from --managed/--path. */ -export function resolveContractCallRequest(args: ParsedArgs): ContractCallRequest { - const dappDir = resolve(getFlag(args, 'path') ?? process.cwd()); - const address = requireFlag(args, 'address', 'contract address'); - const circuit = requireFlag(args, 'circuit', 'circuit name'); - const { info } = findContractInfo(resolveScanDir(args), getFlag(args, 'name')); - const callArgs = parseArgsJson(getFlag(args, 'args')); +/** + * A call of `circuit` on the contract deployed at `address` (64 hex + * characters), compiled at `location`, given `args` in order. Refuses a + * circuit the contract can't call and a count of arguments it doesn't take. + */ +export function contractCallRequest(location: ContractLocation & { address: string; circuit: string; args?: unknown[] }): ContractCallRequest { + const { dappDir, address, circuit } = location; + const { info } = findContractInfo(location.managedDir ?? dappDir, location.name); + const callArgs = location.args ?? []; validateContractAddress(address); validateCallRequest(info, circuit, callArgs); return { dappDir, info, address, circuit, callArgs }; } +/** + * Where contract-info.json is looked for: --managed (a managed// dir), + * else --path (the dApp root), else `cwd`. --managed wins as the more + * specific of the two. + */ +export function resolveScanDir(args: ParsedArgs, cwd: string): string { + return resolve(cwd, getFlag(args, 'managed') ?? getFlag(args, 'path') ?? '.'); +} + +/** The dApp's root a command names: --path, else `cwd`. */ +export function resolveDappDir(args: ParsedArgs, cwd: string): string { + return resolve(cwd, getFlag(args, 'path') ?? '.'); +} + +/** --managed, read from `cwd`, when given. */ +function managedDirOf(args: ParsedArgs, cwd: string): string | undefined { + const managed = getFlag(args, 'managed'); + return managed === undefined ? undefined : resolve(cwd, managed); +} + +/** `deploy [--args ] [--secret-key ]` for the contract found from --managed/--path, else `cwd`. */ +export function resolveContractDeployRequest(args: ParsedArgs, cwd: string): ContractDeployRequest { + // --managed only says where contract-info.json lives; the runner still + // needs the project root (--path or cwd) for witnesses.js. + return contractDeployRequest({ + dappDir: resolveDappDir(args, cwd), + managedDir: managedDirOf(args, cwd), + name: getFlag(args, 'name'), + args: parseArgsJson(getFlag(args, 'args')), + secretKey: getFlag(args, 'secret-key'), + }); +} + +/** `call --address --circuit [--args ]` for the contract found from --managed/--path, else `cwd`. */ +export function resolveContractCallRequest(args: ParsedArgs, cwd: string): ContractCallRequest { + const address = requireFlag(args, 'address', 'contract address'); + const circuit = requireFlag(args, 'circuit', 'circuit name'); + return contractCallRequest({ + dappDir: resolveDappDir(args, cwd), + managedDir: managedDirOf(args, cwd), + name: getFlag(args, 'name'), + address, + circuit, + args: parseArgsJson(getFlag(args, 'args')), + }); +} + /** --args '': an array is passed positionally, an object as its values in order. */ function parseArgsJson(argsJson: string | undefined): unknown[] { if (!argsJson) return []; diff --git a/src/lib/contract/runtime-check.ts b/src/lib/contract/runtime-check.ts index d193dccb..7c905a25 100644 --- a/src/lib/contract/runtime-check.ts +++ b/src/lib/contract/runtime-check.ts @@ -8,6 +8,12 @@ import { sdkSetOf, type HostEngines } from '@kuiralabs/midnight-cli-core/lib/eng import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import type { ContractInfo } from './inspect.ts'; +/** A deploy's or call's contract runs on the network's runtime: paying for it starts next. */ +export interface ContractChecked { + readonly kind: 'contract-checked'; + readonly network: NetworkName; +} + /** * Throws a UsageError unless the engine of `engines` for `network` (by the * config under the state root `root`) runs a contract diff --git a/src/lib/contract/state.ts b/src/lib/contract/state.ts new file mode 100644 index 00000000..820b177c --- /dev/null +++ b/src/lib/contract/state.ts @@ -0,0 +1,106 @@ +// Reading a deployed contract's ledger state: parsed into its fields by the +// state script, run in the dApp's folder with its compiled contract, or, when +// that can't run (no compiled contract there, a script that fails), the +// untyped state tree the indexer holds for the address. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf, type NetworkChoice } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps, type ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { untilCancelled } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import { findContractInfo } from './inspect.ts'; +import { validateContractAddress } from './validate.ts'; + +/** The address is one and the network is known: the state is read next. */ +export interface StateReading { + readonly kind: 'state-reading'; + readonly network: NetworkName; +} + +/** The parsed state couldn't be read: the query's step ends here, and the raw state is read instead. */ +export interface StateFallback { + readonly kind: 'fallback'; + /** Why the state script didn't give the parsed state. */ + readonly reason: string; +} + +export interface ReadContractStateOptions extends NetworkChoice { + /** The dApp's root, where the state script runs. */ + dappDir: string; + /** Where contract-info.json is looked for, when not in `dappDir`. */ + scanDir?: string; + /** Which of the dApp's compiled contracts, when it has more than one. */ + name?: string; + /** The contract's address, 64 hex characters. */ + address: string; + /** Cancels the read: a call cancelled already starts nothing; one cancelled later stops with CancelledError, without the raw fallback. */ + signal?: AbortSignal; + /** Each step, in today's words for a person, and the read's own events. */ + onProgress?: (event: ProgressEvent | StateReading | StateFallback) => void; +} + +/** A contract's ledger state, parsed by its compiled contract: its scalar fields as text, its maps by size. */ +export interface ParsedContractState { + readonly kind: 'parsed'; + readonly network: NetworkName; + readonly address: string; + readonly fields: Record; + readonly maps: Record; +} + +/** A contract's untyped state tree, as the indexer holds it. */ +export interface RawContractState { + readonly kind: 'raw'; + readonly network: NetworkName; + readonly address: string; + readonly raw: RawStateValue; +} + +export type ContractState = ParsedContractState | RawContractState; + +/** + * The state of the contract at `address`: parsed by the compiled contract + * found from `scanDir` (else `dappDir`), or, when that fails, the raw state + * (a 'fallback' event says so first). No contract at the address fails. + */ +export async function readContractState(host: Host, options: ReadContractStateOptions): Promise { + const { dappDir, address, signal, onProgress } = options; + throwIfCancelled(signal); + validateContractAddress(address); + const { runState } = await import('./runner.ts'); + const { network, root, networkConfig } = networkTargetOf(host, networkChoiceOf(options)); + onProgress?.({ kind: 'state-reading', network }); + + const steps = progressSteps(onProgress); + steps.start('Querying contract state...'); + try { + const { info } = findContractInfo(options.scanDir ?? dappDir, options.name); + const { fields, maps } = await runState({ + dappDir, + network, + root, + engines: host.engines, + networkConfig, + managedDir: info.managedDir, + contractName: info.name, + contractAddress: address, + onMessage: (msg) => steps.update(msg), + signal, + }); + steps.done('State retrieved'); + return { kind: 'parsed', network, address, fields, maps }; + } catch (err) { + // A cancelled read stops here; it doesn't fall back to the raw state. + if (err instanceof CancelledError) throw err; + throwIfCancelled(signal); + onProgress?.({ kind: 'fallback', reason: err instanceof Error ? err.message : String(err) }); + } + + // The engine's query takes no signal: the call stops waiting for it when cancelled. + const raw = await untilCancelled((await host.engines.for(network)).contracts.rawState(networkConfig, address), signal); + if (!raw) throw new Error(`No contract found at address ${address} on ${network}`); + return { kind: 'raw', network, address, raw }; +} diff --git a/src/lib/dev/deploy.ts b/src/lib/dev/deploy.ts index ed3c8ba2..0fbeee5d 100644 --- a/src/lib/dev/deploy.ts +++ b/src/lib/dev/deploy.ts @@ -3,29 +3,31 @@ // wallets on the local network. What its steps say goes to `progress`; the // SDK's warnings go to the deploying call's `sdkWarnings`. -import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { deployContract, type DeployedContract } from '../contract/deploy.ts'; -import { resolveContractDeployRequest } from '../contract/request.ts'; -import { resolvePayingTarget, type Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { contractDeployRequest } from '../contract/request.ts'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -export async function deployDevContract(root: string, host: Host, projectRoot: string, wallet: string, network: string, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { - // The deploy as `mn contract deploy --path --wallet --network ` reads it. - const args: ParsedArgs = { - command: 'contract', - subcommand: 'deploy', - positionals: [], - flags: { path: projectRoot, wallet, network }, - }; - return deployContract({ - request: resolveContractDeployRequest(args), - target: resolvePayingTarget(args, 'contract', 'deploy', root, host), +/** + * Deploys the contract compiled in `projectRoot` on `network`, paid by + * `payer` from `wallet`. Every step reports on the one line `progress`: its + * updates, its end and its failure, as each step's own line would. + */ +export async function deployDevContract(host: Host, projectRoot: string, wallet: string, network: NetworkName, payer: Payer, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { + return deployContract(host, { + request: contractDeployRequest({ dappDir: projectRoot }), + network, wallet, payer, - progress: () => progress, sdkWarnings, signal, + onProgress: (event) => { + if (event.kind === 'update') progress.update(event.message); + else if (event.kind === 'done') progress.stop(event.message); + else if (event.kind === 'step-failed') progress.fail(event.message); + }, }); } diff --git a/src/lib/swap/cancel.ts b/src/lib/swap/cancel.ts new file mode 100644 index 00000000..9bf7e418 --- /dev/null +++ b/src/lib/swap/cancel.ts @@ -0,0 +1,64 @@ +// Cancelling a swap offer of the wallet's: its coins are spent back to the +// wallet, so no taker can take it any more. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { type Receipt, RECEIPT_WAIT_MS } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import type { PaidCallOptions } from '../wallet/paid-call.ts'; +import { receiptOfSubmitted } from '../wallet/submit-steps.ts'; +import { cancelOffer } from './offers.ts'; +import { offerWalletAddress, withSwapSession } from './swap-session.ts'; + +export interface CancelSwapOfferOptions extends PaidCallOptions { + /** The open offer's id, or 8 characters of it at least. */ + id: string; + /** How long to wait for the indexer to list the cancel, in milliseconds: RECEIPT_WAIT_MS when not given; 0 does not wait. */ + receiptWaitMs?: number; +} + +/** What cancelling did. */ +export interface CancelledSwapOffer { + readonly network: NetworkName; + /** The offer's full id. */ + readonly id: string; + /** Its coins were spent back to the wallet; false when it was found taken already (it is only closed in mn's record). */ + readonly cancelled: boolean; + /** The cancel's transaction, when one was needed. */ + readonly txHash?: string; + /** The cancel once the indexer lists it, or why it is missing; absent with no cancel, or when `receiptWaitMs` is 0. */ + readonly receipt?: Receipt; +} + +/** + * Cancels the payer's wallet's open offer `id` (a prefix of 8 characters at + * least names it): spends its coins back to the wallet, waits for the indexer + * to list the cancel, and closes the offer in mn's record. An offer found + * taken already is only closed. An id that names no open offer, or more than + * one, is refused. + */ +export async function cancelSwapOffer(host: Host, options: CancelSwapOfferOptions): Promise { + const { signal, onProgress } = options; + const receiptWaitMs = options.receiptWaitMs ?? RECEIPT_WAIT_MS; + throwIfCancelled(signal); + const target = networkTargetOf(host, networkChoiceOf(options)); + const { network, root, networkConfig } = target; + const address = await offerWalletAddress(host, root, options.wallet, network); + + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, (sdkWarnings) => withSwapSession(target, options, sdkWarnings, async (session) => { + const steps = progressSteps(onProgress); + steps.start('Spending the offer\'s coins back to this wallet...'); + const outcome = await cancelOffer(session, root, networkConfig, address, options.id, signal); + const { id } = [...outcome.cancelled, ...outcome.alreadyTaken][0]!; + if (outcome.txHash === undefined) { + steps.done('It was taken already'); + return { network, id, cancelled: false }; + } + const receipt = await receiptOfSubmitted(networkConfig.indexer, outcome.txHash, steps, signal, receiptWaitMs, 'Offer cancelled'); + return { network, id, cancelled: true, txHash: outcome.txHash, ...(receipt === undefined ? {} : { receipt }) }; + })); +} diff --git a/src/lib/swap/inspect.ts b/src/lib/swap/inspect.ts new file mode 100644 index 00000000..7448358e --- /dev/null +++ b/src/lib/swap/inspect.ts @@ -0,0 +1,57 @@ +// Inspecting a swap offer: what its file says, checked against its own bytes, +// and whether it is still live, asked of the indexer. No wallet opens. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf, type NetworkChoice } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps, type ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import type { SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import type { CoinSpend } from '@kuiralabs/midnight-chain/lib/offer-liveness'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import { readOfferFile, standingOf } from './offers.ts'; + +export interface InspectSwapOfferOptions extends NetworkChoice { + /** The offer file's text. */ + offer: string; + /** The time the expiry is read against; the time of the call when not given. */ + now?: Date; + /** Cancels the inspection: a call cancelled already starts nothing; one cancelled later stops with CancelledError. */ + signal?: AbortSignal; + /** Each step, in today's words for a person. */ + onProgress?: (event: ProgressEvent) => void; +} + +/** Where an offer stands. */ +export interface SwapOfferStanding { + readonly network: NetworkName; + readonly id: string; + /** What the maker gives and wants back, as the offer's bytes state them. */ + readonly terms: SwapTerms; + readonly expiresAt: Date; + /** Past the maker's expiry: takers using mn refuse it. */ + readonly expired: boolean; + /** None of its coins is spent: it can be taken. */ + readonly live: boolean; + /** The spends of its coins (it was taken, or its maker cancelled it); empty while it is live. */ + readonly spends: readonly CoinSpend[]; +} + +/** + * Reads the offer file's text for the network (refusing one for another + * network, or whose bytes say otherwise than the file), and asks the indexer + * whether its coins are spent. + */ +export async function inspectSwapOffer(host: Host, options: InspectSwapOfferOptions): Promise { + const { signal } = options; + const now = options.now ?? new Date(); + throwIfCancelled(signal); + const { network, root, networkConfig } = networkTargetOf(host, networkChoiceOf(options)); + const offer = await readOfferFile(root, options.offer, network, host.engines); + const steps = progressSteps(options.onProgress); + steps.start('Asking the indexer whether it is still live...'); + const { expired, spends } = await standingOf(offer, networkConfig, now, signal); + steps.done(spends.length === 0 ? 'Live' : 'Taken'); + const { envelope } = offer; + return { network, id: envelope.id, terms: envelope.terms, expiresAt: envelope.expiresAt, expired, live: spends.length === 0, spends }; +} diff --git a/src/lib/swap/list.ts b/src/lib/swap/list.ts new file mode 100644 index 00000000..1126c837 --- /dev/null +++ b/src/lib/swap/list.ts @@ -0,0 +1,43 @@ +// Listing a wallet's open swap offers, each asked of the indexer: the ones +// taken since are closed in mn's record. No wallet opens. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf, type NetworkChoice } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps, type ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import { listOffers, type ListedOffer } from './offers.ts'; +import { offerWalletAddress } from './swap-session.ts'; + +export interface ListSwapOffersOptions extends NetworkChoice { + /** mn's wallet whose offers to list, a name or a path; the active wallet when not given. */ + wallet?: string; + /** The time expiries are read against; the time of the call when not given. */ + now?: Date; + /** Cancels the listing: a call cancelled already starts nothing; one cancelled later stops with CancelledError. */ + signal?: AbortSignal; + /** Each step, in today's words for a person. */ + onProgress?: (event: ProgressEvent) => void; +} + +/** A wallet's open offers on a network. */ +export interface SwapOffersListed { + readonly network: NetworkName; + /** Each open offer, whether it is past its expiry, and whether it was taken since (then closed in mn's record). */ + readonly offers: readonly ListedOffer[]; +} + +/** The wallet's open offers on the network, each asked of the indexer; the ones taken since are closed in mn's record and listed as taken. */ +export async function listSwapOffers(host: Host, options: ListSwapOffersOptions = {}): Promise { + const { signal } = options; + const now = options.now ?? new Date(); + throwIfCancelled(signal); + const { network, root, networkConfig } = networkTargetOf(host, networkChoiceOf(options)); + const address = await offerWalletAddress(host, root, options.wallet, network); + const steps = progressSteps(options.onProgress); + steps.start('Asking the indexer about each open offer...'); + const offers = await listOffers(root, network, networkConfig, address, now, signal); + steps.done(`${offers.length} offer${offers.length === 1 ? '' : 's'}`); + return { network, offers }; +} diff --git a/src/lib/swap/make.ts b/src/lib/swap/make.ts new file mode 100644 index 00000000..d323c214 --- /dev/null +++ b/src/lib/swap/make.ts @@ -0,0 +1,65 @@ +// Making a swap offer: the maker's wallet proves its half, and the offer +// comes back as an offer file's text for the maker to hand to a taker. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import type { PaidCallOptions } from '../wallet/paid-call.ts'; +import { makeOffer } from './offers.ts'; +import { offerWalletAddress, withSwapSession } from './swap-session.ts'; + +/** The swap's network is known: its wallet opens next. */ +export interface SwapNetworkChosen { + readonly kind: 'swap-network'; + readonly network: NetworkName; +} + +export interface MakeSwapOfferOptions extends PaidCallOptions { + /** What the maker gives and wants back, each a shielded token and an amount of its smallest unit. */ + terms: SwapTerms; + /** When takers using mn stop taking the offer (the chain takes it until it is cancelled). */ + expiresAt: Date; + /** When the offer is made, as mn's record of the wallet's open offers keeps it; the time of the call when not given. */ + now?: Date; +} + +/** An offer made. */ +export interface MadeSwapOffer { + readonly network: NetworkName; + /** The offer's id, 64 hex characters (`swap cancel` takes 8 of them at least). */ + readonly id: string; + /** The terms as the offer's own bytes state them. */ + readonly terms: SwapTerms; + readonly expiresAt: Date; + /** The offer file's text, to hand to the taker. */ + readonly file: string; +} + +/** + * Makes a swap offer with the payer's wallet: proves its half of the swap + * (it gives `terms.give` and is paid `terms.want`), and records the offer + * among the wallet's open offers so its later spends don't cancel it unawares. + * Its coins stay committed until the offer is taken or cancelled. + */ +export async function makeSwapOffer(host: Host, options: MakeSwapOfferOptions): Promise { + const { terms, expiresAt, signal, onProgress } = options; + const now = options.now ?? new Date(); + throwIfCancelled(signal); + const target = networkTargetOf(host, networkChoiceOf(options)); + const { network, root } = target; + onProgress?.({ kind: 'swap-network', network }); + const address = await offerWalletAddress(host, root, options.wallet, network); + + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, (sdkWarnings) => withSwapSession(target, options, sdkWarnings, async (session) => { + const steps = progressSteps(onProgress); + steps.start('Making the offer (proving its half)...'); + const made = await makeOffer(session, await host.engines.for(session.network), root, address, terms, expiresAt, now); + steps.done('Offer made'); + return { network, id: made.envelope.id, terms: made.envelope.terms, expiresAt, file: made.file }; + })); +} diff --git a/src/lib/swap/request.ts b/src/lib/swap/request.ts index f5be0b6e..91bbf004 100644 --- a/src/lib/swap/request.ts +++ b/src/lib/swap/request.ts @@ -29,21 +29,38 @@ export function termsOf(args: ParsedArgs): SwapTerms { return terms; } -export interface MakeRequest { - target: PayingTarget; +/** What `swap make` asks for besides its network: the terms, the expiry, and where the offer file goes. */ +export interface MakeTerms { terms: SwapTerms; expiresAt: Date; /** Where to write the offer file; offer-.json in the working folder when not given. */ out: string | undefined; } -export function prepareMake(args: ParsedArgs, root: string, host: Host, now: Date): MakeRequest { +export interface MakeRequest extends MakeTerms { + target: PayingTarget; +} + +/** --expires-in seconds on from `now`, a day when not given. */ +function expiryOf(args: ParsedArgs, now: Date): Date { const lifetime = getFlag(args, 'expires-in') ?? String(DEFAULT_OFFER_LIFETIME_S); if (!/^[1-9][0-9]*$/.test(lifetime)) throw new UsageError(`--expires-in must be a whole number of seconds above 0, not "${lifetime}"`); + return new Date(now.getTime() + Number(lifetime) * 1000); +} + +/** The terms, the expiry from `now` and the offer file `swap make` names, without its network. */ +export function makeTermsOf(args: ParsedArgs, now: Date): MakeTerms { + const expiresAt = expiryOf(args, now); + return { terms: termsOf(args), expiresAt, out: getFlag(args, 'out') }; +} + +/** A make, checked as far as it can be without a wallet: the expiry, the network and the terms. */ +export function prepareMake(args: ParsedArgs, root: string, host: Host, now: Date): MakeRequest { + const expiresAt = expiryOf(args, now); return { target: resolvePayingTarget(args, 'swap', 'make', root, host), terms: termsOf(args), - expiresAt: new Date(now.getTime() + Number(lifetime) * 1000), + expiresAt, out: getFlag(args, 'out'), }; } @@ -54,17 +71,20 @@ export interface TakeRequest { agreed: SwapTerms; } -/** The offer file named by the first positional, read for the network. */ -export async function readOfferArg(args: ParsedArgs, target: PayingTarget): Promise { +/** The text of the offer file the first positional names. */ +export function readOfferText(args: ParsedArgs): string { const file = args.positionals[0]; if (file === undefined) throw new UsageError(`swap ${args.subcommand} needs the offer file: midnight swap ${args.subcommand} `); - let text: string; try { - text = readFileSync(file, 'utf-8'); + return readFileSync(file, 'utf-8'); } catch (err) { throw new UsageError(`Can't read the offer file ${file}: ${(err as Error).message}`); } - return readOfferFile(target.root, text, target.network, target.host.engines); +} + +/** The offer file named by the first positional, read for the network. */ +export async function readOfferArg(args: ParsedArgs, target: PayingTarget): Promise { + return readOfferFile(target.root, readOfferText(args), target.network, target.host.engines); } /** A take, checked as far as it can be without the chain: the file, its network, the agreed terms and the expiry. */ diff --git a/src/lib/swap/swap-session.ts b/src/lib/swap/swap-session.ts new file mode 100644 index 00000000..360a9860 --- /dev/null +++ b/src/lib/swap/swap-session.ts @@ -0,0 +1,34 @@ +// What the swap operations that open a wallet share: the wallet's address +// mn keeps its open offers under, and the payer's session with the shielded +// side synced, closed whatever happens. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { ConnectOptions, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; +import { resolveWalletPath, walletAddress } from '../wallet-config.ts'; +import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; + +// A swap spends shielded coins only: its wallet syncs the shielded side on every network, stagenet included. +const SHIELDED: ConnectOptions = { shielded: true }; + +/** The unshielded address on `network` of mn's wallet `wallet` (a name or path; the active one when not given), which keys its open offers. */ +export function offerWalletAddress(host: Host, root: string, wallet: string | undefined, network: NetworkName): Promise { + return walletAddress(resolveWalletPath(root, wallet), network, root, host); +} + +/** + * Runs `work` with the payer's wallet open as a session on the target's + * network, its shielded side synced; opening it is the step "Opening the + * wallet...". The session closes whatever happens, reverting what it built + * but never submitted. + */ +export async function withSwapSession(target: PayingTarget, options: PaidCallOptions, sdkWarnings: CallSdkWarnings, work: (session: WalletSession) => Promise): Promise { + const session = await options.payer.connect(target, options.wallet, stepSpinner(options.onProgress, 'Opening the wallet...'), sdkWarnings, options.signal, SHIELDED); + try { + return await work(session); + } finally { + await session.close(); + } +} diff --git a/src/lib/swap/take.ts b/src/lib/swap/take.ts new file mode 100644 index 00000000..fdc22821 --- /dev/null +++ b/src/lib/swap/take.ts @@ -0,0 +1,79 @@ +// Taking a swap offer: every check a taker makes passes before its wallet +// opens (the file is an offer for this network, its bytes say what it says, +// the terms are the agreed ones, the expiry hasn't passed), the wallet adds +// its half once the offer is found live, and the swap is submitted. + +import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import { progressSteps } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { checkTerms, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { assertOfferUnexpired } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; +import { type Receipt, RECEIPT_WAIT_MS } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import type { PaidCallOptions } from '../wallet/paid-call.ts'; +import { receiptOfSubmitted } from '../wallet/submit-steps.ts'; +import { readOfferFile, takeOffer } from './offers.ts'; +import { withSwapSession } from './swap-session.ts'; + +/** The offer is checked as far as it can be without the chain: the wallet opens next. */ +export interface SwapOfferChecked { + readonly kind: 'offer-checked'; + readonly network: NetworkName; + readonly id: string; + /** What the maker gives and wants back: the taker pays `want` and gets `give`. */ + readonly terms: SwapTerms; +} + +export interface TakeSwapOfferOptions extends PaidCallOptions { + /** The offer file's text. */ + offer: string; + /** The terms the taker agreed to, as the maker states them; an offer that says otherwise is refused. */ + agreed: SwapTerms; + /** The time the expiry is read against; the time of the call when not given. */ + now?: Date; + /** How long to wait for the indexer to list the swap, in milliseconds: RECEIPT_WAIT_MS when not given; 0 does not wait. */ + receiptWaitMs?: number; +} + +/** A swap submitted. */ +export interface TakenSwapOffer { + readonly network: NetworkName; + /** The offer's id. */ + readonly id: string; + /** The swap's transaction (`midnight tx status` takes it). */ + readonly txHash: string; + /** The swap once the indexer lists it, or why it is missing; absent when `receiptWaitMs` is 0. */ + readonly receipt?: Receipt; +} + +/** + * Takes the offer with the payer's wallet: refuses an offer for another + * network, one whose bytes say otherwise, other terms than `agreed` and an + * expired one before the wallet opens, then one whose coins are spent; adds + * the wallet's half and the fee, submits the swap, and waits for the indexer + * to list it. + */ +export async function takeSwapOffer(host: Host, options: TakeSwapOfferOptions): Promise { + const { agreed, signal, onProgress } = options; + const now = options.now ?? new Date(); + const receiptWaitMs = options.receiptWaitMs ?? RECEIPT_WAIT_MS; + throwIfCancelled(signal); + const target = networkTargetOf(host, networkChoiceOf(options)); + const { network, networkConfig } = target; + const offer = await readOfferFile(target.root, options.offer, network, host.engines); + checkTerms(offer.contents.terms, agreed); + assertOfferUnexpired(offer.envelope, now); + const { id } = offer.envelope; + onProgress?.({ kind: 'offer-checked', network, id, terms: offer.contents.terms }); + + return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, (sdkWarnings) => withSwapSession(target, options, sdkWarnings, async (session) => { + const steps = progressSteps(onProgress); + steps.start('Checking the offer, adding this half and proving the swap...'); + const txHash = await takeOffer(session, offer, agreed, networkConfig, now, signal); + const receipt = await receiptOfSubmitted(networkConfig.indexer, txHash, steps, signal, receiptWaitMs, 'Swap submitted'); + return { network, id, txHash, ...(receipt === undefined ? {} : { receipt }) }; + })); +} diff --git a/src/lib/wallet/paid-call.ts b/src/lib/wallet/paid-call.ts new file mode 100644 index 00000000..e9d06f49 --- /dev/null +++ b/src/lib/wallet/paid-call.ts @@ -0,0 +1,65 @@ +// What an operation paid through a payer takes besides its own inputs (a +// contract deploy or call, a swap), and the payer's steps said as progress +// events: a payer reports on a Spinner (payer.ts), which stepSpinner turns +// into the operation's events. + +import type { NetworkChoice } from '@kuiralabs/midnight-cli-core/lib/network-target'; +import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; +import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { Spinner, SpinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; + +/** A step ended in failure, saying so: the payer found no NIGHT, the script failed. The operation's error follows. */ +export interface StepFailed { + readonly kind: 'step-failed'; + readonly message: string; +} + +/** The network, the endpoints, the payer and what a call gives an operation it pays for; `Event` is what it says beyond its steps. */ +export interface PaidCallOptions extends NetworkChoice { + /** Pays: checks its wallet can, and serves or opens it (the CLI and the MCP server pass mn serve's). */ + payer: Payer; + /** The wallet the payer pays from, a name or a path; the active wallet when not given. */ + wallet?: string; + /** Cancels the operation: a call cancelled already starts nothing; one cancelled later stops with CancelledError. */ + signal?: AbortSignal; + /** Each step, in today's words for a person, a step that fails, and the operation's own events. */ + onProgress?: (event: ProgressEvent | StepFailed | Event) => void; + /** The call's SDK warnings, kept off the terminal while a wallet in this process runs; a call of the host's own when not given. */ + sdkWarnings?: CallSdkWarnings; +} + +/** + * A step that starts by saying `message`, as a Spinner for a payer to report + * on: its updates, its end (`stop`) and its failure (`fail`) go to + * `onProgress` as events. A step says nothing more once it has ended; `clear` + * ends it as `stop` does, and `log` says its line as an update. + */ +export function stepSpinner(onProgress: ((event: ProgressEvent | StepFailed) => void) | undefined, message: string): Spinner { + let current = message; + let ended = false; + const say = (text: string): void => { + if (ended) return; + current = text; + onProgress?.({ kind: 'update', message: text }); + }; + const end = (event: ProgressEvent | StepFailed): void => { + if (ended) return; + ended = true; + onProgress?.(event); + }; + onProgress?.({ kind: 'start', message }); + return { + update: say, + stop: (finalMessage) => end({ kind: 'done', message: finalMessage ?? current }), + fail: (finalMessage) => end({ kind: 'step-failed', message: finalMessage ?? current }), + log: say, + clear: () => end({ kind: 'done', message: current }), + }; +} + +/** Shows a paid operation's step on `reporter`'s spinners: a failed step ends with a failure mark. */ +export function showPaidStep(reporter: SpinnerReporter, event: ProgressEvent | StepFailed): void { + if (event.kind === 'step-failed') reporter.fail(event.message); + else reporter.report(event); +} diff --git a/src/lib/wallet/submit-steps.ts b/src/lib/wallet/submit-steps.ts index 9eeb1063..c1d60a55 100644 --- a/src/lib/wallet/submit-steps.ts +++ b/src/lib/wallet/submit-steps.ts @@ -29,14 +29,14 @@ export function submitSteps(steps: ProgressSteps): { onProving(): void; onSubmit /** * The submitted transaction `txHash` once the indexer at `indexer` lists it, * or why it is missing; undefined, without asking, when `waitMs` is 0. Then - * the step is done: "Transaction submitted". + * the step is done, saying `doneMessage`. */ -export async function receiptOfSubmitted(indexer: string, txHash: string, steps: ProgressSteps, signal: AbortSignal | undefined, waitMs: number): Promise { +export async function receiptOfSubmitted(indexer: string, txHash: string, steps: ProgressSteps, signal: AbortSignal | undefined, waitMs: number, doneMessage = 'Transaction submitted'): Promise { let receipt: Receipt | undefined; if (waitMs > 0) { steps.update('Waiting for the indexer to list it...'); receipt = await receiptOf(indexer, txHash, signal, waitMs); } - steps.done('Transaction submitted'); + steps.done(doneMessage); return receipt; } From e4bb20450df6184e280eacb6f5f86f1e93236e91 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 17:56:16 -0800 Subject: [PATCH 70/88] Named entry points for core, chain and the engines (3F, 1-4 of 10) Each public package states its API through named entry points, and the open "./*" goes: core "." (the library API), "./engine" (for engine implementors), "./ui" and "./commands"; chain "." and "./commands"; each engine "." only. Every importer uses them. Tests of a package's internals moved into that package (core 37, chain 12, engine-rc 24, engine-beta 6 test files), so no name is public only because a test needed it; suites both engines run, and the test host and stand-ins, sit in test-support/, which imports packages only by entry point. Published manifests carry no source paths: scripts/publish-manifest.mjs strips the development condition, and the release job publishes the tarball. The layering check resolves imports through exports maps and refuses a deep import across packages, in code, tests and scripts; the code scan and the API reports follow the entry points' re-exports. scripts/measure-preprod-dust.ts is removed (with the owner's word): it had not run since before phase 3. Suite 2911, beta 184; snapshot unchanged; fresh install, where a deep path into core, chain or an engine is refused (ERR_PACKAGE_PATH_NOT_EXPORTED); scratch chain final pass 84/84 in a clean runner, swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads. --- .github/workflows/release-sidecar.yml | 4 +- package.json | 4 +- packages/chain/api-report.md | 305 +- packages/chain/package.json | 13 +- .../__tests__/balance-subscription.test.ts | 6 +- .../chain/src}/__tests__/chain-clock.test.ts | 12 +- .../src}/__tests__/endpoint-check.test.ts | 4 +- .../src}/__tests__/endpoint-refusals.test.ts | 8 +- .../chain/src}/__tests__/event-tip.test.ts | 2 +- .../__tests__/graphql-ws-subscription.test.ts | 4 +- .../src}/__tests__/indexer-graphql.test.ts | 4 +- .../chain/src}/__tests__/ledger-guard.test.ts | 12 +- .../src}/__tests__/offer-liveness.test.ts | 4 +- .../src}/__tests__/read-cancellation.test.ts | 64 +- .../chain/src}/__tests__/tx-segments.test.ts | 4 +- .../chain/src/__tests__/tx-status.test.ts | 165 + packages/chain/src/commands.ts | 8 + packages/chain/src/commands/chain.codes.ts | 3 +- packages/chain/src/commands/chain.guidance.ts | 2 +- .../chain/src/commands/status.definition.ts | 4 +- packages/chain/src/commands/status.ts | 13 +- packages/chain/src/commands/tx.definition.ts | 4 +- packages/chain/src/commands/tx.ts | 9 +- packages/chain/src/index.ts | 25 + .../chain/src/lib/balance-subscription.ts | 7 +- packages/chain/src/lib/chain-clock.ts | 2 +- packages/chain/src/lib/chain-id.ts | 2 +- packages/chain/src/lib/endpoint-check.ts | 3 +- .../chain/src/lib/graphql-ws-subscription.ts | 3 +- packages/chain/src/lib/indexer-graphql.ts | 3 +- packages/chain/src/lib/indexer-ready.ts | 3 +- packages/chain/src/lib/ledger-guard.ts | 4 +- packages/chain/src/lib/node-ready.ts | 3 +- packages/chain/src/lib/node-rpc.ts | 3 +- packages/chain/src/lib/offer-liveness.ts | 2 +- packages/chain/src/lib/proof-server-ready.ts | 3 +- packages/chain/src/lib/tx-receipt.ts | 4 +- packages/chain/src/lib/tx-status.ts | 4 +- packages/chain/tsconfig.build.json | 4 + packages/cli-core/api-report.md | 2985 +++++++---------- packages/cli-core/package.json | 23 +- .../cli-core/src/__tests__/amount.test.ts | 93 +- .../cli-core/src}/__tests__/approval.test.ts | 15 +- .../cli-core/src}/__tests__/argv.test.ts | 4 +- .../src}/__tests__/blockfrost.test.ts | 14 +- .../src}/__tests__/cache-indexer.test.ts | 2 +- .../src}/__tests__/call-context.test.ts | 21 +- .../src}/__tests__/cli-config.test.ts | 17 +- .../cli-core/src}/__tests__/colors.test.ts | 9 +- .../src/__tests__/command-definition.test.ts | 92 + .../__tests__/dust-balancing-plan.test.ts | 2 +- .../__tests__/dust-registration-plan.test.ts | 10 +- .../cli-core/src}/__tests__/dust-wait.test.ts | 5 +- .../src}/__tests__/error-trim.test.ts | 2 +- .../src}/__tests__/exec-program.test.ts | 4 +- .../src}/__tests__/fee-limits.test.ts | 12 +- .../cli-core/src}/__tests__/format.test.ts | 6 +- .../cli-core/src}/__tests__/host.test.ts | 8 +- .../cli-core/src}/__tests__/keystore.test.ts | 2 +- .../src}/__tests__/local-stacks.test.ts | 35 +- .../cli-core/src}/__tests__/network.test.ts | 10 +- .../src}/__tests__/offer-envelope.test.ts | 10 +- .../src}/__tests__/open-offers.test.ts | 9 +- .../src}/__tests__/phase-tracker.test.ts | 2 +- .../src}/__tests__/resolve-network.test.ts | 8 +- .../src}/__tests__/sdk-errors.test.ts | 29 +- .../src}/__tests__/sdk-layout.test.ts | 2 +- .../src}/__tests__/sdk-warnings.test.ts | 2 +- .../src}/__tests__/shielded-policy.test.ts | 2 +- .../cli-core/src}/__tests__/sign-data.test.ts | 2 +- .../cli-core/src}/__tests__/sleep.test.ts | 4 +- .../src}/__tests__/spinner-reporter.test.ts | 4 +- .../src}/__tests__/swap-offer.test.ts | 11 +- .../src}/__tests__/terminal-prompter.test.ts | 8 +- .../src}/__tests__/transport-failure.test.ts | 12 +- .../cli-core/src}/__tests__/tx-serde.test.ts | 2 +- .../cli-core/src}/__tests__/verbose.test.ts | 2 +- .../src}/__tests__/wallet-cache.test.ts | 10 +- packages/cli-core/src/commands.ts | 7 + packages/cli-core/src/engine.ts | 47 + packages/cli-core/src/index.ts | 115 + packages/cli-core/src/lib/exec-program.ts | 17 +- packages/cli-core/src/lib/shielded-policy.ts | 2 +- packages/cli-core/src/ui.ts | 10 + packages/cli-core/tsconfig.build.json | 4 +- packages/engine-beta/api-report.md | 589 +--- packages/engine-beta/package.json | 5 - .../src/__tests__/dapp-connector.test.ts | 12 +- .../engine-beta/src/__tests__/engine.test.ts | 16 +- .../engine-beta/src/__tests__/host.test.ts | 10 +- .../src/__tests__/offer-reader.test.ts | 8 +- .../src/__tests__/shielded-direct.test.ts | 10 +- .../src/__tests__/stale-cache.test.ts | 15 + packages/engine-beta/src/addresses.ts | 4 +- packages/engine-beta/src/airdrop.ts | 8 +- .../engine-beta/src/contract-providers.ts | 5 +- packages/engine-beta/src/contract-scripts.ts | 4 +- packages/engine-beta/src/dapp-connector.ts | 30 +- packages/engine-beta/src/derive-address.ts | 4 +- packages/engine-beta/src/dust-direct-cache.ts | 4 +- packages/engine-beta/src/dust-direct.ts | 8 +- packages/engine-beta/src/dust-export.ts | 8 +- packages/engine-beta/src/dust-register.ts | 9 +- packages/engine-beta/src/dust-sync-native.ts | 8 +- packages/engine-beta/src/dust-wallet.ts | 3 +- packages/engine-beta/src/facade.ts | 17 +- packages/engine-beta/src/index.ts | 3 +- packages/engine-beta/src/ledger-parameters.ts | 2 +- packages/engine-beta/src/offer-reader.ts | 3 +- packages/engine-beta/src/raw-state.ts | 2 +- .../engine-beta/src/shielded-direct-cache.ts | 10 +- packages/engine-beta/src/shielded-direct.ts | 2 +- packages/engine-beta/src/transfer.ts | 35 +- packages/engine-beta/src/tx-inspect.ts | 2 +- .../engine-beta/src/wallet-data-repository.ts | 26 +- packages/engine-beta/src/wallet.ts | 21 +- packages/engine-beta/tsconfig.build.json | 4 + packages/engine-rc/api-report.md | 599 +--- packages/engine-rc/package.json | 5 - .../src}/__tests__/contract-raw-state.test.ts | 2 +- .../src/__tests__/contract-scripts.test.ts | 226 ++ .../src}/__tests__/dapp-connector.test.ts | 10 +- .../src}/__tests__/derive-address.test.ts | 4 +- .../src}/__tests__/dust-collapse.test.ts | 2 +- .../src}/__tests__/dust-direct-cache.test.ts | 5 +- .../src}/__tests__/dust-export.test.ts | 14 +- .../src}/__tests__/dust-logic.test.ts | 10 +- .../src}/__tests__/dust-sync-native.test.ts | 32 +- .../src}/__tests__/dust-wallet.test.ts | 8 +- .../engine-rc/src}/__tests__/facade.test.ts | 16 +- .../src}/__tests__/fee-only-check.test.ts | 4 +- .../src}/__tests__/fee-only-signing.test.ts | 6 +- .../__tests__/fixtures/dust-state-owned.ts | 0 .../fixtures/dust-state-two-coins.ts | 0 .../__tests__/helpers/dust-balancing-case.ts | 6 +- .../src}/__tests__/helpers/offline-facade.ts | 8 +- .../__tests__/helpers/sdk-dust-loop-canary.ts | 0 .../src}/__tests__/network-id.test.ts | 8 +- .../src}/__tests__/offer-reader.test.ts | 4 +- .../__tests__/repository-cancellation.test.ts | 52 + .../__tests__/shielded-direct-cache.test.ts | 5 +- .../src}/__tests__/shielded-direct.test.ts | 6 +- .../src}/__tests__/sign-recipe.test.ts | 8 +- .../src/__tests__/stale-cache.test.ts | 16 + .../engine-rc/src/__tests__/transfer.test.ts | 83 + .../__tests__/wallet-data-repository.test.ts | 11 +- .../src}/__tests__/wallet-session.test.ts | 46 +- .../wallet-state-to-restore.live.test.ts | 10 +- packages/engine-rc/src/addresses.ts | 4 +- packages/engine-rc/src/airdrop.ts | 8 +- packages/engine-rc/src/contract-providers.ts | 5 +- packages/engine-rc/src/contract-scripts.ts | 4 +- packages/engine-rc/src/dapp-connector.ts | 31 +- packages/engine-rc/src/derive-address.ts | 4 +- packages/engine-rc/src/dust-direct-cache.ts | 4 +- packages/engine-rc/src/dust-direct.ts | 8 +- packages/engine-rc/src/dust-export.ts | 8 +- packages/engine-rc/src/dust-register.ts | 9 +- packages/engine-rc/src/dust-sync-native.ts | 8 +- packages/engine-rc/src/dust-wallet.ts | 3 +- packages/engine-rc/src/facade.ts | 17 +- packages/engine-rc/src/index.ts | 3 +- packages/engine-rc/src/ledger-parameters.ts | 2 +- packages/engine-rc/src/offer-reader.ts | 3 +- packages/engine-rc/src/raw-state.ts | 2 +- .../engine-rc/src/shielded-direct-cache.ts | 10 +- packages/engine-rc/src/shielded-direct.ts | 2 +- packages/engine-rc/src/transfer.ts | 35 +- packages/engine-rc/src/tx-inspect.ts | 2 +- .../engine-rc/src/wallet-data-repository.ts | 26 +- packages/engine-rc/src/wallet.ts | 21 +- packages/engine-rc/tsconfig.build.json | 4 + scripts/api-report.mjs | 58 +- scripts/check-layering.d.mts | 32 +- scripts/check-layering.mjs | 374 ++- scripts/code-reach.mjs | 27 +- scripts/fresh-install-check.mjs | 30 +- scripts/measure-preprod-dust.ts | 95 - scripts/pack-release.mjs | 6 +- scripts/publish-manifest.d.mts | 7 + scripts/publish-manifest.mjs | 57 + src/__tests__/account-backup.test.ts | 4 +- src/__tests__/address-command.test.ts | 4 +- src/__tests__/agent-guidance.test.ts | 11 +- src/__tests__/airdrop-command.test.ts | 25 +- src/__tests__/balance-command.live.test.ts | 19 +- src/__tests__/balance-command.test.ts | 11 +- src/__tests__/cache-local-stacks.test.ts | 15 + src/__tests__/chain-reset-clearing.test.ts | 4 +- .../classify-reads-no-message.test.ts | 3 +- src/__tests__/command-cancellation.test.ts | 23 +- src/__tests__/command-flags.test.ts | 5 +- src/__tests__/command-registry.test.ts | 115 +- src/__tests__/config-command.test.ts | 10 +- src/__tests__/contract-deploy.test.ts | 4 +- src/__tests__/contract-lib.test.ts | 6 +- src/__tests__/contract-request.test.ts | 3 +- .../contract-runner-endpoints.test.ts | 13 +- src/__tests__/contract-runner.test.ts | 212 +- src/__tests__/contract-runtime-check.test.ts | 4 +- src/__tests__/contract-script-errors.test.ts | 6 +- .../contract-script-packages.test.ts | 46 +- src/__tests__/contract-validate.test.ts | 2 +- src/__tests__/declared-codes.test.ts | 30 +- src/__tests__/device-code.test.ts | 2 +- src/__tests__/dust-command.test.ts | 12 +- .../engine-beta-boundary-errors.test.ts | 2 +- .../engine-beta-error-code-parity.test.ts | 15 - src/__tests__/engine.test.ts | 15 +- src/__tests__/entry-points.test.ts | 31 + src/__tests__/error-code-docs.test.ts | 3 +- src/__tests__/error-code-parity.test.ts | 78 +- src/__tests__/error-code-registry.test.ts | 17 +- src/__tests__/exit-codes.test.ts | 14 +- .../fixtures/code-reach/barrel-handler.ts | 7 + .../fixtures/code-reach/barrel.definition.ts | 14 + src/__tests__/fixtures/code-reach/barrel.ts | 5 + .../fixtures/code-reach/fixture.definition.ts | 2 +- src/__tests__/fixtures/code-reach/refuses.ts | 2 +- src/__tests__/fixtures/code-reach/unpaid.ts | 7 + .../fixtures/layering/by-entry-point.ts | 6 + src/__tests__/fixtures/layering/by-path.ts | 6 + .../fixtures/layering/deep-import.ts | 7 + src/__tests__/fixtures/record-swap-offer.ts | 4 +- src/__tests__/generate-command.test.ts | 6 +- src/__tests__/genesis-address-command.test.ts | 4 +- src/__tests__/grant-account.test.ts | 4 +- src/__tests__/grant-deploy-cost.test.ts | 3 +- src/__tests__/grant-owner-commands.test.ts | 2 +- src/__tests__/grant-prepare.test.ts | 4 +- src/__tests__/grant-request.test.ts | 3 +- src/__tests__/heap-guard.test.ts | 6 +- src/__tests__/help-agent.test.ts | 6 +- src/__tests__/help.test.ts | 5 +- src/__tests__/helpers/cli-call.ts | 7 +- .../helpers/engine-boundary-suite.ts | 7 +- .../helpers/engine-transfer-suite.ts | 8 +- src/__tests__/helpers/expect-declared.ts | 6 +- src/__tests__/helpers/own-call.ts | 2 +- src/__tests__/helpers/plain-wallet.ts | 3 +- src/__tests__/helpers/serve-script-failure.ts | 2 +- src/__tests__/helpers/state-root-in.ts | 2 +- src/__tests__/host-engines.test.ts | 13 +- src/__tests__/host-paths.test.ts | 16 +- src/__tests__/host-slots.test.ts | 9 +- src/__tests__/info-command.test.ts | 8 +- src/__tests__/inspect-cost-command.test.ts | 8 +- src/__tests__/json-fields.test.ts | 3 +- src/__tests__/json-output.test.ts | 20 +- src/__tests__/layering.test.ts | 38 +- src/__tests__/localnet-cancellation.test.ts | 6 +- src/__tests__/localnet-command.test.ts | 5 +- src/__tests__/manual-command.test.ts | 2 +- src/__tests__/mcp-registry-tools.test.ts | 4 +- src/__tests__/mcp-server-advice.test.ts | 2 +- .../mcp-server-concurrent-calls.test.ts | 8 +- src/__tests__/mcp-server-progress.test.ts | 2 +- src/__tests__/mcp-server.test.ts | 2 +- src/__tests__/multi-wallet.test.ts | 22 +- src/__tests__/network-cancellation.test.ts | 7 +- src/__tests__/node-version.test.ts | 2 +- src/__tests__/notices.test.ts | 6 +- src/__tests__/passphrase.test.ts | 6 +- src/__tests__/payer.test.ts | 11 +- .../prep-runner-cancellation.test.ts | 4 +- src/__tests__/protect-account.test.ts | 3 +- src/__tests__/publish-manifest.test.ts | 48 + src/__tests__/run-command.test.ts | 15 +- src/__tests__/sealed-account.test.ts | 3 +- src/__tests__/sealed-wallet.test.ts | 10 +- src/__tests__/seed-resolver.test.ts | 6 +- src/__tests__/serve-command.test.ts | 4 +- src/__tests__/serve-manager.test.ts | 13 +- src/__tests__/settings.test.ts | 6 +- src/__tests__/state-root.test.ts | 18 +- src/__tests__/status.test.ts | 5 +- src/__tests__/swap-command.test.ts | 10 +- src/__tests__/swap-lib.test.ts | 17 +- src/__tests__/swap-request.test.ts | 14 +- src/__tests__/transfer-command.test.ts | 37 +- src/__tests__/transfer-request.test.ts | 16 +- src/__tests__/two-hosts.test.ts | 7 +- src/__tests__/tx-status.test.ts | 186 +- src/__tests__/verbose-per-call.test.ts | 26 +- src/__tests__/wallet-airdrop-lib.test.ts | 14 +- src/__tests__/wallet-balance-lib.test.ts | 29 +- src/__tests__/wallet-config.test.ts | 23 +- src/__tests__/wallet-create.test.ts | 6 +- src/__tests__/wallet-dust-lib.test.ts | 20 +- src/__tests__/wallet-protect.test.ts | 10 +- src/__tests__/wallet-transfer-lib.test.ts | 22 +- src/__tests__/ws-rpc.test.ts | 3 +- src/commands/address.definition.ts | 4 +- src/commands/address.ts | 8 +- src/commands/airdrop.definition.ts | 6 +- src/commands/airdrop.ts | 12 +- src/commands/balance.definition.ts | 6 +- src/commands/balance.ts | 12 +- src/commands/cache.definition.ts | 4 +- src/commands/cache.ts | 9 +- src/commands/connect.guidance.ts | 2 +- src/commands/contract.codes.ts | 3 +- src/commands/contract.definition.ts | 11 +- src/commands/contract.guidance.ts | 2 +- src/commands/contract.ts | 13 +- src/commands/dev.codes.ts | 3 +- src/commands/dev.definition.ts | 6 +- src/commands/dev.guidance.ts | 2 +- src/commands/dev.ts | 7 +- src/commands/dust.definition.ts | 6 +- src/commands/dust.ts | 13 +- src/commands/generate.definition.ts | 5 +- src/commands/generate.ts | 8 +- src/commands/genesis-address.definition.ts | 4 +- src/commands/genesis-address.ts | 8 +- src/commands/grant.codes.ts | 3 +- src/commands/grant.definition.ts | 6 +- src/commands/grant.guidance.ts | 2 +- src/commands/grant.ts | 11 +- src/commands/help.definition.ts | 4 +- src/commands/help.ts | 8 +- src/commands/info.definition.ts | 5 +- src/commands/info.ts | 8 +- src/commands/inspect-cost.definition.ts | 6 +- src/commands/inspect-cost.ts | 9 +- src/commands/localnet.definition.ts | 4 +- src/commands/localnet.ts | 18 +- src/commands/manual.definition.ts | 4 +- src/commands/manual.ts | 5 +- src/commands/serve.definition.ts | 6 +- src/commands/serve.ts | 17 +- src/commands/swap.definition.ts | 6 +- src/commands/swap.guidance.ts | 2 +- src/commands/swap.ts | 13 +- src/commands/test.definition.ts | 7 +- src/commands/test.ts | 13 +- src/commands/transfer.definition.ts | 6 +- src/commands/transfer.ts | 11 +- src/commands/wallet.codes.ts | 3 +- src/commands/wallet.definition.ts | 5 +- src/commands/wallet.guidance.ts | 2 +- src/commands/wallet.ts | 8 +- src/lib/agent-manual.ts | 3 +- src/lib/chain-caches.ts | 5 +- src/lib/chain-params.ts | 2 +- src/lib/cli-host.ts | 5 +- src/lib/code-tables.ts | 6 +- src/lib/command-dispatch.ts | 9 +- src/lib/contract/call.ts | 6 +- src/lib/contract/deploy.ts | 6 +- src/lib/contract/request.ts | 3 +- src/lib/contract/runner.ts | 6 +- src/lib/contract/runtime-check.ts | 4 +- src/lib/contract/served-wallet.ts | 6 +- src/lib/contract/state.ts | 8 +- src/lib/contract/validate.ts | 2 +- src/lib/dev/deploy.ts | 7 +- src/lib/dev/localnet-ready.ts | 4 +- src/lib/dev/provision-wallets.ts | 9 +- src/lib/grant/account-backup.ts | 5 +- src/lib/grant/account-records.ts | 2 +- src/lib/grant/account.ts | 4 +- src/lib/grant/deploy-cost.ts | 2 +- src/lib/grant/device-code.ts | 2 +- src/lib/grant/fee-wallet.ts | 6 +- src/lib/grant/owner-commands.ts | 2 +- src/lib/grant/prepare.ts | 5 +- src/lib/grant/protect-account.ts | 2 +- src/lib/grant/request.ts | 4 +- src/lib/grant/sealed-account.ts | 5 +- src/lib/heap-guard.ts | 6 +- src/lib/installed-commands.ts | 12 +- src/lib/installed-engines.ts | 3 +- src/lib/localnet.ts | 5 +- src/lib/mcp/known-params.ts | 2 +- src/lib/mcp/registry-tools.ts | 13 +- src/lib/mcp/server-advice.ts | 3 +- src/lib/mcp/skills.ts | 3 +- src/lib/output-redaction.ts | 2 +- src/lib/passphrase.ts | 7 +- src/lib/readme-commands.ts | 2 +- src/lib/run-command.ts | 6 +- src/lib/sdk-noise.ts | 2 +- src/lib/seed-resolver.ts | 5 +- src/lib/serve-manager.ts | 10 +- src/lib/serve-payer.ts | 9 +- src/lib/swap/cancel.ts | 9 +- src/lib/swap/inspect.ts | 9 +- src/lib/swap/list.ts | 6 +- src/lib/swap/make.ts | 8 +- src/lib/swap/offers.ts | 10 +- src/lib/swap/request.ts | 7 +- src/lib/swap/swap-session.ts | 6 +- src/lib/swap/take.ts | 11 +- src/lib/test/actions-runner.ts | 3 +- src/lib/test/ai-scaffold.ts | 2 +- src/lib/test/discovery.ts | 2 +- src/lib/test/prep-runner.ts | 10 +- src/lib/test/types.ts | 3 +- src/lib/transfer-request.ts | 7 +- src/lib/wallet-can-pay.ts | 10 +- src/lib/wallet-config.ts | 9 +- src/lib/wallet-create.ts | 4 +- src/lib/wallet-paths.ts | 3 +- src/lib/wallet-protector.ts | 3 +- src/lib/wallet/airdrop.ts | 14 +- src/lib/wallet/balance.ts | 11 +- src/lib/wallet/dust.ts | 11 +- src/lib/wallet/paid-call.ts | 7 +- src/lib/wallet/submit-steps.ts | 4 +- src/lib/wallet/transfer.ts | 13 +- src/lib/wallet/wallet-call.ts | 7 +- src/lib/ws-rpc.ts | 5 +- src/mcp-server.ts | 6 +- src/ui/animate.ts | 2 +- src/ui/dev-keys.ts | 2 +- src/ui/receipt.ts | 5 +- src/ui/test-create-prompt.ts | 2 +- src/wallet.ts | 10 +- .../capture-output.ts | 0 .../helpers => test-support}/closed-port.ts | 0 .../connector-stub.ts | 5 +- .../connector-suite.ts | 22 +- test-support/core-codes.ts | 14 + .../fixtures/ledger9-parameters.ts | 0 .../fixtures/swap-offer.ts | 0 test-support/fixtures/tx-status.ts | 17 + .../fixtures/zswap-events-localnet.json | 0 .../helpers => test-support}/ledger-tx.ts | 0 .../helpers => test-support}/local-indexer.ts | 2 +- .../offer-reader-suite.ts | 5 +- test-support/rc-engine.ts | 9 + .../shielded-direct-suite.ts | 2 +- .../stand-in-indexer.ts | 2 +- .../helpers => test-support}/test-host.ts | 6 +- tsconfig.json | 2 +- vitest.live.config.ts | 2 +- 437 files changed, 3959 insertions(+), 6022 deletions(-) rename {src => packages/chain/src}/__tests__/balance-subscription.test.ts (94%) rename {src => packages/chain/src}/__tests__/chain-clock.test.ts (82%) rename {src => packages/chain/src}/__tests__/endpoint-check.test.ts (95%) rename {src => packages/chain/src}/__tests__/endpoint-refusals.test.ts (89%) rename {src => packages/chain/src}/__tests__/event-tip.test.ts (98%) rename {src => packages/chain/src}/__tests__/graphql-ws-subscription.test.ts (97%) rename {src => packages/chain/src}/__tests__/indexer-graphql.test.ts (93%) rename {src => packages/chain/src}/__tests__/ledger-guard.test.ts (96%) rename {src => packages/chain/src}/__tests__/offer-liveness.test.ts (96%) rename {src => packages/chain/src}/__tests__/read-cancellation.test.ts (59%) rename {src => packages/chain/src}/__tests__/tx-segments.test.ts (96%) create mode 100644 packages/chain/src/__tests__/tx-status.test.ts create mode 100644 packages/chain/src/commands.ts create mode 100644 packages/chain/src/index.ts rename src/__tests__/transfer-lib.test.ts => packages/cli-core/src/__tests__/amount.test.ts (58%) rename {src => packages/cli-core/src}/__tests__/approval.test.ts (97%) rename {src => packages/cli-core/src}/__tests__/argv.test.ts (97%) rename {src => packages/cli-core/src}/__tests__/blockfrost.test.ts (92%) rename {src => packages/cli-core/src}/__tests__/cache-indexer.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/call-context.test.ts (90%) rename {src => packages/cli-core/src}/__tests__/cli-config.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/colors.test.ts (95%) create mode 100644 packages/cli-core/src/__tests__/command-definition.test.ts rename {src => packages/cli-core/src}/__tests__/dust-balancing-plan.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/dust-registration-plan.test.ts (89%) rename {src => packages/cli-core/src}/__tests__/dust-wait.test.ts (97%) rename {src => packages/cli-core/src}/__tests__/error-trim.test.ts (96%) rename {src => packages/cli-core/src}/__tests__/exec-program.test.ts (96%) rename {src => packages/cli-core/src}/__tests__/fee-limits.test.ts (90%) rename {src => packages/cli-core/src}/__tests__/format.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/host.test.ts (89%) rename {src => packages/cli-core/src}/__tests__/keystore.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/local-stacks.test.ts (85%) rename {src => packages/cli-core/src}/__tests__/network.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/offer-envelope.test.ts (86%) rename {src => packages/cli-core/src}/__tests__/open-offers.test.ts (84%) rename {src => packages/cli-core/src}/__tests__/phase-tracker.test.ts (97%) rename {src => packages/cli-core/src}/__tests__/resolve-network.test.ts (95%) rename {src => packages/cli-core/src}/__tests__/sdk-errors.test.ts (91%) rename {src => packages/cli-core/src}/__tests__/sdk-layout.test.ts (96%) rename {src => packages/cli-core/src}/__tests__/sdk-warnings.test.ts (98%) rename {src => packages/cli-core/src}/__tests__/shielded-policy.test.ts (94%) rename {src => packages/cli-core/src}/__tests__/sign-data.test.ts (95%) rename {src => packages/cli-core/src}/__tests__/sleep.test.ts (88%) rename {src => packages/cli-core/src}/__tests__/spinner-reporter.test.ts (94%) rename {src => packages/cli-core/src}/__tests__/swap-offer.test.ts (74%) rename {src => packages/cli-core/src}/__tests__/terminal-prompter.test.ts (92%) rename {src => packages/cli-core/src}/__tests__/transport-failure.test.ts (89%) rename {src => packages/cli-core/src}/__tests__/tx-serde.test.ts (95%) rename {src => packages/cli-core/src}/__tests__/verbose.test.ts (92%) rename {src => packages/cli-core/src}/__tests__/wallet-cache.test.ts (97%) create mode 100644 packages/cli-core/src/commands.ts create mode 100644 packages/cli-core/src/engine.ts create mode 100644 packages/cli-core/src/index.ts create mode 100644 packages/cli-core/src/ui.ts rename src/__tests__/engine-beta-dapp-connector.test.ts => packages/engine-beta/src/__tests__/dapp-connector.test.ts (82%) rename src/__tests__/engine-beta.test.ts => packages/engine-beta/src/__tests__/engine.test.ts (87%) rename src/__tests__/engine-beta-host.test.ts => packages/engine-beta/src/__tests__/host.test.ts (87%) rename src/__tests__/engine-beta-offer-reader.test.ts => packages/engine-beta/src/__tests__/offer-reader.test.ts (66%) rename src/__tests__/engine-beta-shielded-direct.test.ts => packages/engine-beta/src/__tests__/shielded-direct.test.ts (66%) create mode 100644 packages/engine-beta/src/__tests__/stale-cache.test.ts rename {src => packages/engine-rc/src}/__tests__/contract-raw-state.test.ts (96%) create mode 100644 packages/engine-rc/src/__tests__/contract-scripts.test.ts rename {src => packages/engine-rc/src}/__tests__/dapp-connector.test.ts (77%) rename {src => packages/engine-rc/src}/__tests__/derive-address.test.ts (97%) rename {src => packages/engine-rc/src}/__tests__/dust-collapse.test.ts (99%) rename {src => packages/engine-rc/src}/__tests__/dust-direct-cache.test.ts (98%) rename {src => packages/engine-rc/src}/__tests__/dust-export.test.ts (94%) rename {src => packages/engine-rc/src}/__tests__/dust-logic.test.ts (98%) rename {src => packages/engine-rc/src}/__tests__/dust-sync-native.test.ts (88%) rename {src => packages/engine-rc/src}/__tests__/dust-wallet.test.ts (97%) rename {src => packages/engine-rc/src}/__tests__/facade.test.ts (95%) rename {src => packages/engine-rc/src}/__tests__/fee-only-check.test.ts (98%) rename {src => packages/engine-rc/src}/__tests__/fee-only-signing.test.ts (97%) rename {src => packages/engine-rc/src}/__tests__/fixtures/dust-state-owned.ts (100%) rename {src => packages/engine-rc/src}/__tests__/fixtures/dust-state-two-coins.ts (100%) rename {src => packages/engine-rc/src}/__tests__/helpers/dust-balancing-case.ts (96%) rename {src => packages/engine-rc/src}/__tests__/helpers/offline-facade.ts (91%) rename {src => packages/engine-rc/src}/__tests__/helpers/sdk-dust-loop-canary.ts (100%) rename {src => packages/engine-rc/src}/__tests__/network-id.test.ts (87%) rename {src => packages/engine-rc/src}/__tests__/offer-reader.test.ts (59%) create mode 100644 packages/engine-rc/src/__tests__/repository-cancellation.test.ts rename {src => packages/engine-rc/src}/__tests__/shielded-direct-cache.test.ts (96%) rename {src => packages/engine-rc/src}/__tests__/shielded-direct.test.ts (63%) rename {src => packages/engine-rc/src}/__tests__/sign-recipe.test.ts (97%) create mode 100644 packages/engine-rc/src/__tests__/stale-cache.test.ts create mode 100644 packages/engine-rc/src/__tests__/transfer.test.ts rename {src => packages/engine-rc/src}/__tests__/wallet-data-repository.test.ts (98%) rename {src => packages/engine-rc/src}/__tests__/wallet-session.test.ts (85%) rename {src => packages/engine-rc/src}/__tests__/wallet-state-to-restore.live.test.ts (86%) delete mode 100644 scripts/measure-preprod-dust.ts create mode 100644 scripts/publish-manifest.d.mts create mode 100644 scripts/publish-manifest.mjs create mode 100644 src/__tests__/cache-local-stacks.test.ts delete mode 100644 src/__tests__/engine-beta-error-code-parity.test.ts create mode 100644 src/__tests__/entry-points.test.ts create mode 100644 src/__tests__/fixtures/code-reach/barrel-handler.ts create mode 100644 src/__tests__/fixtures/code-reach/barrel.definition.ts create mode 100644 src/__tests__/fixtures/code-reach/barrel.ts create mode 100644 src/__tests__/fixtures/code-reach/unpaid.ts create mode 100644 src/__tests__/fixtures/layering/by-entry-point.ts create mode 100644 src/__tests__/fixtures/layering/by-path.ts create mode 100644 src/__tests__/fixtures/layering/deep-import.ts create mode 100644 src/__tests__/publish-manifest.test.ts rename {src/__tests__/helpers => test-support}/capture-output.ts (100%) rename {src/__tests__/helpers => test-support}/closed-port.ts (100%) rename {src/__tests__/helpers => test-support}/connector-stub.ts (97%) rename {src/__tests__/helpers => test-support}/connector-suite.ts (98%) create mode 100644 test-support/core-codes.ts rename {src/__tests__ => test-support}/fixtures/ledger9-parameters.ts (100%) rename {src/__tests__ => test-support}/fixtures/swap-offer.ts (100%) create mode 100644 test-support/fixtures/tx-status.ts rename {src/__tests__ => test-support}/fixtures/zswap-events-localnet.json (100%) rename {src/__tests__/helpers => test-support}/ledger-tx.ts (100%) rename {src/__tests__/helpers => test-support}/local-indexer.ts (95%) rename {src/__tests__/helpers => test-support}/offer-reader-suite.ts (92%) create mode 100644 test-support/rc-engine.ts rename {src/__tests__/helpers => test-support}/shielded-direct-suite.ts (99%) rename {src/__tests__/helpers => test-support}/stand-in-indexer.ts (98%) rename {src/__tests__/helpers => test-support}/test-host.ts (68%) diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index ca863cfc..55ac1637 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -176,7 +176,9 @@ jobs: else # An engine ships the SDK set the tests ran on, for a program that installs it without mn. case "$name" in @kuiralabs/midnight-engine-*) node scripts/make-shrinkwrap.mjs --package "$dir" ;; esac - ( cd "$dir" && npm publish --access public ${{ env.PRERELEASE == 'true' && '--tag next' || '' }} ) + # Packed with the manifest it is published with: no exports entry names a source file. + tarball="$(node scripts/publish-manifest.mjs "$dir" "$RUNNER_TEMP/workspace-packs")" + npm publish "$tarball" --access public ${{ env.PRERELEASE == 'true' && '--tag next' || '' }} fi done # The tree the tests ran on, shipped with mn so a user's npm installs it diff --git a/package.json b/package.json index 1e7c15b6..0275c43b 100644 --- a/package.json +++ b/package.json @@ -55,8 +55,8 @@ "link": "bun link", "prepublishOnly": "npm run build && npm run test", "test": "vitest run", - "test:rc": "vitest run --exclude 'src/__tests__/engine-beta*.test.ts'", - "test:beta": "vitest run src/__tests__/engine-beta", + "test:rc": "vitest run --exclude 'src/__tests__/engine-beta*.test.ts' --exclude 'packages/engine-beta/**'", + "test:beta": "vitest run src/__tests__/engine-beta packages/engine-beta", "test:live": "vitest run --config vitest.live.config.ts", "test:watch": "vitest", "api-report": "node scripts/api-report.mjs write", diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md index 62ddf944..c557f8e7 100644 --- a/packages/chain/api-report.md +++ b/packages/chain/api-report.md @@ -1,220 +1,47 @@ # API report: @kuiralabs/midnight-chain -Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. -## `@kuiralabs/midnight-chain/commands/chain.codes` +## `@kuiralabs/midnight-chain` ```ts -export declare const chainCodes: readonly [ - { - readonly code: "UNSUPPORTED_LEDGER"; - readonly exitCode: 4; - readonly order: 150; - readonly summary: "The network is on ledger 8; this build supports ledger 9 only."; - readonly recovery: "Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry."; - }, - { - readonly code: "LOCAL_STACK_UNREACHABLE"; - readonly exitCode: 4; - readonly order: 170; - readonly summary: "No ledger-9 stack answers at the configured endpoints."; - readonly recovery: "Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints."; - }, - { - readonly code: "CHAIN_CLOCK_BEHIND"; - readonly exitCode: 4; - readonly order: 140; - readonly summary: "The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold."; - readonly recovery: "Wait for it to catch up, or ask the user to restart the local chain."; - } -]; -export declare const READS_CHAIN: import("@kuiralabs/midnight-cli-core/lib/error-codes").CodeSet; -``` - -## `@kuiralabs/midnight-chain/commands/chain.guidance` - -```ts -import { type PackageGuidance } from "@kuiralabs/midnight-cli-core/lib/agent-guidance"; -export declare const chainGuidance: PackageGuidance; -``` - -## `@kuiralabs/midnight-chain/commands/status` - -```ts -import { type ParsedArgs } from "@kuiralabs/midnight-cli-core/lib/argv"; -import type { CallContext, CommandOutcome } from "@kuiralabs/midnight-cli-core/lib/call-context"; -export default function statusCommand(args: ParsedArgs, ctx: CallContext): Promise; -``` - -## `@kuiralabs/midnight-chain/commands/status.definition` - -```ts -import type { CommandDefinition } from "@kuiralabs/midnight-cli-core/lib/command-definition"; -export declare const statusDefinition: CommandDefinition; -``` - -## `@kuiralabs/midnight-chain/commands/tx` - -```ts -import { type ParsedArgs } from "@kuiralabs/midnight-cli-core/lib/argv"; -import type { CallContext } from "@kuiralabs/midnight-cli-core/lib/call-context"; -export default function txCommand(args: ParsedArgs, ctx: CallContext): Promise; -``` - -## `@kuiralabs/midnight-chain/commands/tx.definition` - -```ts -import { type CommandDefinition } from "@kuiralabs/midnight-cli-core/lib/command-definition"; -export declare const txDefinition: CommandDefinition; -``` - -## `@kuiralabs/midnight-chain/lib/balance-subscription` - -```ts -export type { BalanceSummary } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { BalanceSummary } from "@kuiralabs/midnight-cli-core/lib/engine"; +export type { BalanceSummary } from '@kuiralabs/midnight-cli-core'; export declare function checkBalance(address: string, indexerWS: string, onProgress?: (current: number, highest: number) => void, signal?: AbortSignal): Promise; export declare function isNativeToken(tokenType: string): boolean; -``` - -## `@kuiralabs/midnight-chain/lib/chain-clock` - -```ts -export declare const CHAIN_CLOCK_TOLERANCE_MS: number; -export declare function fetchChainTime(indexerHttpUrl: string): Promise; +export declare function assertChainClockCurrent(chainTime: Date, now: Date): void; export declare class ChainClockBehindError extends Error { readonly code = "CHAIN_CLOCK_BEHIND"; constructor(chainTime: Date, now: Date); } -export declare function assertChainClockCurrent(chainTime: Date, now: Date): void; -``` - -## `@kuiralabs/midnight-chain/lib/chain-id` - -```ts +export declare function fetchChainTime(indexerHttpUrl: string): Promise; export declare function getChainGenesisHash(nodeWsUrl: string, signal?: AbortSignal): Promise; -export declare function clearChainIdMemo(): void; -``` - -## `@kuiralabs/midnight-chain/lib/endpoint-check` - -```ts -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare function assertNetworkAnswers(network: Pick, request?: typeof fetch): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/event-tip` - -```ts -export type LedgerEventStream = "dust" | "zswap"; +export declare function assertNetworkAnswers(network: Pick, request?: typeof fetch): Promise; export declare function fetchEventTip(indexerWS: string, stream: LedgerEventStream): Promise; -export declare function isStreamEmpty(indexerWS: string, stream: LedgerEventStream): Promise; export declare function isCursorBeyondTip(lastAppliedEventId: number, tip: number | null): boolean; -``` - -## `@kuiralabs/midnight-chain/lib/graphql-ws-subscription` - -```ts -export type WsFinishReason = "caught-up" | "complete" | "idle" | "initial-silence" | "graceful-close" | "closed-early" | "timeout"; -export interface GraphqlWsSubscription { - query: string; - variables: Record; - onNext: (data: unknown) => boolean; - buildResult: (partial: boolean, reason: WsFinishReason) => TResult; - timeoutMs: number; - idleMs: number; - idleBeforeFirstEvent?: boolean; - initialSilenceMs?: number; - signal?: AbortSignal; -} +export declare function isStreamEmpty(indexerWS: string, stream: LedgerEventStream): Promise; +export type LedgerEventStream = 'dust' | 'zswap'; export declare function subscribeGraphqlWs(wsUrl: string, sub: GraphqlWsSubscription): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/indexer-graphql` - -```ts -export declare class IndexerQueryError extends Error { - constructor(reason: string, options?: { - cause?: unknown; - }); -} -export declare class IndexerUnreachableError extends IndexerQueryError { - readonly code = "NETWORK_ERROR"; - constructor(reason: string, options?: { - cause?: unknown; - }); -} export declare function queryIndexer(indexerHttpUrl: string, query: string, variables: Record | undefined, timeoutMs: number, signal?: AbortSignal): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/indexer-ready` - -```ts -export interface WaitForIndexerOptions { - timeoutMs?: number; - pollIntervalMs?: number; - signal?: AbortSignal; -} export declare function waitForAddressFunded(indexerWS: string, address: string, opts?: WaitForIndexerOptions): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/ledger-guard` - -```ts -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare class UnsupportedLedgerError extends Error { - readonly code = "UNSUPPORTED_LEDGER"; - constructor(network: string, protocolVersion: bigint); -} -export declare function checkLedgerSupported(network: string, protocolVersion: bigint | null): void; -export declare function fetchProtocolVersion(indexerHttpUrl: string, signal?: AbortSignal): Promise; +export declare function assertLedger9StackReachable(networkName: string, network: NetworkConfig, probes?: StackProbes): Promise; export declare function assertLedgerSupported(networkName: string, network: NetworkConfig, fetchVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise, signal?: AbortSignal): Promise; +export declare function fetchProtocolVersion(indexerHttpUrl: string, signal?: AbortSignal): Promise; export declare class LocalStackUnreachableError extends Error { readonly code = "LOCAL_STACK_UNREACHABLE"; - constructor(component: "indexer" | "node", url: string); + constructor(component: 'indexer' | 'node', url: string); } -export interface StackProbes { - fetchVersion?: (indexerHttpUrl: string) => Promise; - fetchGenesis?: (nodeWsUrl: string) => Promise; +export declare class UnsupportedLedgerError extends Error { + readonly code = "UNSUPPORTED_LEDGER"; + constructor(network: string, protocolVersion: bigint); } -export declare function assertLedger9StackReachable(networkName: string, network: NetworkConfig, probes?: StackProbes): Promise; -type WalletKind = "shielded" | "unshielded" | "dust"; export declare function walletsBelowLedger9(versions: Readonly>): WalletKind[]; -``` - -## `@kuiralabs/midnight-chain/lib/node-ready` - -```ts -export interface WaitForFirstBlockOptions { - timeoutMs?: number; - pollIntervalMs?: number; - signal?: AbortSignal; -} export declare function waitForFirstBlock(nodeWsUrl: string, opts?: WaitForFirstBlockOptions): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/node-rpc` - -```ts -export interface RpcOptions { - url: string; - timeoutMs?: number; - signal?: AbortSignal; -} export declare function callNodeRpc(opts: RpcOptions, method: string, params?: unknown[]): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/offer-liveness` - -```ts export interface CoinSpend { nullifier: string; transactionHash: string; blockHeight: number; } -export declare class LivenessUnknownError extends Error { - constructor(reason: string); -} export declare function spendsOf(indexer: { indexer: string; indexerWS: string; @@ -222,25 +49,7 @@ export declare function spendsOf(indexer: { fromBlock?: number; signal?: AbortSignal; }): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/proof-server-ready` - -```ts -export interface WaitForProofServerOptions { - timeoutMs?: number; - pollIntervalMs?: number; - requestTimeoutMs?: number; - signal?: AbortSignal; -} export declare function waitForProofServerReady(proofServerUrl: string, opts?: WaitForProofServerOptions): Promise; -``` - -## `@kuiralabs/midnight-chain/lib/tx-receipt` - -```ts -import { type FinalTransaction, type TransactionStatus } from "./tx-status.ts"; -export declare const RECEIPT_WAIT_MS = 60000; export type Receipt = { readonly listed: true; readonly transaction: FinalTransaction; @@ -248,67 +57,45 @@ export type Receipt = { readonly listed: false; readonly reason: string; }; -export declare function receiptOf(indexerHttpUrl: string, txId: string, signal?: AbortSignal, waitMs?: number): Promise; -export declare function finalTransactionJson(tx: FinalTransaction): Record; -export declare function transactionStatusJson(status: TransactionStatus): Record; +export declare const RECEIPT_WAIT_MS = 60000; export declare function receiptJson(receipt: Receipt): Record; -``` - -## `@kuiralabs/midnight-chain/lib/tx-segments` - -```ts +export declare function receiptOf(indexerHttpUrl: string, txId: string, signal?: AbortSignal, waitMs?: number): Promise; +export declare function fetchPartialSuccessSegments(indexerHttpUrl: string, txHash: string): Promise; export interface SegmentResult { id: number; success: boolean; } -export declare class SegmentResultsUnavailableError extends Error { - constructor(txHash: string, reason: string); -} -export declare function fetchPartialSuccessSegments(indexerHttpUrl: string, txHash: string): Promise; +export declare function transactionStatus(options: TransactionStatusOptions): Promise; ``` -## `@kuiralabs/midnight-chain/lib/tx-status` +## `@kuiralabs/midnight-chain/commands` ```ts -import { type ProgressListener } from "@kuiralabs/midnight-cli-core/lib/progress"; -export declare const TX_STATUS_WAIT_MS = 120000; -export type TxReference = { - hash: string; -} | { - identifier: string; -}; -export type TxResultStatus = "SUCCESS" | "PARTIAL_SUCCESS" | "FAILURE"; -export interface FinalTransaction { - readonly state: "final"; - readonly kind: "regular" | "system"; - readonly hash: string; - readonly identifiers: readonly string[]; - readonly result?: TxResultStatus; - readonly segments?: ReadonlyArray<{ - id: number; - success: boolean; - }>; - readonly feeSpecks?: bigint; - readonly block: { - readonly height: number; - readonly hash: string; - readonly time: Date; - }; -} -export interface UnknownTransaction { - readonly state: "notFound"; -} -export type TransactionStatus = FinalTransaction | UnknownTransaction; -export declare function parseTxReference(text: string): TxReference; -export declare function fetchTransactionStatus(indexerHttpUrl: string, ref: TxReference, signal?: AbortSignal): Promise; -export declare function waitForTransactionStatus(indexerHttpUrl: string, ref: TxReference, timeoutMs: number, signal?: AbortSignal, intervalMs?: number): Promise; -export interface TransactionStatusOptions { - indexer: string; - ref: TxReference; - wait?: boolean; - timeoutMs?: number; - signal?: AbortSignal; - onProgress?: ProgressListener; -} -export declare function transactionStatus(options: TransactionStatusOptions): Promise; +export declare const chainCodes: readonly [ + { + readonly code: "UNSUPPORTED_LEDGER"; + readonly exitCode: 4; + readonly order: 150; + readonly summary: "The network is on ledger 8; this build supports ledger 9 only."; + readonly recovery: "Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry."; + }, + { + readonly code: "LOCAL_STACK_UNREACHABLE"; + readonly exitCode: 4; + readonly order: 170; + readonly summary: "No ledger-9 stack answers at the configured endpoints."; + readonly recovery: "Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints."; + }, + { + readonly code: "CHAIN_CLOCK_BEHIND"; + readonly exitCode: 4; + readonly order: 140; + readonly summary: "The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold."; + readonly recovery: "Wait for it to catch up, or ask the user to restart the local chain."; + } +]; +export declare const READS_CHAIN: import("@kuiralabs/midnight-cli-core").CodeSet; +export declare const chainGuidance: PackageGuidance; +export declare const statusDefinition: CommandDefinition; +export declare const txDefinition: CommandDefinition; ``` diff --git a/packages/chain/package.json b/packages/chain/package.json index 5ce3f714..31ff0d73 100644 --- a/packages/chain/package.json +++ b/packages/chain/package.json @@ -17,10 +17,15 @@ "node": ">=22" }, "exports": { - "./*": { - "midnight-cli-source": "./src/*.ts", - "types": "./dist/*.d.ts", - "default": "./dist/*.js" + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" } }, "files": [ diff --git a/src/__tests__/balance-subscription.test.ts b/packages/chain/src/__tests__/balance-subscription.test.ts similarity index 94% rename from src/__tests__/balance-subscription.test.ts rename to packages/chain/src/__tests__/balance-subscription.test.ts index 65bf2536..0c5a8bf9 100644 --- a/src/__tests__/balance-subscription.test.ts +++ b/packages/chain/src/__tests__/balance-subscription.test.ts @@ -3,7 +3,7 @@ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; import { EventEmitter } from 'events'; -import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core'; type FakeWs = EventEmitter & { send: ReturnType; @@ -28,9 +28,9 @@ vi.mock('ws', async () => { return { default: WS }; }); -let checkBalance: typeof import('@kuiralabs/midnight-chain/lib/balance-subscription').checkBalance; +let checkBalance: typeof import('../lib/balance-subscription.ts').checkBalance; beforeAll(async () => { - ({ checkBalance } = await import('@kuiralabs/midnight-chain/lib/balance-subscription')); + ({ checkBalance } = await import('../lib/balance-subscription.ts')); }); const OTHER_TOKEN = 'ff'.repeat(32); diff --git a/src/__tests__/chain-clock.test.ts b/packages/chain/src/__tests__/chain-clock.test.ts similarity index 82% rename from src/__tests__/chain-clock.test.ts rename to packages/chain/src/__tests__/chain-clock.test.ts index f50c2375..c1d4693b 100644 --- a/src/__tests__/chain-clock.test.ts +++ b/packages/chain/src/__tests__/chain-clock.test.ts @@ -3,10 +3,12 @@ // clock read 02:33 UTC: about 14 hours behind. import { afterEach, describe, expect, it } from 'vitest'; -import { ChainClockBehindError, CHAIN_CLOCK_TOLERANCE_MS, assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; -import { classifyError, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { ChainClockBehindError, CHAIN_CLOCK_TOLERANCE_MS, assertChainClockCurrent, fetchChainTime } from '../lib/chain-clock.ts'; +import { classifyError, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCodes } from '../commands/chain.codes.ts'; +import { codeRegistry } from '../../../../test-support/core-codes.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../../../test-support/local-indexer.ts'; const LAGGING_BLOCK = 1_791_116_964_002; // 2026-10-04T12:29:24.002Z const WALL = new Date('2026-10-05T02:33:00.000Z'); @@ -37,7 +39,7 @@ describe('assertChainClockCurrent', () => { + '2026-10-04T12:29:24.002Z). Dust is generated in chain time, so a registration now would be refused for an unpaid fee. ' + 'A local chain falls behind like this after the machine sleeps and catches up as it produces blocks: run midnight dust ' + 'register again once it has, or restart the local chain.'); - expect(classifyError(err, installedCommands)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode: 'CHAIN_CLOCK_BEHIND' }); + expect(classifyError(err, codeRegistry(coreCodes, chainCodes))).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode: 'CHAIN_CLOCK_BEHIND' }); }); it('accepts a chain within the tolerance, or ahead', () => { diff --git a/src/__tests__/endpoint-check.test.ts b/packages/chain/src/__tests__/endpoint-check.test.ts similarity index 95% rename from src/__tests__/endpoint-check.test.ts rename to packages/chain/src/__tests__/endpoint-check.test.ts index 7687443c..e098a04f 100644 --- a/src/__tests__/endpoint-check.test.ts +++ b/packages/chain/src/__tests__/endpoint-check.test.ts @@ -1,8 +1,8 @@ // What is asked of a network's endpoints before a wallet sync starts. import { describe, expect, it } from 'vitest'; -import { BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; +import { BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core'; +import { assertNetworkAnswers } from '../lib/endpoint-check.ts'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const LOCAL = { indexer: 'http://localhost:8088/api/v4/graphql', indexerWS: 'ws://localhost:8088/api/v4/graphql/ws', node: 'ws://localhost:9944' }; diff --git a/src/__tests__/endpoint-refusals.test.ts b/packages/chain/src/__tests__/endpoint-refusals.test.ts similarity index 89% rename from src/__tests__/endpoint-refusals.test.ts rename to packages/chain/src/__tests__/endpoint-refusals.test.ts index 9d714a2e..bac0b182 100644 --- a/src/__tests__/endpoint-refusals.test.ts +++ b/packages/chain/src/__tests__/endpoint-refusals.test.ts @@ -5,10 +5,10 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import * as http from 'node:http'; import type { AddressInfo } from 'node:net'; -import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; -import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; +import { checkBalance } from '../lib/balance-subscription.ts'; +import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; +import { callNodeRpc } from '../lib/node-rpc.ts'; +import { BlockfrostProjectIdRequiredError, EndpointShutDownError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core'; const NO_ID = blockfrostEndpoints('preprod', undefined); const ADDRESS = 'mn_addr_preprod1m5cjx3u3hmfhm5268muqp499y82e3fuxj65jpqq7sd0r9x07n3fqk36yhe'; diff --git a/src/__tests__/event-tip.test.ts b/packages/chain/src/__tests__/event-tip.test.ts similarity index 98% rename from src/__tests__/event-tip.test.ts rename to packages/chain/src/__tests__/event-tip.test.ts index 4f3af414..0bf72d9b 100644 --- a/src/__tests__/event-tip.test.ts +++ b/packages/chain/src/__tests__/event-tip.test.ts @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { WebSocketServer } from 'ws'; -import { fetchEventTip, isCursorBeyondTip, isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; +import { fetchEventTip, isCursorBeyondTip, isStreamEmpty } from '../lib/event-tip.ts'; let servers: WebSocketServer[] = []; afterEach(() => { for (const s of servers) s.close(); servers = []; }); diff --git a/src/__tests__/graphql-ws-subscription.test.ts b/packages/chain/src/__tests__/graphql-ws-subscription.test.ts similarity index 97% rename from src/__tests__/graphql-ws-subscription.test.ts rename to packages/chain/src/__tests__/graphql-ws-subscription.test.ts index 682804b4..f9a310ef 100644 --- a/src/__tests__/graphql-ws-subscription.test.ts +++ b/packages/chain/src/__tests__/graphql-ws-subscription.test.ts @@ -4,10 +4,10 @@ // closed-early / initial-silence / error / abort) is exercised end-to-end. import { describe, it, expect, afterEach } from 'vitest'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { CancelledError } from '@kuiralabs/midnight-cli-core'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { subscribeGraphqlWs } from '../lib/graphql-ws-subscription.ts'; type ServerScript = (ws: WsSocket) => void; diff --git a/src/__tests__/indexer-graphql.test.ts b/packages/chain/src/__tests__/indexer-graphql.test.ts similarity index 93% rename from src/__tests__/indexer-graphql.test.ts rename to packages/chain/src/__tests__/indexer-graphql.test.ts index 090add9b..0ca3e3aa 100644 --- a/src/__tests__/indexer-graphql.test.ts +++ b/packages/chain/src/__tests__/indexer-graphql.test.ts @@ -3,8 +3,8 @@ import { afterEach, describe, expect, it } from 'vitest'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; -import { IndexerQueryError, queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { IndexerQueryError, queryIndexer } from '../lib/indexer-graphql.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../../../test-support/local-indexer.ts'; let indexer: LocalIndexer | undefined; afterEach(async () => { await indexer?.close(); indexer = undefined; }); diff --git a/src/__tests__/ledger-guard.test.ts b/packages/chain/src/__tests__/ledger-guard.test.ts similarity index 96% rename from src/__tests__/ledger-guard.test.ts rename to packages/chain/src/__tests__/ledger-guard.test.ts index ee03fa01..7e215005 100644 --- a/src/__tests__/ledger-guard.test.ts +++ b/packages/chain/src/__tests__/ledger-guard.test.ts @@ -3,16 +3,8 @@ // preview 1000300 (ledger 8), ledger-9 localnet 2001000. import { describe, it, expect, vi } from 'vitest'; -import { - checkLedgerSupported, - assertLedgerSupported, - assertLedger9StackReachable, - fetchProtocolVersion, - UnsupportedLedgerError, - LocalStackUnreachableError, - walletsBelowLedger9, -} from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { checkLedgerSupported, assertLedgerSupported, assertLedger9StackReachable, fetchProtocolVersion, UnsupportedLedgerError, LocalStackUnreachableError, walletsBelowLedger9 } from '../lib/ledger-guard.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; const PREVIEW = 1000300n; const LEDGER9_LOCALNET = 2001000n; diff --git a/src/__tests__/offer-liveness.test.ts b/packages/chain/src/__tests__/offer-liveness.test.ts similarity index 96% rename from src/__tests__/offer-liveness.test.ts rename to packages/chain/src/__tests__/offer-liveness.test.ts index a6424236..8a1499d5 100644 --- a/src/__tests__/offer-liveness.test.ts +++ b/packages/chain/src/__tests__/offer-liveness.test.ts @@ -5,8 +5,8 @@ import { afterEach, describe, expect, it } from 'vitest'; import { WebSocketServer } from 'ws'; -import { spendsOf, LivenessUnknownError } from '@kuiralabs/midnight-chain/lib/offer-liveness'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { spendsOf, LivenessUnknownError } from '../lib/offer-liveness.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../../../test-support/local-indexer.ts'; const N1 = 'aa'.repeat(32); const N2 = 'bb'.repeat(32); diff --git a/src/__tests__/read-cancellation.test.ts b/packages/chain/src/__tests__/read-cancellation.test.ts similarity index 59% rename from src/__tests__/read-cancellation.test.ts rename to packages/chain/src/__tests__/read-cancellation.test.ts index cc48cb86..a3235766 100644 --- a/src/__tests__/read-cancellation.test.ts +++ b/packages/chain/src/__tests__/read-cancellation.test.ts @@ -8,19 +8,15 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { WebSocketServer } from 'ws'; -import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; -import { clearChainIdMemo, getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; -import { queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; -import { fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { waitForFirstBlock } from '@kuiralabs/midnight-chain/lib/node-ready'; -import { waitForAddressFunded } from '@kuiralabs/midnight-chain/lib/indexer-ready'; -import { waitForProofServerReady } from '@kuiralabs/midnight-chain/lib/proof-server-ready'; -import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; -import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; -import { testHost } from './helpers/test-host.ts'; -import { getNetworkConfig, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { callNodeRpc } from '../lib/node-rpc.ts'; +import { clearChainIdMemo, getChainGenesisHash } from '../lib/chain-id.ts'; +import { queryIndexer } from '../lib/indexer-graphql.ts'; +import { fetchProtocolVersion } from '../lib/ledger-guard.ts'; +import { checkBalance } from '../lib/balance-subscription.ts'; +import { waitForFirstBlock } from '../lib/node-ready.ts'; +import { waitForAddressFunded } from '../lib/indexer-ready.ts'; +import { waitForProofServerReady } from '../lib/proof-server-ready.ts'; +import { sleep } from '@kuiralabs/midnight-cli-core'; let http: Server; let ws: WebSocketServer; @@ -113,45 +109,3 @@ describe('localnet up\'s readiness waits, cancelled', () => { await expect(sleep(10_000, call.signal)).rejects.toMatchObject({ code: 'CANCELLED' }); }); }); - -describe('the wallet data repository, cancelled while it checks a memoized read', () => { - it('stops with CANCELLED rather than serving the memo as if the node were down', async () => { - let clock = 0; - const summary: BalanceSummary = { balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }; - const call = new AbortController(); - let tipChecks = 0; - const repo = new WalletDataRepository(testHost(), { - now: () => clock, - // The first check answers; the second waits until its call is cancelled, as a node that doesn't answer. - fetchTip: (_network, signal) => { - tipChecks += 1; - if (tipChecks === 1) return Promise.resolve('tip-1'); - return new Promise((_resolve, reject) => { - signal!.addEventListener('abort', () => reject(signal!.reason), { once: true }); - call.abort(); - }); - }, - fetchUnshielded: async () => summary, - }); - const network: NetworkConfig = getNetworkConfig('undeployed'); - - await repo.unshielded('mn_addr_undeployed1x', network); - clock += 60_000; // past the tip probe's memo, so the next read checks the tip again - - await expect(repo.unshielded('mn_addr_undeployed1x', network, { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); - }); - - it('passes the call\'s signal on to its unshielded fetch', async () => { - const seen: Array = []; - const repo = new WalletDataRepository(testHost(), { - fetchTip: async () => 'tip', - fetchUnshielded: async (_address, _network, _onProgress, signal) => { - seen.push(signal); - return { balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }; - }, - }); - const signal = new AbortController().signal; - await repo.unshielded('mn_addr_undeployed1x', getNetworkConfig('undeployed'), { signal }); - expect(seen).toEqual([signal]); - }); -}); diff --git a/src/__tests__/tx-segments.test.ts b/packages/chain/src/__tests__/tx-segments.test.ts similarity index 96% rename from src/__tests__/tx-segments.test.ts rename to packages/chain/src/__tests__/tx-segments.test.ts index 63592e8b..691789aa 100644 --- a/src/__tests__/tx-segments.test.ts +++ b/packages/chain/src/__tests__/tx-segments.test.ts @@ -4,8 +4,8 @@ // success lists segments. import { afterEach, describe, expect, it } from 'vitest'; -import { SegmentResultsUnavailableError, fetchPartialSuccessSegments } from '@kuiralabs/midnight-chain/lib/tx-segments'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { SegmentResultsUnavailableError, fetchPartialSuccessSegments } from '../lib/tx-segments.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../../../test-support/local-indexer.ts'; const HASH = '2ee4f2b48b659ff6b6f6312b85b49cbfba53fc5f77f430603c845c1a3378464b'; const regular = (status: string, segments: unknown) => diff --git a/packages/chain/src/__tests__/tx-status.test.ts b/packages/chain/src/__tests__/tx-status.test.ts new file mode 100644 index 00000000..81202b93 --- /dev/null +++ b/packages/chain/src/__tests__/tx-status.test.ts @@ -0,0 +1,165 @@ +// What became of a transaction, from the indexer: the lookup, the wait, and +// the receipt a submitting command reports. The indexer's answers are +// test-support/fixtures/tx-status.ts. + +import { afterEach, describe, expect, it } from 'vitest'; +import { CancelledError, UsageError, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; +import { IndexerQueryError } from '../lib/indexer-graphql.ts'; +import { fetchTransactionStatus, parseTxReference, transactionStatus, waitForTransactionStatus } from '../lib/tx-status.ts'; +import { receiptJson, receiptOf, transactionStatusJson } from '../lib/tx-receipt.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../../../test-support/local-indexer.ts'; +import { BLOCK, HASH, IDENTIFIER, answer, regular } from '../../../../test-support/fixtures/tx-status.ts'; + +let indexer: LocalIndexer | undefined; +afterEach(async () => { await indexer?.close(); indexer = undefined; }); + +describe('parseTxReference', () => { + it('reads 64 hex characters as a hash and 66 as an identifier, with or without 0x, in any case', () => { + expect(parseTxReference(HASH)).toEqual({ hash: HASH }); + expect(parseTxReference(IDENTIFIER)).toEqual({ identifier: IDENTIFIER }); + expect(parseTxReference(`0x${HASH.toUpperCase()}`)).toEqual({ hash: HASH }); + }); + + it.each(['', 'xyz', HASH.slice(1), `${IDENTIFIER}00`, `${HASH.slice(0, 63)}g`])('refuses %j as a usage error', (text) => { + expect(() => parseTxReference(text)).toThrow(UsageError); + }); +}); + +describe('fetchTransactionStatus', () => { + it('finds a transaction by its identifier: final, with its result, fee in specks and block', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const status = await fetchTransactionStatus(indexer.url, { identifier: IDENTIFIER }); + expect(status).toEqual({ + state: 'final', kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', feeSpecks: 845170285714286n, + block: { height: BLOCK.height, hash: BLOCK.hash, time: new Date('2026-11-03T08:55:18.000Z') }, + }); + expect(indexer.requests[0]!.variables).toEqual({ offset: { identifier: IDENTIFIER } }); + }); + + it('asks by hash when given a hash', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + await fetchTransactionStatus(indexer.url, { hash: HASH }); + expect(indexer.requests[0]!.variables).toEqual({ offset: { hash: HASH } }); + }); + + it('lists the segments of a partial success, and only of one', async () => { + indexer = await startLocalIndexer(() => answer([regular('PARTIAL_SUCCESS', [{ id: 0, success: true }, { id: 1, success: false }])])); + const status = await fetchTransactionStatus(indexer.url, { hash: HASH }); + expect(status).toMatchObject({ result: 'PARTIAL_SUCCESS', segments: [{ id: 0, success: true }, { id: 1, success: false }] }); + }); + + it('reports a failed transaction as final, with the fee it paid', async () => { + indexer = await startLocalIndexer(() => answer([regular('FAILURE')])); + expect(await fetchTransactionStatus(indexer.url, { hash: HASH })).toMatchObject({ state: 'final', result: 'FAILURE', feeSpecks: 845170285714286n }); + }); + + it('reports a system transaction with its block, and no result or fee', async () => { + indexer = await startLocalIndexer(() => answer([{ __typename: 'SystemTransaction', hash: HASH, block: BLOCK }])); + const status = await fetchTransactionStatus(indexer.url, { hash: HASH }); + expect(status).toEqual({ state: 'final', kind: 'system', hash: HASH, identifiers: [], block: { height: BLOCK.height, hash: BLOCK.hash, time: new Date(BLOCK.timestamp) } }); + }); + + it('reports a transaction the indexer does not have as not found', async () => { + indexer = await startLocalIndexer(() => answer([])); + expect(await fetchTransactionStatus(indexer.url, { identifier: IDENTIFIER })).toEqual({ state: 'notFound' }); + }); + + it('throws IndexerQueryError when the indexer refuses the query', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'invalid transaction hash' }] })); + await expect(fetchTransactionStatus(indexer.url, { hash: HASH })).rejects.toThrow(IndexerQueryError); + }); +}); + +describe('waitForTransactionStatus', () => { + it('asks until the indexer lists the transaction', async () => { + let asked = 0; + indexer = await startLocalIndexer(() => (++asked < 3 ? answer([]) : answer([regular('SUCCESS')]))); + const status = await waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 5_000, undefined, 20); + expect(status.state).toBe('final'); + expect(asked).toBe(3); + }); + + it('gives not found once the timeout passes', async () => { + indexer = await startLocalIndexer(() => answer([])); + const started = Date.now(); + expect(await waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 150, undefined, 20)).toEqual({ state: 'notFound' }); + expect(Date.now() - started).toBeLessThan(2_000); + expect(indexer.requests.length).toBeGreaterThan(1); + }); + + it('stops with CancelledError when its call is cancelled', async () => { + indexer = await startLocalIndexer(() => answer([])); + const controller = new AbortController(); + setTimeout(() => controller.abort(), 50); + await expect(waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 10_000, controller.signal, 20)).rejects.toThrow(CancelledError); + }); +}); + +describe('transactionStatus', () => { + it('asks once, saying so, and gives what the indexer knows', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const said: ProgressEvent[] = []; + const status = await transactionStatus({ indexer: indexer.url, ref: { hash: HASH }, onProgress: (event) => said.push(event) }); + expect(status).toMatchObject({ state: 'final', result: 'SUCCESS', feeSpecks: 845170285714286n, block: { height: BLOCK.height } }); + expect(indexer.requests).toHaveLength(1); + expect(said).toEqual([{ kind: 'start', message: 'Asking the indexer...' }, { kind: 'done', message: 'Final' }]); + }); + + it('with wait, asks until the time passes, and says it was not found', async () => { + indexer = await startLocalIndexer(() => answer([])); + const said: ProgressEvent[] = []; + const status = await transactionStatus({ indexer: indexer.url, ref: { identifier: IDENTIFIER }, wait: true, timeoutMs: 100, onProgress: (event) => said.push(event) }); + expect(status).toEqual({ state: 'notFound' }); + expect(said).toEqual([{ kind: 'start', message: 'Waiting for the indexer to list it...' }, { kind: 'done', message: 'Not found' }]); + }); + + it('never asks when its call is cancelled already', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const said: ProgressEvent[] = []; + await expect(transactionStatus({ indexer: indexer.url, ref: { hash: HASH }, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toThrow(CancelledError); + expect(indexer.requests).toEqual([]); + expect(said).toEqual([]); + }); + + it('throws IndexerQueryError when the indexer refuses', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'invalid transaction hash' }] })); + await expect(transactionStatus({ indexer: indexer.url, ref: { hash: HASH } })).rejects.toBeInstanceOf(IndexerQueryError); + }); +}); + +describe('receiptOf', () => { + it('gives the transaction once listed, and its JSON with the fee in DUST exactly', async () => { + indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); + const receipt = await receiptOf(indexer.url, IDENTIFIER); + expect(receiptJson(receipt)).toEqual({ + receipt: { + kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', fee: '0.845170285714286', feeSpecks: '845170285714286', + blockHeight: BLOCK.height, blockHash: BLOCK.hash, blockTime: '2026-11-03T08:55:18.000Z', + }, + }); + }); + + it('says the indexer has not listed it yet, never throwing', async () => { + indexer = await startLocalIndexer(() => answer([])); + expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER, undefined, 100))).toEqual({ receipt: null, receiptMissing: 'the indexer has not listed it after 0 s' }); + }); + + it('says the indexer did not answer, never throwing', async () => { + indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'overloaded' }] })); + expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER))).toEqual({ receipt: null, receiptMissing: 'the indexer did not answer: overloaded' }); + }); + + it('says it was cancelled, never throwing: the transaction is submitted already', async () => { + indexer = await startLocalIndexer(() => answer([])); + const controller = new AbortController(); + setTimeout(() => controller.abort(), 50); + expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER, controller.signal))).toEqual({ receipt: null, receiptMissing: 'cancelled while waiting for the indexer' }); + }); +}); + +describe('transactionStatusJson', () => { + it('gives not found as its state alone', () => { + expect(transactionStatusJson({ state: 'notFound' })).toEqual({ state: 'notFound' }); + }); +}); + diff --git a/packages/chain/src/commands.ts b/packages/chain/src/commands.ts new file mode 100644 index 00000000..9fe9c9c1 --- /dev/null +++ b/packages/chain/src/commands.ts @@ -0,0 +1,8 @@ +// @kuiralabs/midnight-chain/commands: the chain's commands (status, tx), its +// codes and the code set other packages' definitions name, and its agent +// guidance, for the shell that installs them. + +export { chainCodes, READS_CHAIN } from './commands/chain.codes.ts'; +export { chainGuidance } from './commands/chain.guidance.ts'; +export { statusDefinition } from './commands/status.definition.ts'; +export { txDefinition } from './commands/tx.definition.ts'; diff --git a/packages/chain/src/commands/chain.codes.ts b/packages/chain/src/commands/chain.codes.ts index 47992161..dcdf139f 100644 --- a/packages/chain/src/commands/chain.codes.ts +++ b/packages/chain/src/commands/chain.codes.ts @@ -2,8 +2,7 @@ // local stack's endpoints, and the chain's clock; and the set a command // definition declares when it checks the chain's ledger. -import { defineCodeSet, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { defineCodeSet, defineCodes, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core'; export const chainCodes = defineCodes([ { code: 'UNSUPPORTED_LEDGER', exitCode: EXIT_NETWORK_ERROR, order: 150, summary: 'The network is on ledger 8; this build supports ledger 9 only.', recovery: "Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry." }, diff --git a/packages/chain/src/commands/chain.guidance.ts b/packages/chain/src/commands/chain.guidance.ts index b20efb2a..d7b955cf 100644 --- a/packages/chain/src/commands/chain.guidance.ts +++ b/packages/chain/src/commands/chain.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each // naming its section and its place there. -import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core'; import { chainCodes } from './chain.codes.ts'; export const chainGuidance: PackageGuidance = { diff --git a/packages/chain/src/commands/status.definition.ts b/packages/chain/src/commands/status.definition.ts index 59387963..1713a17b 100644 --- a/packages/chain/src/commands/status.definition.ts +++ b/packages/chain/src/commands/status.definition.ts @@ -1,7 +1,7 @@ // The `status` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; export const statusDefinition: CommandDefinition = { name: 'status', diff --git a/packages/chain/src/commands/status.ts b/packages/chain/src/commands/status.ts index 58bd4702..d7f6fe1b 100644 --- a/packages/chain/src/commands/status.ts +++ b/packages/chain/src/commands/status.ts @@ -5,16 +5,9 @@ // canary data from the dashboard (hourly monitoring history). // No wallet or SDK needed — works from anywhere. -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { DASHBOARD_BASE_URL } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { BlockfrostProjectIdRequiredError, assertEndpointUsable, endpointRefusal } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { isValidNetworkName, resolveNetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { resolveBlockfrostProjectId, type NetworkSettings } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim, teal, green, red, gray } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { type ParsedArgs, getFlag, hasFlag, DASHBOARD_BASE_URL, BlockfrostProjectIdRequiredError, assertEndpointUsable, endpointRefusal, isValidNetworkName, resolveNetworkConfig, type NetworkName, resolveBlockfrostProjectId, type NetworkSettings, CancelledError, type CallContext, type CallOutput, type CommandOutcome } from '@kuiralabs/midnight-cli-core'; +import { header, divider, bold, dim, teal, green, red, gray } from '@kuiralabs/midnight-cli-core/ui'; -import type { CallContext, CallOutput, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; // ── Types matching status.json contract ── @@ -149,7 +142,7 @@ async function tryDetectNetwork(args: ParsedArgs, root: string): Promise [--wait [--timeout ]] [--network ] [--json] -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { header, keyValue, formatDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { type ParsedArgs, getFlag, hasFlag, UsageError, resolveNetwork, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, formatDust, dim, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; import { parseTxReference, transactionStatus, TX_STATUS_WAIT_MS } from '../lib/tx-status.ts'; import { transactionStatusJson } from '../lib/tx-receipt.ts'; diff --git a/packages/chain/src/index.ts b/packages/chain/src/index.ts new file mode 100644 index 00000000..1f71543d --- /dev/null +++ b/packages/chain/src/index.ts @@ -0,0 +1,25 @@ +// @kuiralabs/midnight-chain: read-only network access: node, indexer and +// proof-server readiness, the chain id, tip and events, the ledger-version +// guard, transaction status and receipts, and offer liveness. Each name is +// listed, so the API is what this file says. The chain's commands, codes and +// guidance are "./commands". + +export { type BalanceSummary, checkBalance, isNativeToken } from './lib/balance-subscription.ts'; +export { assertChainClockCurrent, ChainClockBehindError, fetchChainTime } from './lib/chain-clock.ts'; +export { getChainGenesisHash } from './lib/chain-id.ts'; +export { assertNetworkAnswers } from './lib/endpoint-check.ts'; +export { fetchEventTip, isCursorBeyondTip, isStreamEmpty, type LedgerEventStream } from './lib/event-tip.ts'; +export { subscribeGraphqlWs } from './lib/graphql-ws-subscription.ts'; +export { queryIndexer } from './lib/indexer-graphql.ts'; +export { waitForAddressFunded } from './lib/indexer-ready.ts'; +export { + assertLedger9StackReachable, assertLedgerSupported, fetchProtocolVersion, LocalStackUnreachableError, + UnsupportedLedgerError, walletsBelowLedger9 +} from './lib/ledger-guard.ts'; +export { waitForFirstBlock } from './lib/node-ready.ts'; +export { callNodeRpc } from './lib/node-rpc.ts'; +export { type CoinSpend, spendsOf } from './lib/offer-liveness.ts'; +export { waitForProofServerReady } from './lib/proof-server-ready.ts'; +export { type Receipt, RECEIPT_WAIT_MS, receiptJson, receiptOf } from './lib/tx-receipt.ts'; +export { fetchPartialSuccessSegments, type SegmentResult } from './lib/tx-segments.ts'; +export { transactionStatus } from './lib/tx-status.ts'; diff --git a/packages/chain/src/lib/balance-subscription.ts b/packages/chain/src/lib/balance-subscription.ts index df30263b..9867868d 100644 --- a/packages/chain/src/lib/balance-subscription.ts +++ b/packages/chain/src/lib/balance-subscription.ts @@ -1,10 +1,7 @@ import WebSocket from 'ws'; -import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { NATIVE_TOKEN_TYPE, BALANCE_CHECK_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { assertEndpointUsable, endpointRefusalFromWsError, NATIVE_TOKEN_TYPE, BALANCE_CHECK_TIMEOUT_MS, CancelledError, NetworkError, type BalanceSummary } from '@kuiralabs/midnight-cli-core'; -export type { BalanceSummary } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { BalanceSummary } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { BalanceSummary } from '@kuiralabs/midnight-cli-core'; interface Utxo { value: string; diff --git a/packages/chain/src/lib/chain-clock.ts b/packages/chain/src/lib/chain-clock.ts index eacb56bb..5b20ecde 100644 --- a/packages/chain/src/lib/chain-clock.ts +++ b/packages/chain/src/lib/chain-clock.ts @@ -6,7 +6,7 @@ // built on them is refused with a bare "Transaction submission error". import { queryIndexer } from './indexer-graphql.ts'; -import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; +import { formatWait } from '@kuiralabs/midnight-cli-core'; /** How far behind this computer's clock the chain may be before mn says so. */ export const CHAIN_CLOCK_TOLERANCE_MS = 2 * 60_000; diff --git a/packages/chain/src/lib/chain-id.ts b/packages/chain/src/lib/chain-id.ts index 0a725cec..08d1dd27 100644 --- a/packages/chain/src/lib/chain-id.ts +++ b/packages/chain/src/lib/chain-id.ts @@ -5,7 +5,7 @@ // preprod reset that advanced the chain past our cache). import { callNodeRpc } from './node-rpc.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core'; /** Memoise genesis-hash lookups so back-to-back commands don't re-fetch. */ const CHAIN_ID_MEMO = new Map(); diff --git a/packages/chain/src/lib/endpoint-check.ts b/packages/chain/src/lib/endpoint-check.ts index 9ff01cf3..2cb2144c 100644 --- a/packages/chain/src/lib/endpoint-check.ts +++ b/packages/chain/src/lib/endpoint-check.ts @@ -2,8 +2,7 @@ // refuses it without saying why, so mn finds out first. The endpoints mn // connects to itself are checked where the connection is made. -import { assertEndpointUsable, endpointRefusal, isBlockfrostUrl } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { assertEndpointUsable, endpointRefusal, isBlockfrostUrl, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; const PROBE_TIMEOUT_MS = 10_000; diff --git a/packages/chain/src/lib/graphql-ws-subscription.ts b/packages/chain/src/lib/graphql-ws-subscription.ts index 94e47c7d..10a14a02 100644 --- a/packages/chain/src/lib/graphql-ws-subscription.ts +++ b/packages/chain/src/lib/graphql-ws-subscription.ts @@ -19,8 +19,7 @@ // `partial=true` means "state is valid but not caught up — persist and resume". import WebSocket from 'ws'; -import { CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { CancelledError, NetworkError, assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core'; /** Why the subscription settled. `timeout`/`closed-early` are the partial cases. */ export type WsFinishReason = diff --git a/packages/chain/src/lib/indexer-graphql.ts b/packages/chain/src/lib/indexer-graphql.ts index fbd2901e..41b61f82 100644 --- a/packages/chain/src/lib/indexer-graphql.ts +++ b/packages/chain/src/lib/indexer-graphql.ts @@ -1,7 +1,6 @@ // One GraphQL query to the indexer's HTTP endpoint. -import { assertEndpointUsable, endpointRefusal } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { assertEndpointUsable, endpointRefusal, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; /** The indexer could not answer a query: unreachable, an HTTP error, a non-JSON body, or GraphQL errors. */ export class IndexerQueryError extends Error { diff --git a/packages/chain/src/lib/indexer-ready.ts b/packages/chain/src/lib/indexer-ready.ts index 46788f5d..756bd03b 100644 --- a/packages/chain/src/lib/indexer-ready.ts +++ b/packages/chain/src/lib/indexer-ready.ts @@ -6,8 +6,7 @@ // on localnet), confirming state has been ingested end-to-end. import { checkBalance } from './balance-subscription.ts'; -import { SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { SyncTimeoutError, throwIfCancelled, sleep } from '@kuiralabs/midnight-cli-core'; export interface WaitForIndexerOptions { /** Overall deadline for the wait. Default 30s. */ diff --git a/packages/chain/src/lib/ledger-guard.ts b/packages/chain/src/lib/ledger-guard.ts index 621c1084..28551c05 100644 --- a/packages/chain/src/lib/ledger-guard.ts +++ b/packages/chain/src/lib/ledger-guard.ts @@ -3,11 +3,9 @@ // events. So check the chain's protocol version up front and fail with a // clear message instead of hanging or failing on a deserialize error. -import { LEDGER_9_FORK_VERSION, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { LEDGER_9_FORK_VERSION, type NetworkConfig, isEndpointError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { getChainGenesisHash } from './chain-id.ts'; -import { isEndpointError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; import { queryIndexer } from './indexer-graphql.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export class UnsupportedLedgerError extends Error { readonly code = 'UNSUPPORTED_LEDGER'; diff --git a/packages/chain/src/lib/node-ready.ts b/packages/chain/src/lib/node-ready.ts index 1198b411..cc61a6e6 100644 --- a/packages/chain/src/lib/node-ready.ts +++ b/packages/chain/src/lib/node-ready.ts @@ -5,8 +5,7 @@ // until a non-zero block number appears. import { callNodeRpc } from './node-rpc.ts'; -import { SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { SyncTimeoutError, throwIfCancelled, sleep } from '@kuiralabs/midnight-cli-core'; export interface WaitForFirstBlockOptions { /** Overall deadline for the wait. Default 30s. */ diff --git a/packages/chain/src/lib/node-rpc.ts b/packages/chain/src/lib/node-rpc.ts index 1a5464c8..4f04cfa4 100644 --- a/packages/chain/src/lib/node-rpc.ts +++ b/packages/chain/src/lib/node-rpc.ts @@ -4,8 +4,7 @@ // this is used at cold-start moments where heavyweight init would hurt. import WebSocket from 'ws'; -import { assertEndpointUsable, endpointRefusalFromWsError } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { assertEndpointUsable, endpointRefusalFromWsError, CancelledError, NetworkError } from '@kuiralabs/midnight-cli-core'; export interface RpcOptions { url: string; diff --git a/packages/chain/src/lib/offer-liveness.ts b/packages/chain/src/lib/offer-liveness.ts index 89f6a9e6..40b5cf22 100644 --- a/packages/chain/src/lib/offer-liveness.ts +++ b/packages/chain/src/lib/offer-liveness.ts @@ -5,7 +5,7 @@ import { queryIndexer } from './indexer-graphql.ts'; import { subscribeGraphqlWs } from './graphql-ws-subscription.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { throwIfCancelled } from '@kuiralabs/midnight-cli-core'; const SPENT_NULLIFIERS = `subscription Spent($prefixes: [HexEncoded!]!, $fromBlock: Int, $toBlock: Int) { shieldedNullifierTransactions(nullifierPrefixes: $prefixes, fromBlock: $fromBlock, toBlock: $toBlock) { diff --git a/packages/chain/src/lib/proof-server-ready.ts b/packages/chain/src/lib/proof-server-ready.ts index c2aef73f..91fffb8f 100644 --- a/packages/chain/src/lib/proof-server-ready.ts +++ b/packages/chain/src/lib/proof-server-ready.ts @@ -5,8 +5,7 @@ // polls the proof-server's `/` status endpoint until it returns a 2xx with // `{"status":"ok",...}` before `mn localnet up` claims readiness. -import { SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { SyncTimeoutError, throwIfCancelled, sleep } from '@kuiralabs/midnight-cli-core'; export interface WaitForProofServerOptions { /** Overall deadline for the wait. Default 30s. */ diff --git a/packages/chain/src/lib/tx-receipt.ts b/packages/chain/src/lib/tx-receipt.ts index cf6bdb77..e9709f6f 100644 --- a/packages/chain/src/lib/tx-receipt.ts +++ b/packages/chain/src/lib/tx-receipt.ts @@ -2,8 +2,8 @@ // indexer lists it. mn's submits return when the node has finalized the // transaction; the indexer may list it a few seconds later. -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { toDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { CancelledError } from '@kuiralabs/midnight-cli-core'; +import { toDust } from '@kuiralabs/midnight-cli-core/ui'; import { IndexerQueryError } from './indexer-graphql.ts'; import { type FinalTransaction, type TransactionStatus, parseTxReference, waitForTransactionStatus } from './tx-status.ts'; diff --git a/packages/chain/src/lib/tx-status.ts b/packages/chain/src/lib/tx-status.ts index 9a6cf92e..0b0e3ec1 100644 --- a/packages/chain/src/lib/tx-status.ts +++ b/packages/chain/src/lib/tx-status.ts @@ -7,9 +7,7 @@ // (33 bytes): what mn reports as a submitted transaction's `txHash` is the // wallet SDK's identifier. -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; -import { progressSteps, type ProgressListener } from '@kuiralabs/midnight-cli-core/lib/progress'; +import { UsageError, throwIfCancelled, sleep, progressSteps, type ProgressListener } from '@kuiralabs/midnight-cli-core'; import { queryIndexer } from './indexer-graphql.ts'; const QUERY_TIMEOUT_MS = 10_000; diff --git a/packages/chain/tsconfig.build.json b/packages/chain/tsconfig.build.json index 16f7d7d6..267c2417 100644 --- a/packages/chain/tsconfig.build.json +++ b/packages/chain/tsconfig.build.json @@ -24,5 +24,9 @@ }, "include": [ "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" ] } diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 9c26e65c..a68e2394 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -1,276 +1,30 @@ # API report: @kuiralabs/midnight-cli-core -Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. -## `@kuiralabs/midnight-cli-core/commands/config` +## `@kuiralabs/midnight-cli-core` ```ts -import { type ParsedArgs } from "../lib/argv.ts"; -import type { CallContext } from "../lib/call-context.ts"; -export default function configCommand(args: ParsedArgs, ctx: CallContext): Promise; -``` - -## `@kuiralabs/midnight-cli-core/commands/config.definition` - -```ts -import type { CommandDefinition } from "../lib/command-definition.ts"; -export declare const configDefinition: CommandDefinition; -``` - -## `@kuiralabs/midnight-cli-core/commands/core.codes` - -```ts -export declare const coreCodes: readonly [ - { - readonly code: "INVALID_ARGS"; - readonly exitCode: 2; - readonly order: 10; - readonly summary: "Missing/invalid argument."; - readonly recovery: "Show the message to the user verbatim \u2014 it names the missing field."; - }, - { - readonly code: "WRONG_PASSPHRASE"; - readonly exitCode: 2; - readonly order: 220; - readonly summary: "`MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed."; - readonly recovery: "Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed."; - }, - { - readonly code: "PASSPHRASE_REQUIRED"; - readonly exitCode: 2; - readonly order: 230; - readonly summary: "A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none)."; - readonly recovery: "Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat."; - }, - { - readonly code: "NETWORK_ERROR"; - readonly exitCode: 4; - readonly order: 30; - readonly summary: "Indexer/node/proof-server connection refused or DNS failure."; - readonly recovery: "Check `midnight_localnet_status()` or the endpoints the user configured; on this build `midnight_localnet_up()` is refused, so ask the user to start their ledger-9 stack."; - }, - { - readonly code: "AMBIGUOUS_LOCAL_STACKS"; - readonly exitCode: 4; - readonly order: 180; - readonly summary: "Several local Midnight stacks are running and no endpoints are configured, so mn won't guess."; - readonly recovery: "Ask the user which stack to use; they set its endpoints with `midnight config set`. Don't retry blindly."; - }, - { - readonly code: "BLOCKFROST_PROJECT_ID_REQUIRED"; - readonly exitCode: 4; - readonly order: 240; - readonly summary: "The network (preprod) is served by Blockfrost and no project id is set."; - readonly recovery: "Ask the user to create a Midnight preprod project at https://blockfrost.io and run `midnight config set blockfrost-project-id ` themselves. Never ask them to paste the id into the chat. Don't retry until they have."; - }, - { - readonly code: "BLOCKFROST_PROJECT_ID_REJECTED"; - readonly exitCode: 4; - readonly order: 250; - readonly summary: "Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network."; - readonly recovery: "Ask the user to check it at blockfrost.io and set it again. Don't retry blindly."; - }, - { - readonly code: "BLOCKFROST_LIMIT_REACHED"; - readonly exitCode: 4; - readonly order: 260; - readonly summary: "Blockfrost's plan limit or rate limit."; - readonly recovery: "Wait and retry once; if it persists, tell the user it is their Blockfrost plan."; - }, - { - readonly code: "ENDPOINT_SHUT_DOWN"; - readonly exitCode: 4; - readonly order: 270; - readonly summary: "An endpoint set by flag or config was shut down by its operator (the old preprod indexer)."; - readonly recovery: "`midnight_config_unset({ key: \"indexer-ws\" })` (and `node` if set), then retry."; - }, - { - readonly code: "CANCELLED"; - readonly exitCode: 7; - readonly order: 370; - readonly summary: "Operation was aborted (SIGINT, or the MCP call was cancelled)."; - readonly recovery: "A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user."; - }, - { - readonly code: "OTHER_SDK_SET"; - readonly exitCode: 1; - readonly order: 280; - readonly summary: "The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet)."; - readonly recovery: "Make the call in a process of its own: ask the user to start an MCP server for that network."; - }, - { - readonly code: "MIXED_SDK_LAYOUT"; - readonly exitCode: 1; - readonly order: 290; - readonly summary: "mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger."; - readonly recovery: "Ask the user to install mn with npm."; - }, - { - readonly code: "UNSUPPORTED_NODE"; - readonly exitCode: 1; - readonly order: 190; - readonly summary: "Node.js is older than 22 (22.18 for mn grant)."; - readonly recovery: "Ask the user to install a current Node.js."; - }, - { - readonly code: "NO_STATE_ROOT"; - readonly exitCode: 1; - readonly order: 300; - readonly summary: "The host gave mn no place to keep its state (a program's `createHost` without paths)."; - readonly recovery: "Give the host its paths (`createHost({ paths })`)."; - }, - { - readonly code: "NO_PAYER"; - readonly exitCode: 1; - readonly order: 310; - readonly summary: "A command that submits a transaction was called without a payer."; - readonly recovery: "Give the call a payer."; - }, - { - readonly code: "COMMAND_FAILED"; - readonly exitCode: 1; - readonly order: 320; - readonly summary: "A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result."; - readonly recovery: "Read the command's result in the message."; - }, - { - readonly code: "UNKNOWN"; - readonly exitCode: 1; - readonly order: 380; - readonly summary: "Error didn't match any known classifier."; - readonly recovery: "Surface the message to the user. If reproducible, a new code may be warranted."; - }, - { - readonly code: "PROOF_TIMEOUT"; - readonly exitCode: 6; - readonly order: 90; - readonly summary: "ZK proof generation didn't finish within the deadline."; - readonly recovery: "Retry \u2014 proofs can be slow under load."; - }, - { - readonly code: "PROOF_FAILURE"; - readonly exitCode: 6; - readonly order: 100; - readonly summary: "Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server."; - readonly recovery: "Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: \"\" })` then retry."; - }, - { - readonly code: "INVALID_DUST_PROOF"; - readonly exitCode: 6; - readonly order: 110; - readonly summary: "Chain rejected the dust spend proof as malformed (substrate \"Custom error 170\"). Stale commitment tree."; - readonly recovery: "`midnight_cache_clear({ wallet: \"\" })` then retry."; - }, - { - readonly code: "TX_REJECTED"; - readonly exitCode: 6; - readonly order: 60; - readonly summary: "Chain rejected the submitted transaction (catch-all when no more specific code applies)."; - readonly recovery: "Read the message; usually a state mismatch resolved by re-sync + retry."; - }, - { - readonly code: "STALE_UTXO"; - readonly exitCode: 6; - readonly order: 70; - readonly summary: "UTXO was already spent on-chain (substrate \"error code 115\")."; - readonly recovery: "Re-sync (the next call will refresh state) and retry."; - }, - { - readonly code: "STALE_CACHE"; - readonly exitCode: 6; - readonly order: 80; - readonly summary: "Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed)."; - readonly recovery: "`midnight_cache_clear({ wallet: \"\" })` then retry."; - }, - { - readonly code: "SYNC_TIMEOUT"; - readonly exitCode: 4; - readonly order: 40; - readonly summary: "Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync."; - readonly recovery: "Retry; the cache resumes from the last applied event so progress is preserved."; - }, - { - readonly code: "DUST_REQUIRED"; - readonly exitCode: 5; - readonly order: 120; - readonly summary: "Wallet has NIGHT but not enough DUST for the fee."; - readonly recovery: "Not registered (`midnight_dust_status()` shows `registered: false`): run `midnight_dust_register()`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes (\"generates the rest in about 4 minutes\"). Wait that long and retry, don't retry at once."; - }, - { - readonly code: "DUST_GENERATING"; - readonly exitCode: 5; - readonly order: 130; - readonly summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust."; - readonly recovery: "The message says when: run `midnight_dust_register()` again then, or add NIGHT."; - }, - { - readonly code: "INSUFFICIENT_BALANCE"; - readonly exitCode: 5; - readonly order: 50; - readonly summary: "Wallet doesn't have enough NIGHT to cover the requested amount."; - readonly recovery: "Show the user. On localnet: `midnight_airdrop({ amount: \"...\" })`. On hosted networks: tell user to fund the address."; - }, - { - readonly code: "NOT_AN_OFFER"; - readonly exitCode: 2; - readonly order: 330; - readonly summary: "The bytes given as a swap offer are not one."; - readonly recovery: "Ask the maker for the offer again."; - }, - { - readonly code: "TERMS_MISMATCH"; - readonly exitCode: 2; - readonly order: 340; - readonly summary: "A swap offer's own terms differ from the agreed ones."; - readonly recovery: "Don't take it; agree the terms again with the maker."; - }, - { - readonly code: "OFFER_EXPIRED"; - readonly exitCode: 2; - readonly order: 350; - readonly summary: "A swap offer is past the expiry its maker set."; - readonly recovery: "Ask the maker for a new one."; - }, - { - readonly code: "OFFER_COINS_IN_USE"; - readonly exitCode: 2; - readonly order: 360; - readonly summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it."; - readonly recovery: "Cancel the offer first (`mn swap cancel`), or wait until it is taken."; - } -]; -export declare const EVERY_COMMAND: readonly [ - "INVALID_ARGS", - "CANCELLED", - "UNKNOWN", - "UNSUPPORTED_NODE", - "NO_STATE_ROOT" -]; -export declare const RESOLVES_NETWORK: import("../lib/error-codes.ts").CodeSet; -export declare const LOADS_ENGINE: import("../lib/error-codes.ts").CodeSet; -export declare const ENGINE_SYNC: import("../lib/error-codes.ts").CodeSet; -export declare const PAYS: import("../lib/error-codes.ts").CodeSet; -export declare const READS_OFFERS: import("../lib/error-codes.ts").CodeSet; -``` - -## `@kuiralabs/midnight-cli-core/commands/core.guidance` - -```ts -import { type PackageGuidance } from "../lib/agent-guidance.ts"; -export declare const coreGuidance: PackageGuidance; -``` - -## `@kuiralabs/midnight-cli-core/lib/agent-guidance` - -```ts -import type { CodeDefinition } from "./error-codes.ts"; -export type GuidanceText = "agent-manual" | "skill-core" | "skill-full"; +export declare function assembleGuidance(text: GuidanceText, sections: readonly string[], pieces: readonly GuidancePiece[]): string; +export declare function codeGuidancePieces(codes: readonly CodeDefinition[]): GuidancePiece[]; +export declare class GuidanceError extends Error { + constructor(message: string); +} export interface GuidancePiece { readonly text: GuidanceText; readonly section: string; readonly order: number; readonly body: string; } +export type GuidanceText = 'agent-manual' | 'skill-core' | 'skill-full'; +export declare function manualCodeRow(definition: CodeDefinition): string; +export interface PackageGuidance { + readonly pieces: readonly GuidancePiece[]; + readonly sections?: readonly GuidanceSection[]; + readonly toolsTable?: readonly ToolsTableRow[]; +} +export declare function sectionsWithAdded(text: GuidanceText, skeleton: readonly string[], added: readonly GuidanceSection[]): string[]; +export declare function skillCodeRow(definition: CodeDefinition): string; export interface ToolsTableRow { readonly tool: string; readonly group: string; @@ -278,188 +32,54 @@ export interface ToolsTableRow { readonly description: readonly string[]; readonly params?: readonly string[]; } -export interface GuidanceSection { - readonly text: GuidanceText; - readonly name: string; - readonly after: string; -} -export interface PackageGuidance { - readonly pieces: readonly GuidancePiece[]; - readonly sections?: readonly GuidanceSection[]; - readonly toolsTable?: readonly ToolsTableRow[]; -} -export declare class GuidanceError extends Error { - constructor(message: string); -} -export declare function unplacedPieces(text: GuidanceText, sections: readonly string[], pieces: readonly GuidancePiece[]): GuidancePiece[]; -export declare function sectionsWithAdded(text: GuidanceText, skeleton: readonly string[], added: readonly GuidanceSection[]): string[]; -export declare function assertDistinctPlaces(pieces: readonly GuidancePiece[]): void; -export declare function assembleGuidance(text: GuidanceText, sections: readonly string[], pieces: readonly GuidancePiece[]): string; export declare function wrapWords(text: string, width: number): string[]; -export declare function manualCodeRow(definition: CodeDefinition): string; -export declare function skillCodeRow(definition: CodeDefinition): string; -export declare function codeGuidancePieces(codes: readonly CodeDefinition[]): GuidancePiece[]; -``` - -## `@kuiralabs/midnight-cli-core/lib/amount` - -```ts +export declare function nightAmountJson(micro: bigint): number; +export declare function nightAmountText(micro: bigint): string; export declare function nightToMicro(amountNight: number): bigint; export declare function parseAmount(amountStr: string): bigint; -export declare function nightAmountText(micro: bigint): string; -export declare function nightAmountJson(micro: bigint): number; -``` - -## `@kuiralabs/midnight-cli-core/lib/approval` - -```ts -import type { NoticeSink } from "./notices.ts"; -import { type Prompter } from "./prompter.ts"; -import type { FeeLimits } from "./fee-limits.ts"; -export interface ApprovalDetail { - label: string; - value: string; -} -export interface ApprovalRequest { - method: string; - dappName?: string; - network: string; - details: ApprovalDetail[]; - feeOnly?: boolean; -} -export type ApprovalResult = "approve" | "reject"; -export interface ApprovalOptions { - autoApproveReads?: boolean; - approveAll?: boolean; - approveFees?: boolean; - prompter: Prompter | null; - notice: NoticeSink; -} -export interface ApprovalPolicy { - reads: "auto"; - balancing: "auto" | "fee-only" | "prompt"; - writes: "auto" | "fee-only" | "prompt"; - feeLimits?: { - maxFeeSpecks: string; - maxPending: number; - }; -} -export declare function describeApprovalPolicy(options: Omit, feeLimits: FeeLimits): ApprovalPolicy; -export declare function isReadOnlyMethod(method: string): boolean; -export declare function isPrepMethod(method: string): boolean; -export declare function renderApprovalBox(request: ApprovalRequest): string; -export declare function promptApproval(request: ApprovalRequest, options: ApprovalOptions): Promise; -``` - -## `@kuiralabs/midnight-cli-core/lib/argv` - -```ts +export declare function describeApprovalPolicy(options: Omit, feeLimits: FeeLimits): ApprovalPolicy; +export declare const FULL_FLAG = "_full"; +export declare function getFlag(args: ParsedArgs, name: string): string | undefined; +export declare function hasFlag(args: ParsedArgs, name: string): boolean; +export declare function isMinimalMode(args: ParsedArgs): boolean; +export declare const MINIMAL_FLAG = "_minimal"; +export declare function parseArgs(argv?: string[]): ParsedArgs; export interface ParsedArgs { command: string | undefined; subcommand: string | undefined; positionals: string[]; flags: Record; } -export declare function parseArgs(argv?: string[]): ParsedArgs; -export declare function getFlag(args: ParsedArgs, name: string): string | undefined; -export declare function hasFlag(args: ParsedArgs, name: string): boolean; -export declare function isVerbose(args: ParsedArgs): boolean; -export declare const MINIMAL_FLAG = "_minimal"; -export declare const FULL_FLAG = "_full"; -export declare function isMinimalMode(args: ParsedArgs): boolean; export declare function rejectNoCacheForWrites(args: ParsedArgs): void; export declare function requireFlag(args: ParsedArgs, name: string, description: string): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/blockfrost` - -```ts -declare const BLOCKFROST_NETWORKS: { - readonly preprod: { - readonly host: "midnight-preprod.blockfrost.io"; - readonly prefix: "nightpreprod"; - }; -}; -export type BlockfrostNetwork = keyof typeof BLOCKFROST_NETWORKS; -export declare const BLOCKFROST_SITE = "https://blockfrost.io"; -export declare const SET_PROJECT_ID_COMMAND = "midnight config set blockfrost-project-id "; -export declare function usesBlockfrost(network: string): network is BlockfrostNetwork; -export declare function blockfrostNetworks(): BlockfrostNetwork[]; -export declare function networkOfProjectId(projectId: string): BlockfrostNetwork | undefined; -export declare function checkProjectId(given: string): { - projectId: string; - network: BlockfrostNetwork; -}; +export declare function assertEndpointUsable(url: string): void; export declare function blockfrostEndpoints(network: BlockfrostNetwork, projectId: string | undefined): { indexer: string; indexerWS: string; node: string; }; -export declare function isBlockfrostUrl(url: string): boolean; -export declare class BlockfrostProjectIdRequiredError extends Error { - readonly code = "BLOCKFROST_PROJECT_ID_REQUIRED"; - constructor(network: string); +export declare class BlockfrostLimitError extends Error { + readonly code = "BLOCKFROST_LIMIT_REACHED"; + constructor(status: number); } export declare class BlockfrostProjectIdRejectedError extends Error { readonly code = "BLOCKFROST_PROJECT_ID_REJECTED"; constructor(network: string); } -export declare class BlockfrostLimitError extends Error { - readonly code = "BLOCKFROST_LIMIT_REACHED"; - constructor(status: number); +export declare class BlockfrostProjectIdRequiredError extends Error { + readonly code = "BLOCKFROST_PROJECT_ID_REQUIRED"; + constructor(network: string); } +export declare function endpointRefusal(url: string, status: number): Error | undefined; +export declare function endpointRefusalFromWsError(url: string, error: unknown): Error | undefined; export declare class EndpointShutDownError extends Error { readonly code = "ENDPOINT_SHUT_DOWN"; constructor(url: string); } +export declare function isBlockfrostUrl(url: string): boolean; export declare function isEndpointError(err: unknown): boolean; -export declare function assertEndpointUsable(url: string): void; -export declare function endpointRefusal(url: string, status: number): Error | undefined; -export declare function endpointRefusalFromWsError(url: string, error: unknown): Error | undefined; -export declare const REDACTED = "***"; -export declare function redactProjectId(text: string): string; export declare function mayHoldProjectId(text: string): boolean; -export declare function maskProjectId(projectId: string): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/cache-indexer` - -```ts -export declare function indexerIdentity(indexerUrl: string): string; -export interface IndexerChange { - previous: string; - current: string; - removed: number; -} -export declare function bindCachesToIndexer(network: string, indexerUrl: string, root: string): IndexerChange | undefined; -export declare function describeIndexerChange(network: string, change: IndexerChange): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/call-context` - -```ts -import { type ParsedArgs } from "./argv.ts"; -import type { Payer } from "./payer.ts"; -import type { Settings } from "./settings.ts"; -import type { HostPaths } from "./state-root.ts"; -import type { Host } from "./host.ts"; -import { type CallSdkWarnings } from "./sdk-warnings.ts"; -import { type Progress, type ProgressReport } from "../ui/spinner.ts"; -export interface CallOutput { - result(data: Readonly>): void; - stdout(text: string): void; - stderr(text: string): void; -} -export type CallProgress = Progress; -export interface CallDiagnostics { - readonly isVerbose: boolean; - line(phase: string, message: string): void; -} -export type { CallSdkWarnings } from "./sdk-warnings.ts"; -export interface CallConfig { - readonly settings: Settings; - readonly paths: HostPaths; -} +export declare function redactProjectId(text: string): string; export interface CallContext { readonly signal: AbortSignal; readonly output: CallOutput; @@ -471,93 +91,112 @@ export interface CallContext { readonly payer?: Payer; readonly protectors?: readonly Protector[]; } -export interface CommandOutcome { - readonly exitCode: number; +export declare function callDiagnostics(verbose: boolean, write: (line: string) => void): CallDiagnostics; +export interface CallOutput { + result(data: Readonly>): void; + stdout(text: string): void; + stderr(text: string): void; } +export type CallProgress = Progress; export type CommandHandler = (args: ParsedArgs, ctx: CallContext) => Promise; -export declare class SecondResultError extends Error { - constructor(); -} -export declare function callOutput(sink: CallOutput): CallOutput; -export declare function callDiagnostics(verbose: boolean, write: (line: string) => void): CallDiagnostics; -export interface CallParts { - readonly host: Host; - readonly args: ParsedArgs; - readonly signal: AbortSignal; - readonly output: CallOutput; - readonly onProgress?: ProgressReport; - readonly sdkWarnings?: CallSdkWarnings; - readonly payer?: Payer; - readonly protectors?: readonly Protector[]; +export interface CommandOutcome { + readonly exitCode: number; } export declare function createCallContext(parts: CallParts): CallContext; export declare function runHandler(handler: CommandHandler, args: ParsedArgs, ctx: CallContext): Promise; -``` - -## `@kuiralabs/midnight-cli-core/lib/cli-config` - -```ts -import { type NetworkName } from "./network.ts"; -import type { SdkSet } from "./engine.ts"; -export interface NetworkEndpointOverrides { - "proof-server"?: string; - node?: string; - "indexer-ws"?: string; -} -export interface NetworkSettings extends NetworkEndpointOverrides { - "blockfrost-project-id"?: string; - "sdk-set"?: SdkSet; +export declare class SecondResultError extends Error { + constructor(); } export interface CliConfig { network: NetworkName; networks?: Partial>; - "proof-server"?: string; + 'proof-server'?: string; node?: string; - "indexer-ws"?: string; + 'indexer-ws'?: string; wallet?: string; } -export declare function loadCliConfig(configDir: string): CliConfig; +export declare function getConfigValue(key: string, configDir: string, scope?: NetworkName): string; export declare function getEndpointOverridesForNetwork(config: CliConfig, networkName: NetworkName): NetworkEndpointOverrides; -export declare function getSdkSetOverride(config: CliConfig, networkName: NetworkName): SdkSet | undefined; -export declare function getBlockfrostProjectId(config: CliConfig, networkName: NetworkName): string | undefined; +export declare function loadCliConfig(configDir: string): CliConfig; export declare function saveCliConfig(config: CliConfig, configDir: string): void; -export declare function getConfigValue(key: string, configDir: string, scope?: NetworkName): string; export declare function setConfigValue(key: string, value: string, configDir: string, scope?: NetworkName): void; -export declare function unsetConfigValue(key: string, configDir: string, scope?: NetworkName): void; -export declare function getValidConfigKeys(): readonly string[]; -``` - -## `@kuiralabs/midnight-cli-core/lib/command-definition` - -```ts -import { type ParsedArgs } from "./argv.ts"; -import { type PackageGuidance } from "./agent-guidance.ts"; -import type { CodeDefinition, CodeRegistry, CodeSet } from "./error-codes.ts"; -import type { CallContext, CommandOutcome } from "./call-context.ts"; -import type { Host } from "./host.ts"; -export interface ParamSchema { - readonly type: "string" | "boolean"; - readonly enum?: readonly string[]; - readonly description?: string; +export interface CommandDefinition { + readonly name: string; + readonly order: number; + readonly subcommands?: readonly string[]; + readonly subcommandAliases?: Readonly>; + readonly flags: readonly FlagDefinition[]; + readonly help?: CommandHelp; + readonly intro?: { + readonly brief: string; + readonly order: number; + }; + readonly needsWalletSdk: boolean; + readonly shell: ShellCall; + readonly errors: CommandErrors; + readonly load: () => Promise; + readonly mcp?: { + readonly tools: readonly ToolDefinition[]; + }; } -export declare const NETWORK_PARAM: ParamSchema; +export declare class CommandDefinitionError extends Error { + constructor(message: string); +} +export declare function commandErrorCodes(registry: Pick, command: CommandDefinition): CodeDefinition[]; +export declare function commandExitCodes(registry: Pick, command: CommandDefinition): number[]; +export interface CommandHelpSpec { + readonly name: string; + readonly description: string; + readonly usage: string; + readonly flags?: readonly string[]; + readonly examples?: readonly string[]; + readonly jsonFields?: Readonly>; + readonly errorCodes: readonly CodeDefinition[]; + readonly ownCodes: readonly CodeDefinition[]; + readonly errorSets: readonly string[]; + readonly outcomes: readonly DeclaredOutcome[]; + readonly exitCodes: readonly number[]; +} +export declare function commandHelpSpecs(registry: Pick): CommandHelpSpec[]; +export declare function commandOwnCodes(registry: Pick, command: CommandDefinition): CodeDefinition[]; +export interface CommandPackage { + readonly name: string; + readonly commands: readonly CommandDefinition[]; + readonly guidance: PackageGuidance; + readonly codes?: readonly CodeDefinition[]; +} +export interface CommandRegistry extends CodeRegistry { + readonly commands: readonly CommandDefinition[]; + readonly globalFlags: readonly FlagDefinition[]; + readonly globalFlagsHelp: readonly GlobalFlagHelp[]; + find(name: string): CommandDefinition | undefined; + readonly tools: readonly RegisteredTool[]; + readonly packages: readonly CommandPackage[]; +} +export declare function confirmationTarget(params: Readonly>): { + network: string; + wallet: string; +}; +export declare function confirmationText(tool: ToolDefinition, params: Readonly>): string; +export declare function createCommandRegistry(commands: readonly CommandDefinition[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; +export declare function createPackageRegistry(packages: readonly CommandPackage[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; +export declare function declaredCodes(command: CommandDefinition): string[]; +export declare function declaredCodeSets(registry: Pick): CodeSet[]; +export declare function declaredSets(command: CommandDefinition): CodeSet[]; export declare const ENDPOINT_PARAMS: { readonly node: { readonly type: "string"; readonly description: "Node RPC URL (default: the configured one, or the network's)"; }; - readonly "indexer-ws": { + readonly 'indexer-ws': { readonly type: "string"; readonly description: "Indexer WebSocket URL (default: the configured one, or the network's)"; }; - readonly "proof-server": { + readonly 'proof-server': { readonly type: "string"; readonly description: "Proof server URL (default: the configured one, or the network's)"; }; }; -export interface NotForAgents { - readonly notForAgents: string; -} export interface FlagDefinition { readonly name: string; readonly takesValue: boolean; @@ -565,24 +204,19 @@ export interface FlagDefinition { readonly help?: readonly string[]; readonly agent?: ParamSchema | NotForAgents; } -export type FlagsSectionEntry = string | { - readonly flag: string; -}; -export interface CommandHelp { +export interface GlobalFlagHelp { + readonly name: string; readonly description: string; - readonly usage: string; - readonly flags?: readonly FlagsSectionEntry[]; - readonly examples?: readonly string[]; - readonly jsonFields?: Readonly>; } -export interface ShellCall { - readonly payer?: true; - readonly protectors?: true; - readonly notice?: string; - readonly unavailable?: string; -} -export interface CommandModule { - default(args: ParsedArgs, ctx: CallContext): Promise; +export declare function introBriefs(registry: Pick): [ + name: string, + brief: string +][]; +export declare function needsConfirmation(tool: ToolDefinition, params: Readonly>): boolean; +export declare const NETWORK_PARAM: ParamSchema; +export interface RegisteredTool extends ToolDefinition { + readonly inputSchema: ToolInputSchema; + readonly command: CommandDefinition; } export interface ToolAnnotations { readonly readOnlyHint?: boolean; @@ -590,37 +224,12 @@ export interface ToolAnnotations { readonly idempotentHint?: boolean; readonly openWorldHint?: boolean; } -export interface ToolInputSchema { - readonly type: "object"; - readonly properties: Readonly>; - readonly required?: readonly string[]; -} -export type ToolParam = { - readonly name: string; - readonly schema: ParamSchema; -} | { - readonly flag: string; - readonly schema?: ParamSchema; -}; -export interface ToolArgv { - readonly subcommand?: string | { - readonly param: string; - }; - readonly positionals?: readonly string[]; - readonly flags: "rest" | readonly string[]; - readonly fixedFlags?: Readonly>; - readonly defaultFlags?: Readonly>; -} +export declare function toolArgv(tool: RegisteredTool, params: Readonly>): ParsedArgs; export interface ToolCheckCall { readonly host: Host; argv(): ParsedArgs; run(args: ParsedArgs): Promise>; } -export interface ToolConfirmation { - readonly when?: (params: Readonly>) => boolean; - readonly describe?: (params: Readonly>) => string; - readonly check?: (params: Readonly>, call: ToolCheckCall) => Promise; -} export interface ToolDefinition { readonly name: string; readonly description: string; @@ -631,291 +240,107 @@ export interface ToolDefinition { readonly confirmation?: ToolConfirmation; readonly order: number; } -export interface DeclaredOutcome { - readonly exitCode: number; - readonly when: string; +export interface ToolInputSchema { + readonly type: 'object'; + readonly properties: Readonly>; + readonly required?: readonly string[]; } -export interface CommandErrors { - readonly codes: readonly (string | CodeSet)[]; - readonly outcomes?: readonly DeclaredOutcome[]; +export declare function assertKnownFlags(args: ParsedArgs, registry: FlagRegistry): void; +export declare function findMisplacedFlags(args: ParsedArgs, registry: FlagRegistry): Array<{ + flag: string; + subcommands: readonly string[]; +}>; +export declare function findUnknownFlags(args: ParsedArgs, registry: FlagRegistry): string[]; +export type APIError = Error & { + type: 'DAppConnectorAPIError'; + code: ErrorCode; + reason: string; +}; +export declare function createApiError(code: ErrorCode, reason: string, mnCode?: string): APIError; +export type ErrorCode = 'InternalError' | 'Rejected' | 'InvalidRequest' | 'PermissionRejected' | 'Disconnected'; +export declare const OPERATOR_REJECTED_MESSAGE = "User rejected the request"; +export type RpcHandler = (params: Record, context: RpcHandlerContext) => Promise; +export interface RpcHandlerContext { + notify: (method: string, params?: Record) => void; + connectionId: string; + requestId: number | string; + metadata: Record; } -export interface CommandDefinition { - readonly name: string; - readonly order: number; - readonly subcommands?: readonly string[]; - readonly subcommandAliases?: Readonly>; - readonly flags: readonly FlagDefinition[]; - readonly help?: CommandHelp; - readonly intro?: { - readonly brief: string; - readonly order: number; - }; - readonly needsWalletSdk: boolean; - readonly shell: ShellCall; - readonly errors: CommandErrors; - readonly load: () => Promise; - readonly mcp?: { - readonly tools: readonly ToolDefinition[]; - }; -} -export interface CommandPackage { - readonly name: string; - readonly commands: readonly CommandDefinition[]; - readonly guidance: PackageGuidance; - readonly codes?: readonly CodeDefinition[]; -} -export interface RegisteredTool extends ToolDefinition { - readonly inputSchema: ToolInputSchema; - readonly command: CommandDefinition; -} -export interface GlobalFlagHelp { - readonly name: string; - readonly description: string; -} -export interface CommandRegistry extends CodeRegistry { - readonly commands: readonly CommandDefinition[]; - readonly globalFlags: readonly FlagDefinition[]; - readonly globalFlagsHelp: readonly GlobalFlagHelp[]; - find(name: string): CommandDefinition | undefined; - readonly tools: readonly RegisteredTool[]; - readonly packages: readonly CommandPackage[]; -} -export declare class CommandDefinitionError extends Error { - constructor(message: string); -} -export declare function toolInputSchema(command: CommandDefinition, tool: ToolDefinition, globalFlags: readonly FlagDefinition[]): ToolInputSchema; -export declare function toolArgv(tool: RegisteredTool, params: Readonly>): ParsedArgs; -export declare function declaredCodes(command: CommandDefinition): string[]; -export declare function declaredSets(command: CommandDefinition): CodeSet[]; -export declare function declaredCodeSets(registry: Pick): CodeSet[]; -export declare function commandErrorCodes(registry: Pick, command: CommandDefinition): CodeDefinition[]; -export declare function commandOwnCodes(registry: Pick, command: CommandDefinition): CodeDefinition[]; -export declare function commandExitCodes(registry: Pick, command: CommandDefinition): number[]; -export declare function createCommandRegistry(commands: readonly CommandDefinition[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; -export declare function createPackageRegistry(packages: readonly CommandPackage[], globalFlags: readonly FlagDefinition[], globalFlagsHelp?: readonly GlobalFlagHelp[]): CommandRegistry; -export declare function flagsSectionLines(command: CommandDefinition): string[]; -export interface CommandHelpSpec { - readonly name: string; - readonly description: string; - readonly usage: string; - readonly flags?: readonly string[]; - readonly examples?: readonly string[]; - readonly jsonFields?: Readonly>; - readonly errorCodes: readonly CodeDefinition[]; - readonly ownCodes: readonly CodeDefinition[]; - readonly errorSets: readonly string[]; - readonly outcomes: readonly DeclaredOutcome[]; - readonly exitCodes: readonly number[]; -} -export declare function commandHelpSpecs(registry: Pick): CommandHelpSpec[]; -export declare function introBriefs(registry: Pick): [ - name: string, - brief: string -][]; -export declare function confirmationTarget(params: Readonly>): { - network: string; - wallet: string; -}; -export declare function needsConfirmation(tool: ToolDefinition, params: Readonly>): boolean; -export declare function confirmationText(tool: ToolDefinition, params: Readonly>): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/command-flags` - -```ts -import { type ParsedArgs } from "./argv.ts"; -import type { CommandRegistry } from "./command-definition.ts"; -type FlagRegistry = Pick; -export declare function findUnknownFlags(args: ParsedArgs, registry: FlagRegistry): string[]; -export declare function findMisplacedFlags(args: ParsedArgs, registry: FlagRegistry): Array<{ - flag: string; - subcommands: readonly string[]; -}>; -export declare function assertKnownFlags(args: ParsedArgs, registry: FlagRegistry): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/connector-api` - -```ts -export type ErrorCode = "InternalError" | "Rejected" | "InvalidRequest" | "PermissionRejected" | "Disconnected"; -export type APIError = Error & { - type: "DAppConnectorAPIError"; - code: ErrorCode; - reason: string; -}; -export interface RpcHandlerContext { - notify: (method: string, params?: Record) => void; - connectionId: string; - requestId: number | string; - metadata: Record; -} -export type RpcHandler = (params: Record, context: RpcHandlerContext) => Promise; -export declare function createApiError(code: ErrorCode, reason: string, mnCode?: string): APIError; -export declare const OPERATOR_REJECTED_MESSAGE = "User rejected the request"; -``` - -## `@kuiralabs/midnight-cli-core/lib/constants` - -```ts -export declare const GENESIS_SEED = "0000000000000000000000000000000000000000000000000000000000000001"; -export declare const NATIVE_TOKEN_TYPE = "0000000000000000000000000000000000000000000000000000000000000000"; -export declare const INDEXER_API_VERSION = "v4"; -export declare const INDEXER_GRAPHQL_PATH = "/api/v4/graphql"; -export declare const INDEXER_GRAPHQL_WS_PATH = "/api/v4/graphql/ws"; -export declare const TOKEN_DECIMALS = 6; -export declare const TOKEN_MULTIPLIER = 1000000; -export declare const DUST_COST_OVERHEAD = 300000000000000n; -export declare const DUST_FEE_BLOCKS_MARGIN = 5; -export declare const MIN_DUST_FOR_TRANSFER = 900000000000000n; -export declare const INITIAL_NIGHT_DUST_RATIO = 5000000000n; -export declare const INITIAL_GENERATION_DECAY_RATE = 8267n; -export declare const INITIAL_DUST_GRACE_PERIOD_SECONDS = 10800n; -export declare const SYNC_TIMEOUT_MS = 300000; -export declare const SYNC_ATTEMPT_TIMEOUT_MS = 30000; -export declare const SYNC_ATTEMPT_REMOTE_TIMEOUT_MS = 120000; -export declare const PRE_SEND_SYNC_TIMEOUT_MS = 10000; -export declare const DUST_TIMEOUT_MS = 120000; -export declare const PROOF_TIMEOUT_MS = 300000; export declare const BALANCE_CHECK_TIMEOUT_MS = 60000; -export declare const SYNC_HEAP_TARGET_MB = 16384; -export declare const SYNC_HEAP_RAM_FRACTION = 0.7; -export declare const SYNC_HEAP_MIN_GAIN_MB = 512; -export declare const TX_TTL_MINUTES = 10; -export declare const MAX_RETRY_ATTEMPTS = 3; -export declare const RETRY_BASE_DELAY_MS = 1000; -export declare const DUST_REGISTRATION_TIMEOUT_MS = 600000; -export declare const DUST_REGISTRATION_RETRY_DELAY_MS = 15000; -export declare const STALE_UTXO_ERROR_CODE = 115; -export declare const BALANCE_OVERSPEND_ERROR_CODE = 138; -export declare const MIDNIGHT_DIR = ".midnight"; +export declare const DASHBOARD_BASE_URL = "https://midnight-comp-tracker.vercel.app"; +export declare const DEFAULT_SERVE_PORT = 9932; export declare const DEFAULT_WALLET_FILENAME = "wallet.json"; -export declare const DEFAULT_CONFIG_FILENAME = "config.json"; +export declare const DEFAULT_WALLET_NAME = "default"; export declare const DIR_MODE = 448; export declare const FILE_MODE = 384; +export declare const GENESIS_SEED = "0000000000000000000000000000000000000000000000000000000000000001"; +export declare function isValidWalletName(name: string): boolean; export declare const LOCALNET_DIR_NAME = "localnet"; -export declare const CACHE_VERSION = 2; -export declare const CACHE_DIR_NAME = "cache"; +export declare const MIDNIGHT_DIR = ".midnight"; +export declare const NATIVE_TOKEN_TYPE = "0000000000000000000000000000000000000000000000000000000000000000"; +export declare const SYNC_HEAP_MIN_GAIN_MB = 512; +export declare const SYNC_HEAP_RAM_FRACTION = 0.7; +export declare const SYNC_HEAP_TARGET_MB = 16384; export declare const WALLETS_DIR_NAME = "wallets"; -export declare const DEFAULT_WALLET_NAME = "default"; -export declare function isValidWalletName(name: string): boolean; -export declare const DUST_RETRY_ATTEMPTS = 10; -export declare const DUST_RETRY_DELAY_MS = 3000; -export declare const ABANDONED_TX_TIMEOUT_MS = 120000; -export declare const DEFAULT_SERVE_PORT = 9932; -export declare const DASHBOARD_BASE_URL = "https://midnight-comp-tracker.vercel.app"; -``` - -## `@kuiralabs/midnight-cli-core/lib/durable-file` - -```ts export declare class FileExistsError extends Error { constructor(file: string); } +export declare function readJsonIfPresent(file: string): T | undefined; export declare function writeJsonDurably(file: string, value: unknown, { exclusive }?: { exclusive?: boolean; }): void; -export declare function readJsonIfPresent(file: string): T | undefined; -``` - -## `@kuiralabs/midnight-cli-core/lib/duration` - -```ts export declare function formatWait(ms: number): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/dust-balancing-plan` - -```ts -export interface DustInput { - token: TToken; - value: bigint; -} -export type DustPlan = { - kind: "covered"; - fee: bigint; - inputs: DustInput[]; -} | { - kind: "short"; - atFirstChoice: boolean; -}; -export interface DustPlanOptions { - owed: bigint; - coinCount: number; - choose: (owed: bigint) => DustInput[] | undefined; - feeWith: (inputs: readonly DustInput[]) => bigint; +export declare function dustShortError(have: bigint, needed: bigint, waitMs: number | null): DustRequiredError; +export declare const OWN_COMMAND_DUST_WAIT_MS: number; +export interface BalanceSummary { + balances: Map; + utxoCount: number; + txCount: number; + highestTxId: number; + registeredUtxos: number; + unregisteredUtxos: number; } -export declare function chooseDustCoins(coins: readonly DustInput[], owed: bigint, combine: (owed: bigint) => DustInput[] | undefined): DustInput[] | undefined; -export declare function planDustInputs({ owed, coinCount, choose, feeWith }: DustPlanOptions): DustPlan; -export declare function spreadFeeAcrossInputs(inputs: readonly DustInput[], fee: bigint): DustInput[]; -``` - -## `@kuiralabs/midnight-cli-core/lib/dust-registration-plan` - -```ts -export interface DustGenerationEstimate { - dust: { - generatedNow: bigint; - rate: bigint; - maxCap: bigint; - }; +export interface DAppConnector { + handlers: Record; + revertPendingTxs(connectionId: string): Promise; + handOffPendingTx(connectionId: string, txHex: string): boolean; + takeOffer(connectionId: string, txHex: string): Promise; + cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; + hasPendingTxs(): boolean; + dispose(): void; } -export interface RegistrationPlan { - fee: bigint; - generated: bigint; - ratePerSecond: bigint; - cap: bigint; - waitMs: number | null; +export interface DAppConnectorCallbacks { + onPhaseStart?: (connectionId: string, method: string, phase: string) => void; + onPhaseComplete?: (connectionId: string, method: string, phase: string, durationMs: number) => void; } -export declare function planRegistration(fee: bigint, estimates: readonly DustGenerationEstimate[]): RegistrationPlan; -export declare class DustFeeNotGeneratedError extends Error { - readonly code = "DUST_GENERATING"; - constructor(plan: RegistrationPlan, now: Date); +export interface DustExportResult { + network: string; + dustPublicKey: string; + offset: number; + balance: bigint; + eventCount: number; + fromCache: boolean; + partial: boolean; + snapshot: string; } -``` - -## `@kuiralabs/midnight-cli-core/lib/dust-wait` - -```ts -import { sleep } from "./sleep.ts"; -import { DustRequiredError } from "./errors.ts"; -export interface DustBalanceSource { - balance(at: Date): bigint; +export interface Engine { + readonly set: SdkSet; + readonly keys: EngineKeys; + readonly ledger: EngineLedger; + readonly contracts: EngineContracts; + readonly readers: EngineReaders; + readonly wallet: EngineWallet; } -export declare const DUST_SHORT_WAIT_MS: number; -export declare const OWN_COMMAND_DUST_WAIT_MS: number; -export declare const LOOK_AHEAD_MS: number; -export declare function msUntilDust(dust: DustBalanceSource, needed: bigint, now: Date, horizonMs: number): number | null; -export declare function dustShortError(have: bigint, needed: bigint, waitMs: number | null): DustRequiredError; -export declare function awaitDustForFee(dust: DustBalanceSource, needed: bigint, onStatus?: (status: string) => void, signal?: AbortSignal): Promise; -export interface DustWaitPlan { - have: bigint; - needed: bigint; - waitMs: number | null; +export interface EngineContractScripts { + readonly packages: readonly string[]; + packageFolder(name: string): string | null; + readonly compactRuntimeVersion: string; + readonly compiler: string; + acceptsRuntime(runtimeVersion: string): boolean; + deploy(script: DeployScript, parts: ScriptParts): string; + call(script: CallScript, parts: ScriptParts): string; + state(script: StateScript, parts: ScriptParts): string; } -export declare function planDustWait(err: unknown, dust: DustBalanceSource, now: Date): DustWaitPlan | undefined; -export declare function payWhenDustCovers(pay: () => Promise, dust: DustBalanceSource, options: { - maxWaitMs: number; - onStatus?: (status: string) => void; - signal?: AbortSignal; -}): Promise; -export { sleep }; -``` - -## `@kuiralabs/midnight-cli-core/lib/engine` - -```ts -import type { OfferContents } from "./swap-offer.ts"; -import type { OpenOffer } from "./open-offers.ts"; -import { type NetworkConfig, type NetworkName } from "./network.ts"; -import type { CallSdkWarnings } from "./sdk-warnings.ts"; -import type { VerboseLog } from "./verbose.ts"; -import type { ApprovalOptions } from "./approval.ts"; -import type { NoticeSink } from "./notices.ts"; -import type { FeeLimits } from "./fee-limits.ts"; -import type { RpcHandler } from "./connector-api.ts"; -import type { Spinner } from "../ui/spinner.ts"; -import type { Host } from "./host.ts"; -export type SdkSet = "rc" | "beta"; export interface EngineKeys { unshieldedAddress(seed: Buffer, network: NetworkName, keyIndex?: number): string; unshieldedAddresses(seed: Buffer, keyIndex?: number): Record; @@ -923,39 +348,37 @@ export interface EngineKeys { shieldedAddresses(seed: Buffer): Record; dustPublicKeyHex(seed: Buffer): string; shieldedCoinPublicKeyHex(seed: Buffer): string; - assertAddress(address: string, kind: "shielded" | "unshielded", network: NetworkName): void; -} -export interface TransactionDetail { - label: string; - value: string; + assertAddress(address: string, kind: 'shielded' | 'unshielded', network: NetworkName): void; } -export interface BlockLimits { - readTime: number; - computeTime: number; - blockUsage: number; - bytesWritten: number; - bytesChurned: number; +export interface HostEngines { + load(set: SdkSet): Promise; + for(network: NetworkName): Promise; + any(): Promise; + prefer(network: NetworkName): void; } -export interface EngineLedger { - blockLimits(parametersHex: string): BlockLimits; - nightTokenId(): string; - readTransaction(txHex: string, stage: "unsealed" | "sealed"): TransactionDetail[]; - readOffer(txHex: string): OfferContents; - spentNullifiers(txHex: string): string[]; +export interface OpenedConnector { + connector: DAppConnector; + stop(): Promise; } -export type RawStateValue = { - type: "null"; -} | { - type: "cell"; - value: string[]; +export declare class OtherSdkSetError extends Error { + readonly code = "OTHER_SDK_SET"; + readonly loadedSet: SdkSet; + readonly wantedSet: SdkSet; + constructor(loadedSet: SdkSet, wantedSet: SdkSet, message?: string); +} +export type RawStateValue = { + type: 'null'; +} | { + type: 'cell'; + value: string[]; } | { - type: "array"; + type: 'array'; items: RawStateValue[]; } | { - type: "map"; + type: 'map'; size: number; } | { - type: "boundedMerkleTree"; + type: 'boundedMerkleTree'; height: number; root: string[] | null; }; @@ -968,1028 +391,1008 @@ export interface ScriptParts { readonly indexerUrlEnv: string; readonly indexerWsUrlEnv: string; } -export interface ScriptContract { - networkConfig: NetworkConfig; - managedDir: string; - contractName: string; +export type SdkSet = 'rc' | 'beta'; +export declare function sdkSetOf(network: NetworkName, root: string): SdkSet; +export interface CodeDefinition { + readonly code: string; + readonly exitCode: number; + readonly summary: string; + readonly recovery?: string; + readonly order?: number; } -export interface DeployScript extends ScriptContract { - servePort: number; - privateStateKey?: string; - args?: unknown[]; +export declare class CodeDefinitionError extends Error { + constructor(message: string); } -export interface CallScript extends ScriptContract { - servePort: number; - contractAddress: string; - circuit: string; - args?: unknown[]; - privateStateKey?: string; +export interface CodeRegistry { + code(code: string): CodeDefinition | undefined; } -export interface StateScript extends ScriptContract { - contractAddress: string; +export interface CodeSet { + readonly name: string; + readonly codes: readonly string[]; } -export interface EngineContractScripts { - readonly packages: readonly string[]; - packageFolder(name: string): string | null; - readonly compactRuntimeVersion: string; - readonly compiler: string; - acceptsRuntime(runtimeVersion: string): boolean; - deploy(script: DeployScript, parts: ScriptParts): string; - call(script: CallScript, parts: ScriptParts): string; - state(script: StateScript, parts: ScriptParts): string; +export declare function defineCodes(codes: T): T; +export declare function defineCodeSet(name: string, codes: readonly string[]): CodeSet; +export declare function trimAgentMessage(raw: string): string; +export declare function asReported(err: Error): Error; +export declare const CANCELLED_MESSAGE = "Operation cancelled"; +export declare class CancelledError extends Error { + readonly code = "CANCELLED"; + constructor(message?: string); } -export interface EngineContracts { - rawState(networkConfig: NetworkConfig, address: string): Promise; - acceptsPrivateStatePassword(password: string): boolean; - readonly scripts: EngineContractScripts; +export declare class CommandFailedError extends Error { + readonly code = "COMMAND_FAILED"; + readonly exitCode: number; + readonly result: Readonly>; + constructor(command: string, exitCode: number, result: Readonly>); } -export interface ShieldedBalanceResult { - balance: bigint; - availableCoins: number; - tokens: ReadonlyMap; - eventCount: number; - lastAppliedEventId: number; - fromCache: boolean; - partial: boolean; +export declare class DustRequiredError extends Error { + readonly code = "DUST_REQUIRED"; + constructor(message: string, options?: { + cause?: unknown; + }); } -export interface ShieldedCachedOptions { - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - signal?: AbortSignal; - timeoutMs?: number; - forceFresh?: boolean; - chainId?: string; - root: string; +export declare class InsufficientBalanceError extends Error { + readonly code = "INSUFFICIENT_BALANCE"; + constructor(message: string, options?: { + cause?: unknown; + }); } -export interface EngineReaders { - shieldedBalance(seed: Buffer, network: NetworkName, indexerWS: string, options: ShieldedCachedOptions): Promise; +export declare function isUsageError(err: unknown): err is UsageError; +export declare class NetworkError extends Error { + readonly code = "NETWORK_ERROR"; + constructor(message: string, options?: { + cause?: unknown; + }); } -export interface BalanceSummary { - balances: Map; - utxoCount: number; - txCount: number; - highestTxId: number; - registeredUtxos: number; - unregisteredUtxos: number; +export declare class ProofFailureError extends EngineError { + constructor(message: string, options?: { + cause?: unknown; + }); } -export interface TransferParams { - seedBuffer: Buffer; - networkConfig: NetworkConfig; - recipientAddress: string; - amount: bigint; - signal?: AbortSignal; - onSync?: (applied: number, highest: number) => void; - onSyncDetail?: (walletsStillSyncing: string) => void; - onDust?: (status: string) => void; - onProving?: () => void; - onSubmitting?: () => void; - onSubmittingTick?: (elapsedMs: number) => void; - onSyncWarning?: (tag: string, message: string) => void; - sdkWarnings: CallSdkWarnings; - log?: VerboseLog; - root: string; - notice: NoticeSink; +export declare class SyncTimeoutError extends Error { + readonly code = "SYNC_TIMEOUT"; + constructor(message: string, options?: { + cause?: unknown; + }); } -export interface TransferResult { - txHash: string; - amountMicroNight: bigint; +export declare function throwIfCancelled(signal: AbortSignal | undefined): void; +export declare class TransactionRefusedError extends Error { + readonly reason: string; + readonly code: RefusalCode; + constructor(reason: string, options?: { + cause?: unknown; + code?: RefusalCode; + }); } -export interface EnsureDustResult { - alreadyAvailable: boolean; - txHash?: string; +export declare class UsageError extends Error { + readonly code: string; + constructor(message: string); } -export type AirdropParams = Omit; -export interface DustRegisterOptions { - signal?: AbortSignal; - onStatus?: (status: string) => void; - onSyncProgress?: (applied: number, highest: number) => void; - onSyncDetail?: (detail: string) => void; - onSyncWarning?: (tag: string, message: string) => void; - sdkWarnings: CallSdkWarnings; - log?: VerboseLog; - root: string; - notice: NoticeSink; +export declare const execProgram: ExecRunner; +export interface ExecRun { + readonly signal: AbortSignal; + readonly timeoutMs?: number; + readonly onStderr?: (text: string) => void; } -export interface DustRegistration { - alreadyAvailable: boolean; - txHash?: string; - dustBalance: bigint; +export type ExecRunner = (file: string, args: readonly string[], run: ExecRun) => Promise; +export declare class ProgramFailedError extends Error { + readonly command: string; + readonly exitCode: number | null; + readonly stderr: string; + readonly stdout: string; + constructor(command: string, exitCode: number | null, stderr: string, stdout: string); } -export interface DustExportResult { - network: string; - dustPublicKey: string; - offset: number; - balance: bigint; - eventCount: number; - fromCache: boolean; - partial: boolean; - snapshot: string; +export declare class ProgramTimedOutError extends Error { + readonly command: string; + readonly code = "NETWORK_ERROR"; + constructor(command: string, timeoutMs: number); } -export interface UnshieldedView extends BalanceSummary { - fromCache: boolean; - fetchedAt: number; +export declare function classifyError(err: Error, codes: CodeRegistry): ClassifiedError; +export declare const ERROR_CODES: { + readonly INVALID_ARGS: "INVALID_ARGS"; + readonly WALLET_NOT_FOUND: "WALLET_NOT_FOUND"; + readonly NETWORK_ERROR: "NETWORK_ERROR"; + readonly INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE"; + readonly TX_REJECTED: "TX_REJECTED"; + readonly STALE_UTXO: "STALE_UTXO"; + readonly STALE_CACHE: "STALE_CACHE"; + readonly PROOF_TIMEOUT: "PROOF_TIMEOUT"; + readonly PROOF_FAILURE: "PROOF_FAILURE"; + readonly INVALID_DUST_PROOF: "INVALID_DUST_PROOF"; + readonly DUST_REQUIRED: "DUST_REQUIRED"; + readonly DUST_GENERATING: "DUST_GENERATING"; + readonly CHAIN_CLOCK_BEHIND: "CHAIN_CLOCK_BEHIND"; + readonly SYNC_TIMEOUT: "SYNC_TIMEOUT"; + readonly CANCELLED: "CANCELLED"; + readonly UNSUPPORTED_LEDGER: "UNSUPPORTED_LEDGER"; + readonly LOCALNET_UNAVAILABLE: "LOCALNET_UNAVAILABLE"; + readonly LOCAL_STACK_UNREACHABLE: "LOCAL_STACK_UNREACHABLE"; + readonly AMBIGUOUS_LOCAL_STACKS: "AMBIGUOUS_LOCAL_STACKS"; + readonly UNSUPPORTED_NODE: "UNSUPPORTED_NODE"; + readonly NO_ACCOUNT: "NO_ACCOUNT"; + readonly BLOCKFROST_PROJECT_ID_REQUIRED: "BLOCKFROST_PROJECT_ID_REQUIRED"; + readonly BLOCKFROST_PROJECT_ID_REJECTED: "BLOCKFROST_PROJECT_ID_REJECTED"; + readonly BLOCKFROST_LIMIT_REACHED: "BLOCKFROST_LIMIT_REACHED"; + readonly ENDPOINT_SHUT_DOWN: "ENDPOINT_SHUT_DOWN"; + readonly OTHER_SDK_SET: "OTHER_SDK_SET"; + readonly MIXED_SDK_LAYOUT: "MIXED_SDK_LAYOUT"; + readonly NOT_AN_OFFER: "NOT_AN_OFFER"; + readonly TERMS_MISMATCH: "TERMS_MISMATCH"; + readonly OFFER_EXPIRED: "OFFER_EXPIRED"; + readonly OFFER_COINS_IN_USE: "OFFER_COINS_IN_USE"; + readonly WRONG_PASSPHRASE: "WRONG_PASSPHRASE"; + readonly PASSPHRASE_REQUIRED: "PASSPHRASE_REQUIRED"; + readonly NO_STATE_ROOT: "NO_STATE_ROOT"; + readonly NO_PAYER: "NO_PAYER"; + readonly NO_NODE_RUNTIME: "NO_NODE_RUNTIME"; + readonly COMMAND_FAILED: "COMMAND_FAILED"; + readonly UNKNOWN: "UNKNOWN"; +}; +export declare const EXIT_CANCELLED = 7; +export declare const EXIT_GENERAL_ERROR = 1; +export declare const EXIT_INSUFFICIENT_BALANCE = 5; +export declare const EXIT_INVALID_ARGS = 2; +export declare const EXIT_NETWORK_ERROR = 4; +export declare const EXIT_TX_REJECTED = 6; +export declare const EXIT_WALLET_NOT_FOUND = 3; +export declare function humanizeNetworkError(message: string): string; +export declare function parseFeeLimits(maxFee: string | undefined, maxPending: string | undefined): FeeLimits; +export declare function createHost(options?: HostOptions): Host; +export declare function defineHostSlot(name: string, init: () => T): HostSlot; +export interface Host { + settings(): Settings; + paths(): HostPaths; + notice(line: string): void; + readonly prompter: Prompter | null; + readonly sdkWarnings: SdkWarningCalls; + readonly engines: HostEngines; + slot(key: HostSlot): T; } -export interface ReadOptions { - forceFresh?: boolean; - signal?: AbortSignal; - onStatus?: (s: string) => void; - onProgress?: (current: number, highest: number) => void; - log?: VerboseLog; +export interface HostOptions { + readonly paths?: Supplied; + readonly settings?: Supplied; + readonly notice?: (line: string) => void; + readonly prompter?: Prompter | null; + readonly sdkWarnings?: SdkWarningCalls; + readonly engineLoader?: EngineLoader; } -export interface CachedReadOptions extends ReadOptions { - root: string; - notice: NoticeSink; -} -export interface DustBalance { - balance: bigint; - availableCoins: number; - ownedUtxoCount: number; - syncTime: Date; - fromCache: boolean; - eventsApplied: number; - lastAppliedEventId: number; - partial: boolean; - fetchedAt: number; -} -export interface WalletSyncHooks { - signal?: AbortSignal; - log?: VerboseLog; - onStatus?: (status: string) => void; - onSyncProgress?: (applied: number, highest: number) => void; - onSyncDetail?: (detail: string) => void; +export declare function writeJsonError(err: Error, errorCode: string, exitCode: number): void; +export declare function writeJsonResult(data: Readonly>): void; +export declare function freshDataKey(): Buffer; +export declare function isSealedSecret(value: unknown): value is SealedSecret; +export interface KeyedSecret { + v: 1; + iv: string; + tag: string; + ciphertext: string; } -export interface ShieldedTransferParams extends WalletSyncHooks { - seed: Buffer; - root: string; - notice: NoticeSink; - network: NetworkName; - networkConfig: NetworkConfig; - recipient: string; - amount: bigint; - progress: Spinner; - insufficient: (availableNight: string) => string; - waitForDustToCover: boolean; - onSenderShieldedAddress?: (address: string) => void; +export declare function openSecret(sealed: unknown, passphrase: string, purpose: SecretPurpose): Buffer; +export declare function openWithKey(key: Uint8Array, sealed: unknown, purpose: SecretPurpose): Buffer; +export interface SealedSecret { + v: 1; + kdf: 'scrypt'; + n: number; + r: number; + p: number; + salt: string; + iv: string; + tag: string; + ciphertext: string; } -export interface PrepWallet { - seed: Buffer; - root: string; - notice: NoticeSink; - network: NetworkName; - networkConfig: NetworkConfig; - address: string; - signal?: AbortSignal; - onMessage: (message: string) => void; +export declare function sealSecret(secret: Uint8Array, passphrase: string, purpose: SecretPurpose): SealedSecret; +export declare function sealWithKey(key: Uint8Array, secret: Uint8Array, purpose: SecretPurpose): KeyedSecret; +export declare class WrongPassphraseError extends Error { + readonly code = "WRONG_PASSPHRASE"; + constructor(message?: string); } -export interface DAppConnectorCallbacks { - onPhaseStart?: (connectionId: string, method: string, phase: string) => void; - onPhaseComplete?: (connectionId: string, method: string, phase: string, durationMs: number) => void; +export declare class AmbiguousLocalStacksError extends Error { + readonly code = "AMBIGUOUS_LOCAL_STACKS"; + constructor(found: LocalStackPorts); } -export interface DAppConnector { - handlers: Record; - revertPendingTxs(connectionId: string): Promise; - handOffPendingTx(connectionId: string, txHex: string): boolean; - takeOffer(connectionId: string, txHex: string): Promise; - cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; - hasPendingTxs(): boolean; - dispose(): void; +export declare function applyEndpointOverrides(config: NetworkConfig, flagOverrides: EndpointOverrides, networkName: NetworkName, configDir: string): NetworkConfig; +export declare function detectLocalStacks(settings: Pick): LocalStackPorts; +export declare function endpointFlags(e: EndpointOverrides): Record; +export interface EndpointOverrides { + proofServer?: string; + node?: string; + indexerWS?: string; } -export interface OpenedConnector { - connector: DAppConnector; - stop(): Promise; +export declare function getNetworkConfig(name: NetworkName): NetworkConfig; +export declare function getValidNetworkNames(): readonly string[]; +export declare function isValidNetworkName(name: string): name is NetworkName; +export declare const LEDGER_9_FORK_VERSION = 2000000n; +export interface NetworkConfig { + indexer: string; + indexerWS: string; + node: string; + proofServer: string; + networkId: string; } -export interface ServedWalletSession { - waitForDust(): Promise; - saveState(): Promise; - connect(options: { - approvalOptions: ApprovalOptions; - feeLimits?: FeeLimits; - callbacks?: DAppConnectorCallbacks; - }): DAppConnector; +export type NetworkName = 'preprod' | 'preview' | 'stagenet' | 'undeployed'; +export declare function networksOnSdkSet(set: SdkSet, root: string): NetworkName[]; +export declare function resolveNetworkConfig(name: NetworkName, options?: ResolveNetworkConfigOptions): NetworkConfig; +export declare function sdkSetOfNetwork(name: NetworkName, root: string): SdkSet; +export interface NetworkChoice extends EndpointOverrides { + network?: NetworkName; } -export interface EngineWallet { - unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; - dustBalance(seed: Buffer, networkConfig: NetworkConfig, options: CachedReadOptions): Promise; - transfer(params: TransferParams): Promise; - airdrop(params: AirdropParams): Promise; - shieldedTransfer(params: ShieldedTransferParams): Promise; - registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; - exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { - root: string; - notice: NoticeSink; - signal?: AbortSignal; - log?: VerboseLog; - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - }): Promise; - prepNightBalance(wallet: PrepWallet): Promise; - prepDust(wallet: PrepWallet, waitMs: number): Promise<{ - alreadyAvailable: boolean; - dustAvailable: boolean; - }>; - openConnector(options: { - seed: Buffer; - root: string; - notice: NoticeSink; - network: NetworkName; - networkConfig: NetworkConfig; - address: string; - syncMode: "full" | "lite"; - dustWaitMs?: number; - signal?: AbortSignal; - onMessage: (message: string) => void; - }): Promise; - serveWallet(options: { - seed: Buffer; - root: string; - notice: NoticeSink; - networkConfig: NetworkConfig; - network: NetworkName; - address: string; - syncMode: "full" | "lite"; - } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; +export declare function networkChoiceFromArgs(args: ParsedArgs): NetworkChoice; +export declare function networkTargetOf(host: Host, choice?: NetworkChoice): PayingTarget; +export type NoticeSink = (line: string) => void; +export declare function assertEnvelopeMatches(envelope: OfferEnvelope, read: OfferContents): void; +export declare function assertOfferUnexpired(envelope: OfferEnvelope, now: Date): void; +export declare function decodeOfferEnvelope(text: string): OfferEnvelope; +export declare function encodeOfferEnvelope(envelope: OfferEnvelope): string; +export interface OfferEnvelope { + network: NetworkName; + id: string; + terms: SwapTerms; + expiresAt: Date; + tx: string; } -export interface Engine { - readonly set: SdkSet; - readonly keys: EngineKeys; - readonly ledger: EngineLedger; - readonly contracts: EngineContracts; - readonly readers: EngineReaders; - readonly wallet: EngineWallet; +export declare class OfferExpiredError extends Error { + readonly code = "OFFER_EXPIRED"; + constructor(id: string, expiresAt: Date); } -export declare function sdkSetOf(network: NetworkName, root: string): SdkSet; -export type EngineHost = Pick; -export type EngineLoader = (set: SdkSet, host: Host) => Promise; -export interface HostEngines { - load(set: SdkSet): Promise; - for(network: NetworkName): Promise; - any(): Promise; - prefer(network: NetworkName): void; +export declare function closeOpenOffers(root: string, network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[]; +export declare class OfferCoinsInUseError extends Error { + readonly code = "OFFER_COINS_IN_USE"; + readonly offerIds: string[]; + constructor(offerIds: string[]); } -export declare class OtherSdkSetError extends Error { - readonly code = "OTHER_SDK_SET"; - readonly loadedSet: SdkSet; - readonly wantedSet: SdkSet; - constructor(loadedSet: SdkSet, wantedSet: SdkSet, message?: string); +export interface OpenOffer { + id: string; + terms: SwapTerms; + nullifiers: string[]; + madeAt: Date; + expiresAt: Date; } -export declare function claimSdkSet(set: SdkSet): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/error-codes` - -```ts -export interface CodeDefinition { - readonly code: string; - readonly exitCode: number; - readonly summary: string; - readonly recovery?: string; - readonly order?: number; +export declare function readOpenOffers(root: string, network: NetworkName, walletAddress: string): OpenOffer[]; +export declare function recordOpenOffer(root: string, network: NetworkName, walletAddress: string, offer: OpenOffer): void; +export interface ConnectOptions { + shielded?: boolean; } -export interface CodeRegistry { - code(code: string): CodeDefinition | undefined; +export declare class NoPayerError extends Error { + readonly code = "NO_PAYER"; + constructor(command: string); } -export declare class CodeDefinitionError extends Error { - constructor(message: string); +export interface Payer { + assertCanPay: (target: PayingTarget, wallet: string | undefined, progress: Spinner, signal: AbortSignal | undefined) => Promise; + serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; + connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options?: ConnectOptions) => Promise; } -export declare function defineCodes(codes: T): T; -export interface CodeSet { - readonly name: string; - readonly codes: readonly string[]; +export declare function payerFor(command: string, context: CommandContext | undefined): Payer; +export interface PayingTarget { + network: NetworkName; + root: string; + host: Host; + networkConfig: NetworkConfig; + endpoints: EndpointOverrides; } -export declare function defineCodeSet(name: string, codes: readonly string[]): CodeSet; -``` - -## `@kuiralabs/midnight-cli-core/lib/error-trim` - -```ts -export declare function trimAgentMessage(raw: string): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/errors` - -```ts -export declare class UsageError extends Error { - readonly code: string; - constructor(message: string); +export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string, host: Host): PayingTarget; +export interface ServedWallet { + port: number; + stop: () => Promise; } -export declare function isUsageError(err: unknown): err is UsageError; -export declare const CANCELLED_MESSAGE = "Operation cancelled"; -export declare class CancelledError extends Error { - readonly code = "CANCELLED"; - constructor(message?: string); +export interface PhaseTiming { + phase: string; + durationMs: number; } -export declare class TransactionRefusedError extends Error { - readonly reason: string; - readonly code: RefusalCode; - constructor(reason: string, options?: { - cause?: unknown; - code?: RefusalCode; - }); +export type ProgressEvent = { + readonly kind: 'start'; + readonly message: string; +} | { + readonly kind: 'update'; + readonly message: string; +} | { + readonly kind: 'done'; + readonly message: string; +}; +export type ProgressListener = (event: Event) => void; +export interface ProgressSteps { + start(message: string): void; + update(message: string): void; + done(message: string): void; } -export type RefusalCode = "TX_REJECTED" | "STALE_UTXO" | "INVALID_DUST_PROOF"; -export declare function asReported(err: Error): Error; -export declare class EngineError extends Error { - readonly code: string; - constructor(code: string, message: string, options?: { - cause?: unknown; - }); +export declare function progressSteps(listener: ProgressListener | undefined): ProgressSteps; +export interface Prompter { + isInteractive(): boolean; + ask(question: string): Promise; + askSecret(question: string): Promise; } -export declare class ProofTimeoutError extends EngineError { - constructor(message?: string, options?: { - cause?: unknown; - }); +export declare function clearDustDirectCache(network: string | undefined, pubkeyHex: string | undefined, root: string): void; +export declare function clearNativeDustCheckpoint(network: string | undefined, pubkeyHex: string | undefined, root: string): void; +export declare function clearShieldedDirectCache(network: string | undefined, pubkeyHex: string | undefined, root: string): void; +export type NetworkSettings = BlockfrostSettings & Pick; +export declare function resolveBlockfrostProjectId(name: NetworkName, configDir: string, settings: BlockfrostSettings): string | undefined; +export declare function resolveNetwork(ctx: NetworkResolutionContext, settings: NetworkSettings): { + name: NetworkName; + config: NetworkConfig; +}; +export declare function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName; +export interface CallSdkWarnings { + listen(listener: SdkWarningListener | undefined): () => void; } -export declare class ProofFailureError extends EngineError { - constructor(message: string, options?: { - cause?: unknown; - }); +export declare function createSdkWarningRouter(): SdkWarningRouter; +export declare function sdkTransientWarning(value: unknown): { + tag: string; + message: string; +} | null; +export interface SdkWarningCalls { + run(run: (warnings: CallSdkWarnings) => Promise): Promise; } -export declare class StaleUtxoError extends EngineError { - constructor(message: string, options?: { - cause?: unknown; - }); +export declare function withCallSdkWarnings(calls: SdkWarningCalls, given: CallSdkWarnings | undefined, work: (warnings: CallSdkWarnings) => Promise): Promise; +export declare const PASSPHRASE_ENV = "MN_PASSPHRASE"; +export interface Settings { + passphrase: string | undefined; + seed: string | undefined; + isLocalDetectOff: boolean; + dustSyncBin: string | undefined; + isNativeDustOff: boolean; + isDustCollapseOff: boolean; + blockfrostProjectId: string | undefined; + sharedBlockfrostProjectId: string | undefined; } -export declare class InvalidDustProofError extends EngineError { - constructor(message: string, options?: { - cause?: unknown; - }); +export declare function settingsFromEnvironment(env: Record): Settings; +export declare function shieldedDisabledReason(network: NetworkName): string; +export declare function shieldedSyncEnabled(network: NetworkName, force?: boolean): boolean; +export declare function sleep(ms: number, signal?: AbortSignal): Promise; +export declare function untilCancelled(work: Promise, signal?: AbortSignal): Promise; +export declare class NoStateRootError extends Error { + readonly code = "NO_STATE_ROOT"; + constructor(); } -export declare class StaleWalletStateError extends EngineError { - constructor(message: string, options?: { - cause?: unknown; - }); +export declare function checkTerms(offered: SwapTerms, agreed: SwapTerms): void; +export interface OfferContents { + id: string; + terms: SwapTerms; + nullifiers: string[]; } -export declare class DustRequiredError extends Error { - readonly code = "DUST_REQUIRED"; - constructor(message: string, options?: { - cause?: unknown; - }); +export interface SwapLeg { + token: string; + amount: bigint; } -export declare class InsufficientBalanceError extends Error { - readonly code = "INSUFFICIENT_BALANCE"; - constructor(message: string, options?: { - cause?: unknown; - }); +export interface SwapTerms { + give: SwapLeg; + want: SwapLeg; } -export declare class SyncTimeoutError extends Error { - readonly code = "SYNC_TIMEOUT"; - constructor(message: string, options?: { - cause?: unknown; - }); +export declare class TermsMismatchError extends Error { + readonly code = "TERMS_MISMATCH"; + readonly agreed: SwapTerms; + readonly offered: SwapTerms; + constructor(agreed: SwapTerms, offered: SwapTerms); } -export declare class NetworkError extends Error { - readonly code = "NETWORK_ERROR"; - constructor(message: string, options?: { - cause?: unknown; - }); +export declare function isTransportFailure(failure: unknown): boolean; +export declare function withTransportCode(err: unknown): unknown; +export type VerboseLog = (phase: string, message: string) => void; +export declare function clearWalletCache(address: string | undefined, network: string | undefined, root: string): void; +export declare function sessionOver(network: NetworkName, opened: OpenedConnector, readTransaction: (tx: string, stage: 'unsealed' | 'sealed') => TransactionDetail[], reopening?: SessionReopening): WalletSession; +export interface WalletSession { + readonly network: NetworkName; + addresses(): Promise; + balances(): Promise; + balanceTransaction(tx: string): Promise; + swap(give: TokenAmount[], take: TokenPayment[]): Promise; + makeOffer(give: SwapLeg, want: SwapLeg): Promise; + takeOffer(tx: string): Promise; + cancelOffers(offers: readonly OpenOffer[]): Promise; + sign(data: string, encoding: 'hex' | 'base64' | 'text'): Promise; + submit(tx: string): Promise; + readTransaction(tx: string, stage: 'unsealed' | 'sealed'): Promise; + close(): Promise; } -export declare class CommandFailedError extends Error { - readonly code = "COMMAND_FAILED"; - readonly exitCode: number; - readonly result: Readonly>; - constructor(command: string, exitCode: number, result: Readonly>); +``` + +## `@kuiralabs/midnight-cli-core/commands` + +```ts +export declare const configDefinition: CommandDefinition; +export declare const coreCodes: readonly [ + { + readonly code: "INVALID_ARGS"; + readonly exitCode: 2; + readonly order: 10; + readonly summary: "Missing/invalid argument."; + readonly recovery: "Show the message to the user verbatim — it names the missing field."; + }, + { + readonly code: "WRONG_PASSPHRASE"; + readonly exitCode: 2; + readonly order: 220; + readonly summary: "`MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed."; + readonly recovery: "Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed."; + }, + { + readonly code: "PASSPHRASE_REQUIRED"; + readonly exitCode: 2; + readonly order: 230; + readonly summary: "A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none)."; + readonly recovery: "Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat."; + }, + { + readonly code: "NETWORK_ERROR"; + readonly exitCode: 4; + readonly order: 30; + readonly summary: "Indexer/node/proof-server connection refused or DNS failure."; + readonly recovery: "Check `midnight_localnet_status()` or the endpoints the user configured; on this build `midnight_localnet_up()` is refused, so ask the user to start their ledger-9 stack."; + }, + { + readonly code: "AMBIGUOUS_LOCAL_STACKS"; + readonly exitCode: 4; + readonly order: 180; + readonly summary: "Several local Midnight stacks are running and no endpoints are configured, so mn won't guess."; + readonly recovery: "Ask the user which stack to use; they set its endpoints with `midnight config set`. Don't retry blindly."; + }, + { + readonly code: "BLOCKFROST_PROJECT_ID_REQUIRED"; + readonly exitCode: 4; + readonly order: 240; + readonly summary: "The network (preprod) is served by Blockfrost and no project id is set."; + readonly recovery: "Ask the user to create a Midnight preprod project at https://blockfrost.io and run `midnight config set blockfrost-project-id ` themselves. Never ask them to paste the id into the chat. Don't retry until they have."; + }, + { + readonly code: "BLOCKFROST_PROJECT_ID_REJECTED"; + readonly exitCode: 4; + readonly order: 250; + readonly summary: "Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network."; + readonly recovery: "Ask the user to check it at blockfrost.io and set it again. Don't retry blindly."; + }, + { + readonly code: "BLOCKFROST_LIMIT_REACHED"; + readonly exitCode: 4; + readonly order: 260; + readonly summary: "Blockfrost's plan limit or rate limit."; + readonly recovery: "Wait and retry once; if it persists, tell the user it is their Blockfrost plan."; + }, + { + readonly code: "ENDPOINT_SHUT_DOWN"; + readonly exitCode: 4; + readonly order: 270; + readonly summary: "An endpoint set by flag or config was shut down by its operator (the old preprod indexer)."; + readonly recovery: "`midnight_config_unset({ key: \"indexer-ws\" })` (and `node` if set), then retry."; + }, + { + readonly code: "CANCELLED"; + readonly exitCode: 7; + readonly order: 370; + readonly summary: "Operation was aborted (SIGINT, or the MCP call was cancelled)."; + readonly recovery: "A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user."; + }, + { + readonly code: "OTHER_SDK_SET"; + readonly exitCode: 1; + readonly order: 280; + readonly summary: "The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet)."; + readonly recovery: "Make the call in a process of its own: ask the user to start an MCP server for that network."; + }, + { + readonly code: "MIXED_SDK_LAYOUT"; + readonly exitCode: 1; + readonly order: 290; + readonly summary: "mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger."; + readonly recovery: "Ask the user to install mn with npm."; + }, + { + readonly code: "UNSUPPORTED_NODE"; + readonly exitCode: 1; + readonly order: 190; + readonly summary: "Node.js is older than 22 (22.18 for mn grant)."; + readonly recovery: "Ask the user to install a current Node.js."; + }, + { + readonly code: "NO_STATE_ROOT"; + readonly exitCode: 1; + readonly order: 300; + readonly summary: "The host gave mn no place to keep its state (a program's `createHost` without paths)."; + readonly recovery: "Give the host its paths (`createHost({ paths })`)."; + }, + { + readonly code: "NO_PAYER"; + readonly exitCode: 1; + readonly order: 310; + readonly summary: "A command that submits a transaction was called without a payer."; + readonly recovery: "Give the call a payer."; + }, + { + readonly code: "COMMAND_FAILED"; + readonly exitCode: 1; + readonly order: 320; + readonly summary: "A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result."; + readonly recovery: "Read the command's result in the message."; + }, + { + readonly code: "UNKNOWN"; + readonly exitCode: 1; + readonly order: 380; + readonly summary: "Error didn't match any known classifier."; + readonly recovery: "Surface the message to the user. If reproducible, a new code may be warranted."; + }, + { + readonly code: "PROOF_TIMEOUT"; + readonly exitCode: 6; + readonly order: 90; + readonly summary: "ZK proof generation didn't finish within the deadline."; + readonly recovery: "Retry — proofs can be slow under load."; + }, + { + readonly code: "PROOF_FAILURE"; + readonly exitCode: 6; + readonly order: 100; + readonly summary: "Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server."; + readonly recovery: "Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: \"\" })` then retry."; + }, + { + readonly code: "INVALID_DUST_PROOF"; + readonly exitCode: 6; + readonly order: 110; + readonly summary: "Chain rejected the dust spend proof as malformed (substrate \"Custom error 170\"). Stale commitment tree."; + readonly recovery: "`midnight_cache_clear({ wallet: \"\" })` then retry."; + }, + { + readonly code: "TX_REJECTED"; + readonly exitCode: 6; + readonly order: 60; + readonly summary: "Chain rejected the submitted transaction (catch-all when no more specific code applies)."; + readonly recovery: "Read the message; usually a state mismatch resolved by re-sync + retry."; + }, + { + readonly code: "STALE_UTXO"; + readonly exitCode: 6; + readonly order: 70; + readonly summary: "UTXO was already spent on-chain (substrate \"error code 115\")."; + readonly recovery: "Re-sync (the next call will refresh state) and retry."; + }, + { + readonly code: "STALE_CACHE"; + readonly exitCode: 6; + readonly order: 80; + readonly summary: "Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed)."; + readonly recovery: "`midnight_cache_clear({ wallet: \"\" })` then retry."; + }, + { + readonly code: "SYNC_TIMEOUT"; + readonly exitCode: 4; + readonly order: 40; + readonly summary: "Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync."; + readonly recovery: "Retry; the cache resumes from the last applied event so progress is preserved."; + }, + { + readonly code: "DUST_REQUIRED"; + readonly exitCode: 5; + readonly order: 120; + readonly summary: "Wallet has NIGHT but not enough DUST for the fee."; + readonly recovery: "Not registered (`midnight_dust_status()` shows `registered: false`): run `midnight_dust_register()`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes (\"generates the rest in about 4 minutes\"). Wait that long and retry, don't retry at once."; + }, + { + readonly code: "DUST_GENERATING"; + readonly exitCode: 5; + readonly order: 130; + readonly summary: "A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust."; + readonly recovery: "The message says when: run `midnight_dust_register()` again then, or add NIGHT."; + }, + { + readonly code: "INSUFFICIENT_BALANCE"; + readonly exitCode: 5; + readonly order: 50; + readonly summary: "Wallet doesn't have enough NIGHT to cover the requested amount."; + readonly recovery: "Show the user. On localnet: `midnight_airdrop({ amount: \"...\" })`. On hosted networks: tell user to fund the address."; + }, + { + readonly code: "NOT_AN_OFFER"; + readonly exitCode: 2; + readonly order: 330; + readonly summary: "The bytes given as a swap offer are not one."; + readonly recovery: "Ask the maker for the offer again."; + }, + { + readonly code: "TERMS_MISMATCH"; + readonly exitCode: 2; + readonly order: 340; + readonly summary: "A swap offer's own terms differ from the agreed ones."; + readonly recovery: "Don't take it; agree the terms again with the maker."; + }, + { + readonly code: "OFFER_EXPIRED"; + readonly exitCode: 2; + readonly order: 350; + readonly summary: "A swap offer is past the expiry its maker set."; + readonly recovery: "Ask the maker for a new one."; + }, + { + readonly code: "OFFER_COINS_IN_USE"; + readonly exitCode: 2; + readonly order: 360; + readonly summary: "A spend would use coins an open swap offer of this wallet's holds, cancelling it."; + readonly recovery: "Cancel the offer first (`mn swap cancel`), or wait until it is taken."; + } +]; +export declare const ENGINE_SYNC: import("../index.ts").CodeSet; +export declare const EVERY_COMMAND: readonly [ + "INVALID_ARGS", + "CANCELLED", + "UNKNOWN", + "UNSUPPORTED_NODE", + "NO_STATE_ROOT" +]; +export declare const LOADS_ENGINE: import("../index.ts").CodeSet; +export declare const PAYS: import("../index.ts").CodeSet; +export declare const READS_OFFERS: import("../index.ts").CodeSet; +export declare const RESOLVES_NETWORK: import("../index.ts").CodeSet; +export declare const coreGuidance: PackageGuidance; +``` + +## `@kuiralabs/midnight-cli-core/engine` + +```ts +export interface ApprovalOptions { + autoApproveReads?: boolean; + approveAll?: boolean; + approveFees?: boolean; + prompter: Prompter | null; + notice: NoticeSink; +} +export declare function promptApproval(request: ApprovalRequest, options: ApprovalOptions): Promise; +export declare function bindCachesToIndexer(network: string, indexerUrl: string, root: string): IndexerChange | undefined; +export declare function describeIndexerChange(network: string, change: IndexerChange): string; +export declare const ABANDONED_TX_TIMEOUT_MS = 120000; +export declare const DUST_COST_OVERHEAD = 300000000000000n; +export declare const DUST_FEE_BLOCKS_MARGIN = 5; +export declare const DUST_REGISTRATION_RETRY_DELAY_MS = 15000; +export declare const DUST_REGISTRATION_TIMEOUT_MS = 600000; +export declare const DUST_RETRY_ATTEMPTS = 10; +export declare const DUST_RETRY_DELAY_MS = 3000; +export declare const DUST_TIMEOUT_MS = 120000; +export declare const INITIAL_DUST_GRACE_PERIOD_SECONDS = 10800n; +export declare const INITIAL_GENERATION_DECAY_RATE = 8267n; +export declare const INITIAL_NIGHT_DUST_RATIO = 5000000000n; +export declare const MAX_RETRY_ATTEMPTS = 3; +export declare const MIN_DUST_FOR_TRANSFER = 900000000000000n; +export declare const PRE_SEND_SYNC_TIMEOUT_MS = 10000; +export declare const PROOF_TIMEOUT_MS = 300000; +export declare const STALE_UTXO_ERROR_CODE = 115; +export declare const SYNC_ATTEMPT_TIMEOUT_MS = 30000; +export declare const SYNC_TIMEOUT_MS = 300000; +export declare const TOKEN_MULTIPLIER = 1000000; +export declare const TX_TTL_MINUTES = 10; +export declare function chooseDustCoins(coins: readonly DustInput[], owed: bigint, combine: (owed: bigint) => DustInput[] | undefined): DustInput[] | undefined; +export interface DustInput { + token: TToken; + value: bigint; } -export declare function throwIfCancelled(signal: AbortSignal | undefined): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/exec-program` - -```ts -export interface ExecRun { - readonly signal: AbortSignal; - readonly timeoutMs?: number; - readonly onStderr?: (text: string) => void; +export declare function planDustInputs({ owed, coinCount, choose, feeWith }: DustPlanOptions): DustPlan; +export declare function spreadFeeAcrossInputs(inputs: readonly DustInput[], fee: bigint): DustInput[]; +export declare class DustFeeNotGeneratedError extends Error { + readonly code = "DUST_GENERATING"; + constructor(plan: RegistrationPlan, now: Date); } -export type ExecRunner = (file: string, args: readonly string[], run: ExecRun) => Promise; -export declare class ProgramFailedError extends Error { - readonly command: string; - readonly exitCode: number | null; - readonly stderr: string; - readonly stdout: string; - constructor(command: string, exitCode: number | null, stderr: string, stdout: string); +export declare function planRegistration(fee: bigint, estimates: readonly DustGenerationEstimate[]): RegistrationPlan; +export declare function awaitDustForFee(dust: DustBalanceSource, needed: bigint, onStatus?: (status: string) => void, signal?: AbortSignal): Promise; +export declare const DUST_SHORT_WAIT_MS: number; +export interface DustWaitPlan { + have: bigint; + needed: bigint; + waitMs: number | null; } -export declare class ProgramTimedOutError extends Error { - readonly command: string; - readonly code = "NETWORK_ERROR"; - constructor(command: string, timeoutMs: number); +export declare function payWhenDustCovers(pay: () => Promise, dust: DustBalanceSource, options: { + maxWaitMs: number; + onStatus?: (status: string) => void; + signal?: AbortSignal; +}): Promise; +export declare function planDustWait(err: unknown, dust: DustBalanceSource, now: Date): DustWaitPlan | undefined; +export declare function sleep(ms: number, signal?: AbortSignal): Promise; +export type AirdropParams = Omit; +export interface BlockLimits { + readTime: number; + computeTime: number; + blockUsage: number; + bytesWritten: number; + bytesChurned: number; } -export declare const execProgram: ExecRunner; -``` - -## `@kuiralabs/midnight-cli-core/lib/exit-codes` - -```ts -import type { CodeRegistry } from "./error-codes.ts"; -export declare const EXIT_SUCCESS = 0; -export declare const EXIT_GENERAL_ERROR = 1; -export declare const EXIT_INVALID_ARGS = 2; -export declare const EXIT_WALLET_NOT_FOUND = 3; -export declare const EXIT_NETWORK_ERROR = 4; -export declare const EXIT_INSUFFICIENT_BALANCE = 5; -export declare const EXIT_TX_REJECTED = 6; -export declare const EXIT_CANCELLED = 7; -export declare const ERROR_CODES: { - readonly INVALID_ARGS: "INVALID_ARGS"; - readonly WALLET_NOT_FOUND: "WALLET_NOT_FOUND"; - readonly NETWORK_ERROR: "NETWORK_ERROR"; - readonly INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE"; - readonly TX_REJECTED: "TX_REJECTED"; - readonly STALE_UTXO: "STALE_UTXO"; - readonly STALE_CACHE: "STALE_CACHE"; - readonly PROOF_TIMEOUT: "PROOF_TIMEOUT"; - readonly PROOF_FAILURE: "PROOF_FAILURE"; - readonly INVALID_DUST_PROOF: "INVALID_DUST_PROOF"; - readonly DUST_REQUIRED: "DUST_REQUIRED"; - readonly DUST_GENERATING: "DUST_GENERATING"; - readonly CHAIN_CLOCK_BEHIND: "CHAIN_CLOCK_BEHIND"; - readonly SYNC_TIMEOUT: "SYNC_TIMEOUT"; - readonly CANCELLED: "CANCELLED"; - readonly UNSUPPORTED_LEDGER: "UNSUPPORTED_LEDGER"; - readonly LOCALNET_UNAVAILABLE: "LOCALNET_UNAVAILABLE"; - readonly LOCAL_STACK_UNREACHABLE: "LOCAL_STACK_UNREACHABLE"; - readonly AMBIGUOUS_LOCAL_STACKS: "AMBIGUOUS_LOCAL_STACKS"; - readonly UNSUPPORTED_NODE: "UNSUPPORTED_NODE"; - readonly NO_ACCOUNT: "NO_ACCOUNT"; - readonly BLOCKFROST_PROJECT_ID_REQUIRED: "BLOCKFROST_PROJECT_ID_REQUIRED"; - readonly BLOCKFROST_PROJECT_ID_REJECTED: "BLOCKFROST_PROJECT_ID_REJECTED"; - readonly BLOCKFROST_LIMIT_REACHED: "BLOCKFROST_LIMIT_REACHED"; - readonly ENDPOINT_SHUT_DOWN: "ENDPOINT_SHUT_DOWN"; - readonly OTHER_SDK_SET: "OTHER_SDK_SET"; - readonly MIXED_SDK_LAYOUT: "MIXED_SDK_LAYOUT"; - readonly NOT_AN_OFFER: "NOT_AN_OFFER"; - readonly TERMS_MISMATCH: "TERMS_MISMATCH"; - readonly OFFER_EXPIRED: "OFFER_EXPIRED"; - readonly OFFER_COINS_IN_USE: "OFFER_COINS_IN_USE"; - readonly WRONG_PASSPHRASE: "WRONG_PASSPHRASE"; - readonly PASSPHRASE_REQUIRED: "PASSPHRASE_REQUIRED"; - readonly NO_STATE_ROOT: "NO_STATE_ROOT"; - readonly NO_PAYER: "NO_PAYER"; - readonly NO_NODE_RUNTIME: "NO_NODE_RUNTIME"; - readonly COMMAND_FAILED: "COMMAND_FAILED"; - readonly UNKNOWN: "UNKNOWN"; -}; -export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES]; -interface ClassifiedError { - exitCode: number; - errorCode: string; +export interface CachedReadOptions extends ReadOptions { + root: string; + notice: NoticeSink; } -export declare function classifyError(err: Error, codes: CodeRegistry): ClassifiedError; -export declare function classifyByCode(err: Error, codes: CodeRegistry): ClassifiedError; -export declare function humanizeNetworkError(message: string): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/fee-limits` - -```ts -export declare const SPECKS_PER_DUST: bigint; -export interface FeeLimits { - maxFeeSpecks: bigint; - maxPending: number; +export interface CallScript extends ScriptContract { + servePort: number; + contractAddress: string; + circuit: string; + args?: unknown[]; + privateStateKey?: string; } -export declare const DEFAULT_FEE_LIMITS: FeeLimits; -export declare function parseDustAmount(input: string, flag: string): bigint; -export declare function parseFeeLimits(maxFee: string | undefined, maxPending: string | undefined): FeeLimits; -export declare function feeLimitRefusal(feeSpecks: bigint, limits: FeeLimits): string | undefined; -export declare function pendingLimitRefusal(pendingCount: number, limits: FeeLimits): string | undefined; -``` - -## `@kuiralabs/midnight-cli-core/lib/host` - -```ts -import type { HostPaths } from "./state-root.ts"; -import { type Settings } from "./settings.ts"; -import type { Prompter } from "./prompter.ts"; -import { type SdkWarningCalls } from "./sdk-warnings.ts"; -import { type EngineLoader, type HostEngines } from "./engine.ts"; -export interface HostSlot { - readonly name: string; - readonly init: () => T; +export interface DAppConnector { + handlers: Record; + revertPendingTxs(connectionId: string): Promise; + handOffPendingTx(connectionId: string, txHex: string): boolean; + takeOffer(connectionId: string, txHex: string): Promise; + cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; + hasPendingTxs(): boolean; + dispose(): void; } -export declare function defineHostSlot(name: string, init: () => T): HostSlot; -export interface Host { - settings(): Settings; - paths(): HostPaths; - notice(line: string): void; - readonly prompter: Prompter | null; - readonly sdkWarnings: SdkWarningCalls; - readonly engines: HostEngines; - slot(key: HostSlot): T; +export interface DAppConnectorCallbacks { + onPhaseStart?: (connectionId: string, method: string, phase: string) => void; + onPhaseComplete?: (connectionId: string, method: string, phase: string, durationMs: number) => void; } -export type Supplied = T | (() => T); -export interface HostOptions { - readonly paths?: Supplied; - readonly settings?: Supplied; - readonly notice?: (line: string) => void; - readonly prompter?: Prompter | null; - readonly sdkWarnings?: SdkWarningCalls; - readonly engineLoader?: EngineLoader; +export interface DeployScript extends ScriptContract { + servePort: number; + privateStateKey?: string; + args?: unknown[]; } -export declare function createHost(options?: HostOptions): Host; -``` - -## `@kuiralabs/midnight-cli-core/lib/json-output` - -```ts -export declare function writeJsonResult(data: Readonly>): void; -export declare function writeJsonError(err: Error, errorCode: string, exitCode: number): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/keystore` - -```ts -export type SecretPurpose = "wallet" | "owner-key" | "keystore-check" | "account-key" | "owner-record" | "owner-roster" | "owner-device" | "private-state-password" | "account-backup" | "owner-devices" | "owner-device-read"; -export interface KeyedSecret { - v: 1; - iv: string; - tag: string; - ciphertext: string; +export interface DustBalance { + balance: bigint; + availableCoins: number; + ownedUtxoCount: number; + syncTime: Date; + fromCache: boolean; + eventsApplied: number; + lastAppliedEventId: number; + partial: boolean; + fetchedAt: number; } -export interface SealedSecret { - v: 1; - kdf: "scrypt"; - n: number; - r: number; - p: number; - salt: string; - iv: string; - tag: string; - ciphertext: string; +export interface DustExportResult { + network: string; + dustPublicKey: string; + offset: number; + balance: bigint; + eventCount: number; + fromCache: boolean; + partial: boolean; + snapshot: string; } -export declare class WrongPassphraseError extends Error { - readonly code = "WRONG_PASSPHRASE"; - constructor(message?: string); +export interface DustRegisterOptions { + signal?: AbortSignal; + onStatus?: (status: string) => void; + onSyncProgress?: (applied: number, highest: number) => void; + onSyncDetail?: (detail: string) => void; + onSyncWarning?: (tag: string, message: string) => void; + sdkWarnings: CallSdkWarnings; + log?: VerboseLog; + root: string; + notice: NoticeSink; } -export declare class MalformedSecretError extends Error { - constructor(reason: string); +export interface DustRegistration { + alreadyAvailable: boolean; + txHash?: string; + dustBalance: bigint; } -export declare function sealSecret(secret: Uint8Array, passphrase: string, purpose: SecretPurpose): SealedSecret; -export declare function isSealedSecret(value: unknown): value is SealedSecret; -export declare function openSecret(sealed: unknown, passphrase: string, purpose: SecretPurpose): Buffer; -export declare function freshDataKey(): Buffer; -export declare function sealWithKey(key: Uint8Array, secret: Uint8Array, purpose: SecretPurpose): KeyedSecret; -export declare function openWithKey(key: Uint8Array, sealed: unknown, purpose: SecretPurpose): Buffer; -``` - -## `@kuiralabs/midnight-cli-core/lib/network` - -```ts -import type { Settings } from "./settings.ts"; -import type { SdkSet } from "./engine.ts"; -export type NetworkName = "preprod" | "preview" | "stagenet" | "undeployed"; -export declare const LEDGER_9_FORK_VERSION = 2000000n; -export interface NetworkConfig { - indexer: string; - indexerWS: string; - node: string; - proofServer: string; - networkId: string; +export interface Engine { + readonly set: SdkSet; + readonly keys: EngineKeys; + readonly ledger: EngineLedger; + readonly contracts: EngineContracts; + readonly readers: EngineReaders; + readonly wallet: EngineWallet; } -export declare const SDK_SETS: readonly SdkSet[]; -export declare function defaultSdkSetOf(name: NetworkName): SdkSet; -export declare function networksOnSdkSet(set: SdkSet, root: string): NetworkName[]; -export declare function sdkSetOfNetwork(name: NetworkName, root: string): SdkSet; -export declare function isValidNetworkName(name: string): name is NetworkName; -export declare function getNetworkConfig(name: NetworkName): NetworkConfig; -export declare function getValidNetworkNames(): readonly string[]; -export declare function detectNetworkFromAddress(address: string): NetworkName | null; -interface TestcontainerPorts { - indexerPort?: number; - nodePort?: number; - proofServerPort?: number; -} -export interface LocalStackPorts { - node: number[]; - indexer: number[]; - proofServer: number[]; -} -export declare function parseLocalStacks(dockerPsOutput: string): LocalStackPorts; -export declare class AmbiguousLocalStacksError extends Error { - readonly code = "AMBIGUOUS_LOCAL_STACKS"; - constructor(found: LocalStackPorts); +export type EngineHost = Pick; +export interface EngineWallet { + unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; + dustBalance(seed: Buffer, networkConfig: NetworkConfig, options: CachedReadOptions): Promise; + transfer(params: TransferParams): Promise; + airdrop(params: AirdropParams): Promise; + shieldedTransfer(params: ShieldedTransferParams): Promise; + registerDust(seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; + exportDust(seed: Buffer, network: string, networkConfig: NetworkConfig, options: { + root: string; + notice: NoticeSink; + signal?: AbortSignal; + log?: VerboseLog; + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + }): Promise; + prepNightBalance(wallet: PrepWallet): Promise; + prepDust(wallet: PrepWallet, waitMs: number): Promise<{ + alreadyAvailable: boolean; + dustAvailable: boolean; + }>; + openConnector(options: { + seed: Buffer; + root: string; + notice: NoticeSink; + network: NetworkName; + networkConfig: NetworkConfig; + address: string; + syncMode: 'full' | 'lite'; + dustWaitMs?: number; + signal?: AbortSignal; + onMessage: (message: string) => void; + }): Promise; + serveWallet(options: { + seed: Buffer; + root: string; + notice: NoticeSink; + networkConfig: NetworkConfig; + network: NetworkName; + address: string; + syncMode: 'full' | 'lite'; + } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; } -export interface NeededComponents { - node: boolean; - indexer: boolean; - proofServer: boolean; +export interface EnsureDustResult { + alreadyAvailable: boolean; + txHash?: string; } -export declare function pickLocalStack(found: LocalStackPorts, need?: NeededComponents): TestcontainerPorts; -export declare function detectLocalStacks(settings: Pick): LocalStackPorts; -export interface ResolveNetworkConfigOptions { - given?: EndpointOverrides; - detect?: () => LocalStackPorts; - isLocalDetectOff?: boolean; - blockfrostProjectId?: string; +export interface OpenedConnector { + connector: DAppConnector; + stop(): Promise; } -export declare function resolveNetworkConfig(name: NetworkName, options?: ResolveNetworkConfigOptions): NetworkConfig; -export declare function indexerHttpFromWs(wsUrl: string): string; -export interface EndpointOverrides { - proofServer?: string; - node?: string; - indexerWS?: string; +export interface PrepWallet { + seed: Buffer; + root: string; + notice: NoticeSink; + network: NetworkName; + networkConfig: NetworkConfig; + address: string; + signal?: AbortSignal; + onMessage: (message: string) => void; } -export declare function endpointFlags(e: EndpointOverrides): Record; -export declare function applyEndpointOverrides(config: NetworkConfig, flagOverrides: EndpointOverrides, networkName: NetworkName, configDir: string): NetworkConfig; -``` - -## `@kuiralabs/midnight-cli-core/lib/network-id` - -```ts -import type { NetworkName } from "./network.ts"; -export type MidnightNetworkId = "preprod" | "preview" | "stagenet" | "undeployed"; -export declare function getNetworkId(networkIdStr: string): MidnightNetworkId; -export declare function networkIdForName(name: NetworkName): MidnightNetworkId; -``` - -## `@kuiralabs/midnight-cli-core/lib/network-target` - -```ts -import { type ParsedArgs } from "./argv.ts"; -import { type EndpointOverrides, type NetworkName } from "./network.ts"; -import type { Host } from "./host.ts"; -import type { PayingTarget } from "./payer.ts"; -export interface NetworkChoice extends EndpointOverrides { - network?: NetworkName; +export type RawStateValue = { + type: 'null'; +} | { + type: 'cell'; + value: string[]; +} | { + type: 'array'; + items: RawStateValue[]; +} | { + type: 'map'; + size: number; +} | { + type: 'boundedMerkleTree'; + height: number; + root: string[] | null; +}; +export interface ReadOptions { + forceFresh?: boolean; + signal?: AbortSignal; + onStatus?: (s: string) => void; + onProgress?: (current: number, highest: number) => void; + log?: VerboseLog; } -export declare function networkChoiceFromArgs(args: ParsedArgs): NetworkChoice; -export declare function networkTargetOf(host: Host, choice?: NetworkChoice): PayingTarget; -export declare function networkTargetUnder(root: string, host: Host, choice: NetworkChoice): PayingTarget; -``` - -## `@kuiralabs/midnight-cli-core/lib/notices` - -```ts -export type NoticeSink = (line: string) => void; -``` - -## `@kuiralabs/midnight-cli-core/lib/offer-envelope` - -```ts -import type { NetworkName } from "./network.ts"; -import { type OfferContents, type SwapTerms } from "./swap-offer.ts"; -export declare const OFFER_ENVELOPE_KIND = "midnight-swap-offer"; -export declare const OFFER_ENVELOPE_VERSION = 1; -export interface OfferEnvelope { - network: NetworkName; - id: string; - terms: SwapTerms; - expiresAt: Date; - tx: string; +export interface ScriptParts { + readonly prelude: string; + rpcClientCode(servePort: number): string; + readonly coerceArgFn: string; + readonly privateStateSecretFn: string; + readonly witnessCandidates: readonly string[]; + readonly indexerUrlEnv: string; + readonly indexerWsUrlEnv: string; } -export declare class OfferExpiredError extends Error { - readonly code = "OFFER_EXPIRED"; - constructor(id: string, expiresAt: Date); +export interface ServedWalletSession { + waitForDust(): Promise; + saveState(): Promise; + connect(options: { + approvalOptions: ApprovalOptions; + feeLimits?: FeeLimits; + callbacks?: DAppConnectorCallbacks; + }): DAppConnector; } -export declare function encodeOfferEnvelope(envelope: OfferEnvelope): string; -export declare function decodeOfferEnvelope(text: string): OfferEnvelope; -export declare function assertEnvelopeMatches(envelope: OfferEnvelope, read: OfferContents): void; -export declare function assertOfferUnexpired(envelope: OfferEnvelope, now: Date): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/open-offers` - -```ts -import type { NetworkName } from "./network.ts"; -import type { SwapTerms } from "./swap-offer.ts"; -export interface OpenOffer { - id: string; - terms: SwapTerms; - nullifiers: string[]; - madeAt: Date; - expiresAt: Date; +export interface ShieldedBalanceResult { + balance: bigint; + availableCoins: number; + tokens: ReadonlyMap; + eventCount: number; + lastAppliedEventId: number; + fromCache: boolean; + partial: boolean; } -export declare class OfferCoinsInUseError extends Error { - readonly code = "OFFER_COINS_IN_USE"; - readonly offerIds: string[]; - constructor(offerIds: string[]); +export interface ShieldedCachedOptions { + onProgress?: (eventsApplied: number, maxIdSeen: number) => void; + signal?: AbortSignal; + timeoutMs?: number; + forceFresh?: boolean; + chainId?: string; + root: string; } -export declare function openOffersFile(root: string, network: NetworkName, walletAddress: string): string; -export declare function readOpenOffers(root: string, network: NetworkName, walletAddress: string): OpenOffer[]; -export declare function recordOpenOffer(root: string, network: NetworkName, walletAddress: string, offer: OpenOffer): void; -export declare function closeOpenOffers(root: string, network: NetworkName, walletAddress: string, ids: readonly string[]): OpenOffer[]; -export declare function assertSpendsNoOfferCoin(open: readonly OpenOffer[], spent: readonly string[], cancelling?: readonly string[]): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/payer` - -```ts -import type { ParsedArgs } from "./argv.ts"; -import type { EndpointOverrides, NetworkConfig, NetworkName } from "./network.ts"; -import type { Spinner } from "../ui/spinner.ts"; -import type { CallSdkWarnings } from "./sdk-warnings.ts"; -import type { WalletSession } from "./wallet-session.ts"; -import type { Host } from "./host.ts"; -export interface PayingTarget { - network: NetworkName; +export interface ShieldedTransferParams extends WalletSyncHooks { + seed: Buffer; root: string; - host: Host; + notice: NoticeSink; + network: NetworkName; networkConfig: NetworkConfig; - endpoints: EndpointOverrides; -} -export declare function resolvePayingTarget(args: ParsedArgs, command: string, subcommand: string, root: string, host: Host): PayingTarget; -export interface ServedWallet { - port: number; - stop: () => Promise; -} -export interface PayingFunds { - nightBalance: bigint; - dustBalance: bigint; -} -export interface Payer { - assertCanPay: (target: PayingTarget, wallet: string | undefined, progress: Spinner, signal: AbortSignal | undefined) => Promise; - serve: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined) => Promise; - connect: (target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options?: ConnectOptions) => Promise; + recipient: string; + amount: bigint; + progress: Spinner; + insufficient: (availableNight: string) => string; + waitForDustToCover: boolean; + onSenderShieldedAddress?: (address: string) => void; } -export interface ConnectOptions { - shielded?: boolean; +export interface StateScript extends ScriptContract { + contractAddress: string; } -export interface CommandContext { - payer?: Payer; +export interface TransactionDetail { + label: string; + value: string; } -export declare class NoPayerError extends Error { - readonly code = "NO_PAYER"; - constructor(command: string); +export interface TransferParams { + seedBuffer: Buffer; + networkConfig: NetworkConfig; + recipientAddress: string; + amount: bigint; + signal?: AbortSignal; + onSync?: (applied: number, highest: number) => void; + onSyncDetail?: (walletsStillSyncing: string) => void; + onDust?: (status: string) => void; + onProving?: () => void; + onSubmitting?: () => void; + onSubmittingTick?: (elapsedMs: number) => void; + onSyncWarning?: (tag: string, message: string) => void; + sdkWarnings: CallSdkWarnings; + log?: VerboseLog; + root: string; + notice: NoticeSink; } -export declare function payerFor(command: string, context: CommandContext | undefined): Payer; -``` - -## `@kuiralabs/midnight-cli-core/lib/phase-tracker` - -```ts -export interface PhaseTiming { - phase: string; - durationMs: number; +export interface TransferResult { + txHash: string; + amountMicroNight: bigint; } -export interface PhaseTracker { - start(phase: string): void; - complete(): void; - getTimings(): PhaseTiming[]; +export interface UnshieldedView extends BalanceSummary { + fromCache: boolean; + fetchedAt: number; } -export interface PhaseCallbacks { - onStart?: (phase: string) => void; - onComplete?: (phase: string, durationMs: number) => void; +export declare class EngineError extends Error { + readonly code: string; + constructor(code: string, message: string, options?: { + cause?: unknown; + }); } -export declare function createPhaseTracker(callbacks?: PhaseCallbacks): PhaseTracker; -``` - -## `@kuiralabs/midnight-cli-core/lib/progress` - -```ts -export type ProgressEvent = { - readonly kind: "start"; - readonly message: string; -} | { - readonly kind: "update"; - readonly message: string; -} | { - readonly kind: "done"; - readonly message: string; -}; -export type ProgressListener = (event: Event) => void; -export interface ProgressSteps { - start(message: string): void; - update(message: string): void; - done(message: string): void; +export declare class ProofTimeoutError extends EngineError { + constructor(message?: string, options?: { + cause?: unknown; + }); } -export declare function progressSteps(listener: ProgressListener | undefined): ProgressSteps; -``` - -## `@kuiralabs/midnight-cli-core/lib/prompter` - -```ts -export interface Prompter { - isInteractive(): boolean; - ask(question: string): Promise; - askSecret(question: string): Promise; +export declare const DEFAULT_FEE_LIMITS: FeeLimits; +export declare function feeLimitRefusal(feeSpecks: bigint, limits: FeeLimits): string | undefined; +export interface FeeLimits { + maxFeeSpecks: bigint; + maxPending: number; } -export declare class PromptBusyError extends Error { - constructor(); +export declare function pendingLimitRefusal(pendingCount: number, limits: FeeLimits): string | undefined; +export declare function getNetworkId(networkIdStr: string): MidnightNetworkId; +export declare function networkIdForName(name: NetworkName): MidnightNetworkId; +export declare function assertSpendsNoOfferCoin(open: readonly OpenOffer[], spent: readonly string[], cancelling?: readonly string[]): void; +export declare function createPhaseTracker(callbacks?: PhaseCallbacks): PhaseTracker; +export interface PhaseTracker { + start(phase: string): void; + complete(): void; + getTimings(): PhaseTiming[]; } -``` - -## `@kuiralabs/midnight-cli-core/lib/reader-cache-files` - -```ts export declare function dustCacheDir(network: string, root: string): string; export declare function getDustCachePath(network: string, pubkeyHex: string, root: string): string; -export declare function clearDustDirectCache(network: string | undefined, pubkeyHex: string | undefined, root: string): void; export declare function getShieldedCachePath(network: string, pubkeyHex: string, root: string): string; -export declare function clearShieldedDirectCache(network: string | undefined, pubkeyHex: string | undefined, root: string): void; export declare const nativeCheckpointName: (pubkeyHex: string) => string; -export declare function clearNativeDustCheckpoint(network: string | undefined, pubkeyHex: string | undefined, root: string): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/resolve-network` - -```ts -import { type ParsedArgs } from "./argv.ts"; -import { type NetworkName, type NetworkConfig } from "./network.ts"; -import { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV, type Settings } from "./settings.ts"; -export type BlockfrostSettings = Pick; -export type NetworkSettings = BlockfrostSettings & Pick; -export interface NetworkResolutionContext { - args: ParsedArgs; - configDir: string; -} -export declare function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName; -export { BLOCKFROST_PROJECT_ID_ENV, SHARED_BLOCKFROST_PROJECT_ID_ENV }; -export declare function resolveBlockfrostProjectId(name: NetworkName, configDir: string, settings: BlockfrostSettings): string | undefined; -export declare function resolveNetwork(ctx: NetworkResolutionContext, settings: NetworkSettings): { - name: NetworkName; - config: NetworkConfig; -}; -``` - -## `@kuiralabs/midnight-cli-core/lib/sdk-errors` - -```ts -import { type RefusalCode } from "./errors.ts"; -export declare function isTransactionRejectedError(err: any): boolean; -export declare function isDustShortage(err: unknown): boolean; export interface DustShortfall { needed: bigint; available: bigint; } -export declare function withDustShortfall(error: E, shortfall: DustShortfall): E; export declare function dustShortfallOf(err: unknown): DustShortfall | undefined; +export declare function isColdStartRace(err: unknown): boolean; export declare function isDustRelatedError(err: any): boolean; +export declare function isDustShortage(err: unknown): boolean; export declare function isSdkInsufficientFundsError(err: any): boolean; -export declare function isColdStartRace(err: unknown): boolean; -export declare function nodeRefusalOf(err: unknown): string | undefined; -export declare function withNodeReason(err: Error): Error; +export declare function markingEngineCodes Promise>>(handlers: T): T; export declare function refusalCodeOf(reason: string): RefusalCode; -export declare function mnCodeOf(err: unknown): string | undefined; +export declare function reportingEngineErrors(operations: T): T; export declare function toEngineError(err: unknown): unknown; +export declare function withDustShortfall(error: E, shortfall: DustShortfall): E; export declare function withEngineCode(err: unknown): unknown; -export declare function reportingEngineErrors(operations: T): T; -export declare function markingEngineCodes Promise>>(handlers: T): T; -``` - -## `@kuiralabs/midnight-cli-core/lib/sdk-layout` - -```ts -export declare function resolvedPackageFolder(from: string, name: string): string | null; +export declare function assertOneSdkCopy(engine: string, engineDir: string, packages: readonly string[], wasmPackages: readonly string[]): void; export declare class MixedSdkLayoutError extends Error { readonly code = "MIXED_SDK_LAYOUT"; constructor(engine: string, wasmPackage: string, copies: string[]); } -export declare function assertOneSdkCopy(engine: string, engineDir: string, packages: readonly string[], wasmPackages: readonly string[]): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/sdk-warnings` - -```ts -export type SdkWarningListener = (tag: string, message: string) => void; -export interface CallSdkWarnings { - listen(listener: SdkWarningListener | undefined): () => void; -} -export interface SdkWarningCall { - readonly id: number; - readonly warnings: CallSdkWarnings; -} -export interface SdkWarningRouter { - openCall(): SdkWarningCall; - isListening(): boolean; - route(callId: number | undefined, tag: string, message: string): void; -} -export declare function createSdkWarningRouter(): SdkWarningRouter; -export interface SdkWarningCalls { - run(run: (warnings: CallSdkWarnings) => Promise): Promise; -} -export declare function sdkWarningCallsOn(router: SdkWarningRouter): SdkWarningCalls; -export declare function withCallSdkWarnings(calls: SdkWarningCalls, given: CallSdkWarnings | undefined, work: (warnings: CallSdkWarnings) => Promise): Promise; -export declare function sdkTransientWarning(value: unknown): { - tag: string; - message: string; -} | null; -``` - -## `@kuiralabs/midnight-cli-core/lib/settings` - -```ts -export declare const PASSPHRASE_ENV = "MN_PASSPHRASE"; -export declare const SEED_ENV = "MN_SEED"; -export declare const NO_LOCAL_DETECT_ENV = "MN_NO_LOCAL_DETECT"; -export declare const DUST_SYNC_BIN_ENV = "MN_DUST_SYNC_BIN"; -export declare const DISABLE_NATIVE_DUST_ENV = "MN_DISABLE_NATIVE_DUST"; -export declare const DUST_COLLAPSE_DISABLE_ENV = "MN_DISABLE_DUST_COLLAPSE"; -export declare const BLOCKFROST_PROJECT_ID_ENV = "MN_BLOCKFROST_PROJECT_ID"; -export declare const SHARED_BLOCKFROST_PROJECT_ID_ENV = "BLOCKFROST_PROJECT_ID"; -export interface Settings { - passphrase: string | undefined; - seed: string | undefined; - isLocalDetectOff: boolean; - dustSyncBin: string | undefined; - isNativeDustOff: boolean; - isDustCollapseOff: boolean; - blockfrostProjectId: string | undefined; - sharedBlockfrostProjectId: string | undefined; -} -export declare function settingsFromEnvironment(env: Record): Settings; -``` - -## `@kuiralabs/midnight-cli-core/lib/shielded-policy` - -```ts -import type { NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare function networkHasShielded(network: NetworkName): boolean; -export declare function shieldedSyncEnabled(network: NetworkName, force?: boolean): boolean; -export declare function shieldedDisabledReason(network: NetworkName): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/sign-data` - -```ts -export type SignDataEncoding = "hex" | "base64" | "text"; +export declare function resolvedPackageFolder(from: string, name: string): string | null; export declare function decodeSignPayload(data: string, encoding: string): Uint8Array; export declare function signedMessageBytes(payload: Uint8Array): Uint8Array; -``` - -## `@kuiralabs/midnight-cli-core/lib/sleep` - -```ts -export declare function sleep(ms: number, signal?: AbortSignal): Promise; -export declare function untilCancelled(work: Promise, signal?: AbortSignal): Promise; -``` - -## `@kuiralabs/midnight-cli-core/lib/state-root` - -```ts -export interface HostPaths { - stateRoot: string; - home: string; -} -export declare class NoStateRootError extends Error { - readonly code = "NO_STATE_ROOT"; - constructor(); -} -``` - -## `@kuiralabs/midnight-cli-core/lib/swap-offer` - -```ts -export interface SwapLeg { - token: string; - amount: bigint; -} -export interface SwapTerms { - give: SwapLeg; - want: SwapLeg; -} -export interface OfferContents { - id: string; - terms: SwapTerms; - nullifiers: string[]; -} +export declare function describeLeg(leg: SwapLeg): string; export declare class NotAnOfferError extends Error { readonly code = "NOT_AN_OFFER"; constructor(reason: string, options?: { cause?: unknown; }); } -export declare class TermsMismatchError extends Error { - readonly code = "TERMS_MISMATCH"; - readonly agreed: SwapTerms; - readonly offered: SwapTerms; - constructor(agreed: SwapTerms, offered: SwapTerms); -} -export declare function checkTerms(offered: SwapTerms, agreed: SwapTerms): void; -export declare function describeLeg(leg: SwapLeg): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/transport-failure` - -```ts -export declare function isTransportFailure(failure: unknown): boolean; -export declare function carriesOwnCode(failure: unknown): boolean; -export declare function withTransportCode(err: unknown): unknown; -``` - -## `@kuiralabs/midnight-cli-core/lib/tx-serde` - -```ts -export declare function toHex(bytes: Uint8Array): string; export declare function fromHex(hex: string): Uint8Array; -``` - -## `@kuiralabs/midnight-cli-core/lib/verbose` - -```ts -export type VerboseLog = (phase: string, message: string) => void; -export declare function verboseLine(phase: string, message: string): string; -``` - -## `@kuiralabs/midnight-cli-core/lib/wallet-cache` - -```ts -export interface WalletCacheData { - shielded: string; - unshielded: string; - dust: string; -} +export declare function toHex(bytes: Uint8Array): string; export declare function cacheRootDir(root: string): string; -export declare function networkCacheFolder(network: string, root: string): string; -export declare const CACHE_KEY_PREFIX_LENGTH = 20; -export declare function cacheKeyOf(addressOrKey: string): string; +export declare function clearWalletCache(address: string | undefined, network: string | undefined, root: string): void; export declare function getCachePath(address: string, network: string, root: string): string; export declare function loadWalletCache(address: string, network: string, root: string): WalletCacheData | null; +export declare function networkCacheFolder(network: string, root: string): string; export declare function saveWalletCache(address: string, network: string, facade: { shielded: { serializeState(): Promise; @@ -2002,128 +1405,39 @@ export declare function saveWalletCache(address: string, network: string, facade }; }, root: string, chainId?: string): Promise; export declare function validateWalletCacheChainId(network: string, currentChainId: string | null, root: string): string[]; -export declare function clearWalletCache(address: string | undefined, network: string | undefined, root: string): void; -``` - -## `@kuiralabs/midnight-cli-core/lib/wallet-session` - -```ts -import { type HostEngines, type OpenedConnector, type TransactionDetail } from "./engine.ts"; -import type { NetworkConfig, NetworkName } from "./network.ts"; -import type { NoticeSink } from "./notices.ts"; -import { type NetworkSettings } from "./resolve-network.ts"; -import type { SwapLeg } from "./swap-offer.ts"; -import type { OpenOffer } from "./open-offers.ts"; -export interface WalletAddresses { - unshielded: string; +export interface WalletCacheData { shielded: string; - shieldedCoinPublicKey: string; - shieldedEncryptionPublicKey: string; + unshielded: string; dust: string; } -export interface WalletBalances { - unshielded: Record; - shielded: Record; - dust: bigint; -} -export interface TokenAmount { - kind: "shielded" | "unshielded"; - type: string; - value: bigint; -} -export interface TokenPayment extends TokenAmount { - recipient: string; -} -export interface SignedData { - data: string; - signature: string; - verifyingKey: string; - scheme: string; -} -export interface WalletSession { - readonly network: NetworkName; - addresses(): Promise; - balances(): Promise; - balanceTransaction(tx: string): Promise; - swap(give: TokenAmount[], take: TokenPayment[]): Promise; - makeOffer(give: SwapLeg, want: SwapLeg): Promise; - takeOffer(tx: string): Promise; - cancelOffers(offers: readonly OpenOffer[]): Promise; - sign(data: string, encoding: "hex" | "base64" | "text"): Promise; - submit(tx: string): Promise; - readTransaction(tx: string, stage: "unsealed" | "sealed"): Promise; - close(): Promise; -} -export interface SessionReopening { - reopen: () => Promise; - onMessage?: (message: string) => void; - delayMs?: number; -} -export declare function sessionOver(network: NetworkName, opened: OpenedConnector, readTransaction: (tx: string, stage: "unsealed" | "sealed") => TransactionDetail[], reopening?: SessionReopening): WalletSession; -export interface OpenWalletSessionOptions { - seed: Buffer; - network: NetworkName; - root: string; - notice: NoticeSink; - engines: HostEngines; - networkConfig?: NetworkConfig; - settings?: NetworkSettings; - forceShielded?: boolean; - dustWaitMs?: number; - signal?: AbortSignal; - onMessage?: (message: string) => void; -} -export declare function openWalletSession(options: OpenWalletSessionOptions): Promise; ``` -## `@kuiralabs/midnight-cli-core/ui/colors` +## `@kuiralabs/midnight-cli-core/ui` ```ts -export declare const MIDNIGHT_BLUE = 17; -export declare const TEAL = 38; -export declare const PURPLE = 99; -export declare const WHITE_CODE = 15; -export declare const DIM_GRAY = 245; -export declare const RED_CODE = 196; -export declare const GREEN_CODE = 40; -export declare const YELLOW_CODE = 226; -export declare function isColorEnabled(): boolean; -export declare function fg(text: string, code: number): string; -export declare function bg(text: string, code: number): string; export declare function bold(text: string): string; export declare function dim(text: string): string; -export declare function teal(text: string): string; +export declare function gray(text: string): string; +export declare function green(text: string): string; +export declare function isColorEnabled(): boolean; export declare function purple(text: string): string; export declare function red(text: string): string; -export declare function green(text: string): string; -export declare function yellow(text: string): string; -export declare function midnightBlue(text: string): string; +export declare function teal(text: string): string; export declare function white(text: string): string; -export declare function gray(text: string): string; -``` - -## `@kuiralabs/midnight-cli-core/ui/format` - -```ts -export declare function header(title: string, width?: number): string; +export declare function yellow(text: string): string; export declare function divider(width?: number): string; -export declare function keyValue(key: string, value: string, padWidth?: number): string; -export declare function toNight(microNight: bigint): string; +export declare function errorMessage(error: string, suggestion?: string): string; +export declare function formatAddress(address: string, truncate?: boolean): string; +export declare function formatDust(specks: bigint): string; export declare function formatNight(microNight: bigint): string; -export declare function toDust(specks: bigint): string; +export declare function header(title: string, width?: number): string; +export declare function keyValue(key: string, value: string, padWidth?: number): string; export declare function roughDust(specks: bigint, up?: boolean): string; -export declare function formatDust(specks: bigint): string; -export declare function formatAddress(address: string, truncate?: boolean): string; -export declare function box(lines: string[], style?: "light" | "heavy", maxWidth?: number): string; -export declare function errorMessage(error: string, suggestion?: string): string; -export declare function usageMessage(message: string, suggestion?: string): string; export declare function successMessage(msg: string, txHash?: string): string; -``` - -## `@kuiralabs/midnight-cli-core/ui/spinner` - -```ts -import type { ProgressEvent } from "../lib/progress.ts"; +export declare function toDust(specks: bigint): string; +export declare function toNight(microNight: bigint): string; +export declare function usageMessage(message: string, suggestion?: string): string; +export declare function silentSpinner(report?: ProgressReport): Spinner; export interface Spinner { update(message: string): void; stop(finalMessage?: string): void; @@ -2131,36 +1445,11 @@ export interface Spinner { log(line: string): void; clear(): void; } -export type ProgressReport = (message: string) => void; -export declare function silentSpinner(report?: ProgressReport): Spinner; -export interface Progress { - start(message: string): Spinner; - silent(): Spinner; - active(): Spinner | null; -} -export declare function createProgress(report?: ProgressReport): Progress; export interface SpinnerReporter { report(event: ProgressEvent): void; fail(message?: string): void; } export declare function spinnerReporter(progress: Progress, silent: boolean): SpinnerReporter; -export declare function start(message: string, report?: ProgressReport, onEnd?: (spinner: Spinner) => void): Spinner; export declare function trackElapsed(spinner: Spinner, baseMessage: string, promise: Promise): Promise; -export declare function withSpinner(message: string, fn: () => Promise): Promise; -``` - -## `@kuiralabs/midnight-cli-core/ui/terminal-prompter` - -```ts -import type { Readable, Writable } from "node:stream"; -import { type Prompter } from "../lib/prompter.ts"; -export interface TerminalIo { - input?: Readable & { - setRawMode?: (mode: boolean) => unknown; - isTTY?: boolean; - }; - output?: Writable; - isTTY?: boolean; -} export declare function createTerminalPrompter(io?: TerminalIo): Prompter; ``` diff --git a/packages/cli-core/package.json b/packages/cli-core/package.json index fca327ea..c3b60e7a 100644 --- a/packages/cli-core/package.json +++ b/packages/cli-core/package.json @@ -17,10 +17,25 @@ "node": ">=22" }, "exports": { - "./*": { - "midnight-cli-source": "./src/*.ts", - "types": "./dist/*.d.ts", - "default": "./dist/*.js" + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./engine": { + "midnight-cli-source": "./src/engine.ts", + "types": "./dist/engine.d.ts", + "default": "./dist/engine.js" + }, + "./ui": { + "midnight-cli-source": "./src/ui.ts", + "types": "./dist/ui.d.ts", + "default": "./dist/ui.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" } }, "files": [ diff --git a/src/__tests__/transfer-lib.test.ts b/packages/cli-core/src/__tests__/amount.test.ts similarity index 58% rename from src/__tests__/transfer-lib.test.ts rename to packages/cli-core/src/__tests__/amount.test.ts index fadd92d1..0c263265 100644 --- a/src/__tests__/transfer-lib.test.ts +++ b/packages/cli-core/src/__tests__/amount.test.ts @@ -1,12 +1,11 @@ +// Amounts as mn reads and prints them, and the sync timeouts: core's. + import { describe, it, expect } from 'vitest'; -import { validateRecipientAddress, isDustRelatedError } from '@kuiralabs/midnight-engine-rc/transfer'; -import { nightAmountJson, nightAmountText, nightToMicro, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; -import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { GENESIS_SEED, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_ATTEMPT_REMOTE_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { nightAmountJson, nightAmountText, nightToMicro, parseAmount } from '../lib/amount.ts'; +import { SYNC_ATTEMPT_REMOTE_TIMEOUT_MS, SYNC_ATTEMPT_TIMEOUT_MS } from '../lib/constants.ts'; +import { UsageError } from '../lib/errors.ts'; +import { ERROR_CODES, EXIT_INVALID_ARGS, classifyError } from '../lib/exit-codes.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; describe('nightToMicro', () => { it('converts whole NIGHT to micro-NIGHT', () => { @@ -107,7 +106,7 @@ describe('parseAmount', () => { for (const amount of ['0', '-5', 'abc', 'Infinity']) { const refused = (() => { try { parseAmount(amount); } catch (err) { return err as Error; } throw new Error(`${amount} was accepted`); })(); expect(refused).toBeInstanceOf(UsageError); - expect(classifyError(refused, installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); + expect(classifyError(refused, CORE_CODES)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); } }); }); @@ -126,82 +125,6 @@ describe('nightAmountText and nightAmountJson: an amount as mn prints it', () => }); }); -describe('validateRecipientAddress', () => { - const genesisSeed = Buffer.from(GENESIS_SEED, 'hex'); - - it('accepts a valid undeployed address', () => { - const address = deriveUnshieldedAddress(genesisSeed, 'undeployed'); - const config = getNetworkConfig('undeployed'); - expect(() => validateRecipientAddress(address, config)).not.toThrow(); - }); - - it('accepts a valid preprod address', () => { - const address = deriveUnshieldedAddress(genesisSeed, 'preprod'); - const config = getNetworkConfig('preprod'); - expect(() => validateRecipientAddress(address, config)).not.toThrow(); - }); - - it('accepts a valid preview address', () => { - const address = deriveUnshieldedAddress(genesisSeed, 'preview'); - const config = getNetworkConfig('preview'); - expect(() => validateRecipientAddress(address, config)).not.toThrow(); - }); - - it('rejects an address for the wrong network', () => { - const preprodAddr = deriveUnshieldedAddress(genesisSeed, 'preprod'); - const undeployedConfig = getNetworkConfig('undeployed'); - expect(() => validateRecipientAddress(preprodAddr, undeployedConfig)).toThrow('Invalid recipient address'); - }); - - it('rejects a garbage string', () => { - const config = getNetworkConfig('undeployed'); - expect(() => validateRecipientAddress('not-an-address', config)).toThrow('Invalid recipient address'); - }); - - it('rejects an empty string', () => { - const config = getNetworkConfig('undeployed'); - expect(() => validateRecipientAddress('', config)).toThrow('Invalid recipient address'); - }); -}); - -describe('isDustRelatedError', () => { - it('matches "not enough dust" errors', () => { - expect(isDustRelatedError(new Error('Not enough dust to pay fees'))).toBe(true); - }); - - it('matches "dust generated" errors', () => { - expect(isDustRelatedError(new Error('dust generated capacity insufficient'))).toBe(true); - }); - - it('matches "insufficient funds" errors', () => { - expect(isDustRelatedError(new Error('Insufficient funds: dust wallet sync timed out'))).toBe(true); - }); - - it('matches "no dust tokens" errors', () => { - expect(isDustRelatedError(new Error('No dust tokens found in the wallet state'))).toBe(true); - }); - - it('matches transaction submission errors', () => { - expect(isDustRelatedError(new Error('Transaction submission error'))).toBe(true); - }); - - it('matches errors with _tag TransactionInvalidError', () => { - const err = new Error('fail'); - (err as any)._tag = 'TransactionInvalidError'; - expect(isDustRelatedError(err)).toBe(true); - }); - - it('does not match unrelated errors', () => { - expect(isDustRelatedError(new Error('Network timeout'))).toBe(false); - expect(isDustRelatedError(new Error('Invalid address format'))).toBe(false); - }); - - it('handles null/undefined errors', () => { - expect(isDustRelatedError(null)).toBe(false); - expect(isDustRelatedError(undefined)).toBe(false); - }); -}); - describe('sync timeout constants', () => { it('remote timeout is longer than local timeout', () => { expect(SYNC_ATTEMPT_REMOTE_TIMEOUT_MS).toBeGreaterThan(SYNC_ATTEMPT_TIMEOUT_MS); diff --git a/src/__tests__/approval.test.ts b/packages/cli-core/src/__tests__/approval.test.ts similarity index 97% rename from src/__tests__/approval.test.ts rename to packages/cli-core/src/__tests__/approval.test.ts index 297a1f84..d55f52c0 100644 --- a/src/__tests__/approval.test.ts +++ b/packages/cli-core/src/__tests__/approval.test.ts @@ -1,16 +1,9 @@ -import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { type Prompter } from '../lib/prompter.ts'; +import { describeApprovalPolicy, renderApprovalBox, isReadOnlyMethod, isPrepMethod, type ApprovalRequest } from '../lib/approval.ts'; +import { createTerminalPrompter } from '../ui/terminal-prompter.ts'; +import { promptApproval, type ApprovalOptions } from '../lib/approval.ts'; import { PassThrough } from 'node:stream'; import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { - describeApprovalPolicy, - renderApprovalBox, - isReadOnlyMethod, - isPrepMethod, - promptApproval, - type ApprovalOptions, - type ApprovalRequest, -} from '@kuiralabs/midnight-cli-core/lib/approval'; // Strip ANSI codes for content assertions const stripAnsi = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ''); diff --git a/src/__tests__/argv.test.ts b/packages/cli-core/src/__tests__/argv.test.ts similarity index 97% rename from src/__tests__/argv.test.ts rename to packages/cli-core/src/__tests__/argv.test.ts index 053115ff..c3c2c08d 100644 --- a/src/__tests__/argv.test.ts +++ b/packages/cli-core/src/__tests__/argv.test.ts @@ -1,6 +1,6 @@ -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '../lib/errors.ts'; +import { parseArgs, getFlag, hasFlag, isVerbose, requireFlag, type ParsedArgs } from '../lib/argv.ts'; import { describe, it, expect } from 'vitest'; -import { parseArgs, getFlag, hasFlag, isVerbose, requireFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; describe('parseArgs', () => { it('parses command from first positional', () => { diff --git a/src/__tests__/blockfrost.test.ts b/packages/cli-core/src/__tests__/blockfrost.test.ts similarity index 92% rename from src/__tests__/blockfrost.test.ts rename to packages/cli-core/src/__tests__/blockfrost.test.ts index 8d659d18..f4a6f1ca 100644 --- a/src/__tests__/blockfrost.test.ts +++ b/packages/cli-core/src/__tests__/blockfrost.test.ts @@ -4,14 +4,10 @@ // and how the project id is kept out of anything printed. import { describe, expect, it } from 'vitest'; -import { - BlockfrostLimitError, BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, - assertEndpointUsable, blockfrostEndpoints, checkProjectId, endpointRefusal, endpointRefusalFromWsError, isBlockfrostUrl, - maskProjectId, mayHoldProjectId, networkOfProjectId, redactProjectId, usesBlockfrost, -} from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { ERROR_CODES, EXIT_NETWORK_ERROR, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { BlockfrostLimitError, BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, assertEndpointUsable, blockfrostEndpoints, checkProjectId, endpointRefusal, endpointRefusalFromWsError, isBlockfrostUrl, maskProjectId, mayHoldProjectId, networkOfProjectId, redactProjectId, usesBlockfrost } from '../lib/blockfrost.ts'; +import { UsageError } from '../lib/errors.ts'; +import { ERROR_CODES, EXIT_NETWORK_ERROR, classifyError } from '../lib/exit-codes.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const WITH_ID = blockfrostEndpoints('preprod', ID); @@ -145,7 +141,7 @@ describe('the errors\' codes', () => { [new EndpointShutDownError('https://indexer.preprod.midnight.network/api/v4/graphql'), ERROR_CODES.ENDPOINT_SHUT_DOWN], ]; for (const [error, errorCode] of cases) { - expect(classifyError(error, installedCommands)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode }); + expect(classifyError(error, CORE_CODES)).toEqual({ exitCode: EXIT_NETWORK_ERROR, errorCode }); } }); }); diff --git a/src/__tests__/cache-indexer.test.ts b/packages/cli-core/src/__tests__/cache-indexer.test.ts similarity index 98% rename from src/__tests__/cache-indexer.test.ts rename to packages/cli-core/src/__tests__/cache-indexer.test.ts index 12eab208..918b07d7 100644 --- a/src/__tests__/cache-indexer.test.ts +++ b/packages/cli-core/src/__tests__/cache-indexer.test.ts @@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { bindCachesToIndexer, describeIndexerChange, indexerIdentity } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { bindCachesToIndexer, describeIndexerChange, indexerIdentity } from '../lib/cache-indexer.ts'; const BLOCKFROST = 'wss://midnight-preprod.blockfrost.io/api/v0/ws?project_id=nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const OLD_PREPROD = 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws'; diff --git a/src/__tests__/call-context.test.ts b/packages/cli-core/src/__tests__/call-context.test.ts similarity index 90% rename from src/__tests__/call-context.test.ts rename to packages/cli-core/src/__tests__/call-context.test.ts index 17e1883c..c1a7af0a 100644 --- a/src/__tests__/call-context.test.ts +++ b/packages/cli-core/src/__tests__/call-context.test.ts @@ -4,20 +4,13 @@ // already cancelled never starts. import { describe, expect, it } from 'vitest'; -import { - SecondResultError, - callDiagnostics, - callOutput, - createCallContext, - runHandler, - type CallContext, -} from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { testHost } from './helpers/test-host.ts'; -import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { SecondResultError, callDiagnostics, callOutput, createCallContext, runHandler, type CallContext } from '../lib/call-context.ts'; +import { CancelledError } from '../lib/errors.ts'; +import { parseArgs } from '../lib/argv.ts'; +import { createHost } from '../lib/host.ts'; +import { settingsFromEnvironment } from '../lib/settings.ts'; +import { type Payer } from '../lib/payer.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; const recordingSink = () => { const seen: string[] = []; diff --git a/src/__tests__/cli-config.test.ts b/packages/cli-core/src/__tests__/cli-config.test.ts similarity index 98% rename from src/__tests__/cli-config.test.ts rename to packages/cli-core/src/__tests__/cli-config.test.ts index bb3c9036..b431420e 100644 --- a/src/__tests__/cli-config.test.ts +++ b/packages/cli-core/src/__tests__/cli-config.test.ts @@ -2,19 +2,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import { - loadCliConfig, - saveCliConfig, - getConfigValue, - setConfigValue, - unsetConfigValue, - getValidConfigKeys, - getBlockfrostProjectId, - getSdkSetOverride, -} from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { sdkSetOfNetwork } from '@kuiralabs/midnight-cli-core/lib/network'; -import { getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { loadCliConfig, saveCliConfig, getConfigValue, setConfigValue, unsetConfigValue, getValidConfigKeys, getBlockfrostProjectId, getSdkSetOverride } from '../lib/cli-config.ts'; +import { sdkSetOfNetwork } from '../lib/network.ts'; +import { getCachePath, networkCacheFolder } from '../lib/wallet-cache.ts'; +import { getDustCachePath } from '../lib/reader-cache-files.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-cli-config-test-${process.pid}`); diff --git a/src/__tests__/colors.test.ts b/packages/cli-core/src/__tests__/colors.test.ts similarity index 95% rename from src/__tests__/colors.test.ts rename to packages/cli-core/src/__tests__/colors.test.ts index c2a1370f..7df6dc07 100644 --- a/src/__tests__/colors.test.ts +++ b/packages/cli-core/src/__tests__/colors.test.ts @@ -1,12 +1,5 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { - isColorEnabled, - fg, bg, bold, dim, - teal, purple, red, green, yellow, - midnightBlue, white, gray, - TEAL, PURPLE, RED_CODE, GREEN_CODE, YELLOW_CODE, - MIDNIGHT_BLUE, WHITE_CODE, DIM_GRAY, -} from '@kuiralabs/midnight-cli-core/ui/colors'; +import { isColorEnabled, fg, bg, bold, dim, teal, purple, red, green, yellow, midnightBlue, white, gray, TEAL, PURPLE, RED_CODE, GREEN_CODE, YELLOW_CODE, MIDNIGHT_BLUE, WHITE_CODE, DIM_GRAY } from '../ui/colors.ts'; const ESC = '\x1b['; const RESET = '\x1b[0m'; diff --git a/packages/cli-core/src/__tests__/command-definition.test.ts b/packages/cli-core/src/__tests__/command-definition.test.ts new file mode 100644 index 00000000..df5fc12b --- /dev/null +++ b/packages/cli-core/src/__tests__/command-definition.test.ts @@ -0,0 +1,92 @@ +// A command registry made from definitions: the Flags section help renders, +// and the definitions it refuses (a command or a flag defined twice, a tool +// that doesn't fit its command). + +import { describe, expect, it } from 'vitest'; +import { CommandDefinitionError, createCommandRegistry, flagsSectionLines, type CommandDefinition, type ToolDefinition } from '../lib/command-definition.ts'; + +describe('createCommandRegistry', () => { + const base: CommandDefinition = { + name: 'x', + order: 1, + flags: [{ name: 'a', takesValue: false, help: ['--a A'] }], + help: { description: 'X', usage: 'midnight x', flags: ['note', { flag: 'a' }] }, + needsWalletSdk: false, + shell: {}, + errors: { codes: [] }, + load: async () => ({ default: async () => {} }), + }; + + it('renders the Flags section from its lines and the flags\' own help', () => { + expect(flagsSectionLines(base)).toStrictEqual(['note', '--a A']); + }); + + it('refuses a command defined twice', () => { + expect(() => createCommandRegistry([base, base], [])).toThrow(CommandDefinitionError); + }); + + it('refuses help that shows a flag with no help lines, or a flag\'s help that help never shows', () => { + expect(() => createCommandRegistry([{ ...base, help: { ...base.help!, flags: [{ flag: 'b' }] } }], [])).toThrow(/--b/); + expect(() => createCommandRegistry([{ ...base, help: { ...base.help!, flags: [] } }], [])).toThrow(/--a has help lines/); + }); + + it('refuses a flag tied to a subcommand the command lacks', () => { + expect(() => createCommandRegistry([{ ...base, flags: [{ name: 'a', takesValue: false, subcommands: ['nope'] }], help: undefined }], [])).toThrow(/"nope"/); + }); + + const tool: ToolDefinition = { name: 't', description: 'T', params: [], argv: { flags: [] }, order: 1 }; + const withTools = (flags: CommandDefinition['flags'], ...tools: ToolDefinition[]): CommandDefinition => + ({ ...base, subcommands: ['s', 'r'], flags, help: undefined, mcp: { tools } }); + + it('refuses two tools with one name or one place', () => { + expect(() => createCommandRegistry([{ ...base, mcp: { tools: [tool, tool] } }], [])).toThrow(/MCP tool "t"/); + expect(() => createCommandRegistry([{ ...base, mcp: { tools: [tool, { ...tool, name: 'u' }] } }], [])).toThrow(/place "1"/); + }); + + it('generates a tool\'s schema: its params in order, then the flags it passes on that agents may pass and apply to its subcommand', () => { + const registry = createCommandRegistry([withTools([ + { name: 'z', takesValue: true, agent: { type: 'string', description: 'Z' } }, + { name: 'only-r', takesValue: true, subcommands: ['r'], agent: { type: 'string' } }, + { name: 'loud', takesValue: false, agent: { notForAgents: 'a terminal\'s' } }, + { name: 'a', takesValue: true, subcommands: ['s'], agent: { type: 'string', enum: ['x'] } }, + ], { + ...tool, + params: [{ name: 'id', schema: { type: 'string' } }, { flag: 'a', schema: { type: 'string', description: 'as shown before' } }], + required: ['id'], + argv: { subcommand: 's', positionals: ['id'], flags: 'rest' }, + })], [{ name: 'json', takesValue: false, agent: { notForAgents: 'set by the server' } }]); + expect(JSON.stringify(registry.tools[0]!.inputSchema)).toBe(JSON.stringify({ + type: 'object', + properties: { id: { type: 'string' }, a: { type: 'string', description: 'as shown before' }, z: { type: 'string', description: 'Z' } }, + required: ['id'], + })); + }); + + it('refuses a tool that places a flag its command lacks, one hidden from agents, or one not of its subcommand', () => { + const flags = [ + { name: 'hidden', takesValue: false, agent: { notForAgents: 'why' } }, + { name: 'only-r', takesValue: true, subcommands: ['r'], agent: { type: 'string' as const } }, + ]; + const placing = (flag: string) => withTools(flags, { ...tool, params: [{ flag }], argv: { subcommand: 's', flags: [flag] } }); + expect(() => createCommandRegistry([placing('nope')], [])).toThrow(/--nope, which x doesn't accept/); + expect(() => createCommandRegistry([placing('hidden')], [])).toThrow(/--hidden, which says no schema/); + expect(() => createCommandRegistry([placing('only-r')], [])).toThrow(/--only-r, which doesn't apply/); + }); + + it('refuses a tool passing the rest on when a flag of its subcommand says neither how agents see it nor why not', () => { + const rest = { ...tool, argv: { subcommand: 's', flags: 'rest' as const } }; + expect(() => createCommandRegistry([withTools([{ name: 'quiet', takesValue: false }], rest)], [])).toThrow(/--quiet on, which says neither/); + // A flag of another subcommand needs nothing. + expect(() => createCommandRegistry([withTools([{ name: 'quiet', takesValue: false, subcommands: ['r'] }], rest)], [])).not.toThrow(); + // Nor does a global flag, which the tool passes on too. + expect(() => createCommandRegistry([withTools([], rest)], [{ name: 'json', takesValue: false }])).toThrow(/--json on, which says neither/); + }); + + it('refuses an own parameter named like a flag, a mapping to a parameter it lacks, and a required one its schema lacks', () => { + const flags = [{ name: 'a', takesValue: true, agent: { type: 'string' as const } }]; + expect(() => createCommandRegistry([withTools(flags, { ...tool, params: [{ name: 'a', schema: { type: 'string' } }] })], [])).toThrow(/"a" is also a flag/); + expect(() => createCommandRegistry([withTools(flags, { ...tool, argv: { positionals: ['id'], flags: [] } })], [])).toThrow(/"id" fills/); + expect(() => createCommandRegistry([withTools(flags, { ...tool, argv: { flags: ['a'] } })], [])).toThrow(/passes "a"/); + expect(() => createCommandRegistry([withTools(flags, { ...tool, required: ['b'] })], [])).toThrow(/requires "b"/); + }); +}); diff --git a/src/__tests__/dust-balancing-plan.test.ts b/packages/cli-core/src/__tests__/dust-balancing-plan.test.ts similarity index 98% rename from src/__tests__/dust-balancing-plan.test.ts rename to packages/cli-core/src/__tests__/dust-balancing-plan.test.ts index 78e97b92..672cf5df 100644 --- a/src/__tests__/dust-balancing-plan.test.ts +++ b/packages/cli-core/src/__tests__/dust-balancing-plan.test.ts @@ -4,7 +4,7 @@ // combines them: the smallest first, until they cover what is owed. import { describe, expect, it } from 'vitest'; -import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '@kuiralabs/midnight-cli-core/lib/dust-balancing-plan'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '../lib/dust-balancing-plan.ts'; type Coin = DustInput; const coin = (token: string, value: bigint): Coin => ({ token, value }); diff --git a/src/__tests__/dust-registration-plan.test.ts b/packages/cli-core/src/__tests__/dust-registration-plan.test.ts similarity index 89% rename from src/__tests__/dust-registration-plan.test.ts rename to packages/cli-core/src/__tests__/dust-registration-plan.test.ts index 55375232..977ee4cc 100644 --- a/src/__tests__/dust-registration-plan.test.ts +++ b/packages/cli-core/src/__tests__/dust-registration-plan.test.ts @@ -3,10 +3,10 @@ // wallet airdropped 20 NIGHT 34 minutes earlier. import { describe, it, expect } from 'vitest'; -import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; -import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { classifyError, EXIT_INSUFFICIENT_BALANCE } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { formatWait } from '../lib/duration.ts'; +import { classifyError, EXIT_INSUFFICIENT_BALANCE } from '../lib/exit-codes.ts'; +import { DustFeeNotGeneratedError, planRegistration } from '../lib/dust-registration-plan.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; const FEE = 526_587_115_818_352n; const TWENTY_NIGHT = { dust: { generatedNow: 337_954_960_000_000n, rate: 165_340_000_000n, maxCap: 100_000_000_000_000_000n } }; @@ -62,7 +62,7 @@ describe('DustFeeNotGeneratedError', () => { }); it('exits as an insufficient balance, with its own error code', () => { - expect(classifyError(new DustFeeNotGeneratedError(planRegistration(FEE, [TWENTY_NIGHT]), now), installedCommands)) + expect(classifyError(new DustFeeNotGeneratedError(planRegistration(FEE, [TWENTY_NIGHT]), now), CORE_CODES)) .toEqual({ exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: 'DUST_GENERATING' }); }); }); diff --git a/src/__tests__/dust-wait.test.ts b/packages/cli-core/src/__tests__/dust-wait.test.ts similarity index 97% rename from src/__tests__/dust-wait.test.ts rename to packages/cli-core/src/__tests__/dust-wait.test.ts index 4be24b5c..0a5c0fa1 100644 --- a/src/__tests__/dust-wait.test.ts +++ b/packages/cli-core/src/__tests__/dust-wait.test.ts @@ -3,8 +3,9 @@ // NIGHT generates it (1000 NIGHT: ~0.0083 DUST/s on a ledger-9 localnet). import { describe, it, expect, vi } from 'vitest'; -import { DUST_SHORT_WAIT_MS, awaitDustForFee, dustShortError, msUntilDust, payWhenDustCovers, planDustWait, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; -import { withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { dustShortError, msUntilDust } from '../lib/dust-wait.ts'; +import { DUST_SHORT_WAIT_MS, awaitDustForFee, payWhenDustCovers, planDustWait, sleep } from '../lib/dust-wait.ts'; +import { withDustShortfall } from '../lib/sdk-errors.ts'; const DUST = 10n ** 15n; const NOW = new Date('2026-10-05T05:00:00Z'); diff --git a/src/__tests__/error-trim.test.ts b/packages/cli-core/src/__tests__/error-trim.test.ts similarity index 96% rename from src/__tests__/error-trim.test.ts rename to packages/cli-core/src/__tests__/error-trim.test.ts index c7342f6a..9807ee0d 100644 --- a/src/__tests__/error-trim.test.ts +++ b/packages/cli-core/src/__tests__/error-trim.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { trimAgentMessage } from '@kuiralabs/midnight-cli-core/lib/error-trim'; +import { trimAgentMessage } from '../lib/error-trim.ts'; describe('trimAgentMessage', () => { it('returns the input unchanged when there are no suggestions or paragraphs', () => { diff --git a/src/__tests__/exec-program.test.ts b/packages/cli-core/src/__tests__/exec-program.test.ts similarity index 96% rename from src/__tests__/exec-program.test.ts rename to packages/cli-core/src/__tests__/exec-program.test.ts index 1591c1d7..fd800701 100644 --- a/src/__tests__/exec-program.test.ts +++ b/packages/cli-core/src/__tests__/exec-program.test.ts @@ -3,8 +3,8 @@ // processes (this Node, running a short script), never on Docker. import { describe, expect, it } from 'vitest'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { execProgram, ProgramFailedError, ProgramTimedOutError } from '@kuiralabs/midnight-cli-core/lib/exec-program'; +import { CancelledError } from '../lib/errors.ts'; +import { execProgram, ProgramFailedError, ProgramTimedOutError } from '../lib/exec-program.ts'; /** Whether a process with this id is still alive. */ function isAlive(pid: number): boolean { diff --git a/src/__tests__/fee-limits.test.ts b/packages/cli-core/src/__tests__/fee-limits.test.ts similarity index 90% rename from src/__tests__/fee-limits.test.ts rename to packages/cli-core/src/__tests__/fee-limits.test.ts index 4e358f18..36cee8db 100644 --- a/src/__tests__/fee-limits.test.ts +++ b/packages/cli-core/src/__tests__/fee-limits.test.ts @@ -3,15 +3,9 @@ // may hold Dust at once. Amounts are exact: DUST has 15 decimals (specks). import { describe, it, expect } from 'vitest'; -import { - parseDustAmount, - parseFeeLimits, - feeLimitRefusal, - pendingLimitRefusal, - DEFAULT_FEE_LIMITS, - SPECKS_PER_DUST, -} from '@kuiralabs/midnight-cli-core/lib/fee-limits'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { parseDustAmount, parseFeeLimits, SPECKS_PER_DUST } from '../lib/fee-limits.ts'; +import { UsageError } from '../lib/errors.ts'; +import { feeLimitRefusal, pendingLimitRefusal, DEFAULT_FEE_LIMITS } from '../lib/fee-limits.ts'; describe('parseDustAmount', () => { it.each([ diff --git a/src/__tests__/format.test.ts b/packages/cli-core/src/__tests__/format.test.ts similarity index 98% rename from src/__tests__/format.test.ts rename to packages/cli-core/src/__tests__/format.test.ts index 035d3035..fdb80946 100644 --- a/src/__tests__/format.test.ts +++ b/packages/cli-core/src/__tests__/format.test.ts @@ -1,9 +1,5 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { - header, divider, keyValue, - toNight, formatNight, toDust, roughDust, formatDust, formatAddress, - box, errorMessage, usageMessage, successMessage, -} from '@kuiralabs/midnight-cli-core/ui/format'; +import { header, divider, keyValue, toNight, formatNight, toDust, roughDust, formatDust, formatAddress, box, errorMessage, usageMessage, successMessage } from '../ui/format.ts'; // Run format tests with NO_COLOR so we can assert exact string content // without ANSI escape codes getting in the way diff --git a/src/__tests__/host.test.ts b/packages/cli-core/src/__tests__/host.test.ts similarity index 89% rename from src/__tests__/host.test.ts rename to packages/cli-core/src/__tests__/host.test.ts index d97022fb..1636f5b0 100644 --- a/src/__tests__/host.test.ts +++ b/packages/cli-core/src/__tests__/host.test.ts @@ -2,10 +2,10 @@ // values or functions read when used, and state kept per host. import { describe, expect, it } from 'vitest'; -import { createHost, defineHostSlot } from '@kuiralabs/midnight-cli-core/lib/host'; -import { NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { createHost, defineHostSlot } from '../lib/host.ts'; +import { NoStateRootError } from '../lib/state-root.ts'; +import { settingsFromEnvironment } from '../lib/settings.ts'; +import { type Prompter } from '../lib/prompter.ts'; describe('createHost', () => { it('gives, when told nothing: every setting unset, no state root, notices dropped, nobody to ask', () => { diff --git a/src/__tests__/keystore.test.ts b/packages/cli-core/src/__tests__/keystore.test.ts similarity index 98% rename from src/__tests__/keystore.test.ts rename to packages/cli-core/src/__tests__/keystore.test.ts index c6bac5e4..6707b095 100644 --- a/src/__tests__/keystore.test.ts +++ b/packages/cli-core/src/__tests__/keystore.test.ts @@ -5,7 +5,7 @@ // machine than mn's own parameters do. import { describe, expect, it } from 'vitest'; -import { MalformedSecretError, WrongPassphraseError, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { MalformedSecretError, WrongPassphraseError, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '../lib/keystore.ts'; const SEED = Buffer.from('aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233', 'hex'); const PASSPHRASE = 'correct horse battery staple'; diff --git a/src/__tests__/local-stacks.test.ts b/packages/cli-core/src/__tests__/local-stacks.test.ts similarity index 85% rename from src/__tests__/local-stacks.test.ts rename to packages/cli-core/src/__tests__/local-stacks.test.ts index 925bf87e..6cf2a8c9 100644 --- a/src/__tests__/local-stacks.test.ts +++ b/packages/cli-core/src/__tests__/local-stacks.test.ts @@ -6,13 +6,8 @@ // two stacks (image names normalised). import { describe, it, expect } from 'vitest'; -import { - parseLocalStacks, - pickLocalStack, - resolveNetworkConfig, - AmbiguousLocalStacksError, -} from '@kuiralabs/midnight-cli-core/lib/network'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { parseLocalStacks, pickLocalStack, resolveNetworkConfig, AmbiguousLocalStacksError } from '../lib/network.ts'; +import { settingsFromEnvironment } from '../lib/settings.ts'; // Settings that turn detection off, for the resolutions whose docker output isn't the test's. const NO_DETECT = settingsFromEnvironment({ MN_NO_LOCAL_DETECT: '1' }); @@ -146,8 +141,8 @@ describe('resolveNetwork', () => { } it('applies endpoints saved with `midnight config set`, for commands with no endpoint flags', async () => { - const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); - const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); + const { resolveNetwork } = await import('../lib/resolve-network.ts'); + const { parseArgs } = await import('../lib/argv.ts'); await withConfig({ network: 'undeployed', networks: { undeployed: { node: 'ws://localhost:29944', 'indexer-ws': 'ws://localhost:28088/api/v4/graphql/ws', 'proof-server': 'http://localhost:26300' } }, @@ -161,8 +156,8 @@ describe('resolveNetwork', () => { }); it('lets a flag win over the saved config', async () => { - const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); - const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); + const { resolveNetwork } = await import('../lib/resolve-network.ts'); + const { parseArgs } = await import('../lib/argv.ts'); await withConfig({ network: 'undeployed', networks: { undeployed: { node: 'ws://localhost:29944' } } }, (configDir) => { const { config } = resolveNetwork({ args: parseArgs(['balance', '--node', 'ws://localhost:39944']), configDir }, NO_DETECT); expect(config.node).toBe('ws://localhost:39944'); @@ -170,8 +165,8 @@ describe('resolveNetwork', () => { }); it('keeps one network\'s saved endpoints away from another', async () => { - const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); - const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); + const { resolveNetwork } = await import('../lib/resolve-network.ts'); + const { parseArgs } = await import('../lib/argv.ts'); await withConfig({ network: 'preview', networks: { preview: { 'proof-server': 'http://preview-prover:6300' } } }, (configDir) => { const { config } = resolveNetwork({ args: parseArgs(['balance', '--network', 'preprod']), configDir }, NO_DETECT); expect(config.proofServer).toBe('http://localhost:6300'); @@ -179,8 +174,8 @@ describe('resolveNetwork', () => { }); it('with every endpoint given by flag, works whatever docker runs', async () => { - const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); - const { parseArgs } = await import('@kuiralabs/midnight-cli-core/lib/argv'); + const { resolveNetwork } = await import('../lib/resolve-network.ts'); + const { parseArgs } = await import('../lib/argv.ts'); await withConfig(null, (configDir) => { const { name, config } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed', '--node', 'ws://localhost:29944', @@ -193,13 +188,3 @@ describe('resolveNetwork', () => { }); }); }); - -describe('mn cache clear with several local stacks', () => { - it('needs only the network name, so it never runs detection', async () => { - const src = (await import('node:fs')).readFileSync(new URL('../commands/cache.ts', import.meta.url), 'utf-8'); - // Full resolution would detect local stacks and refuse when several run, - // yet cache takes no endpoint flags to settle it. - expect(src).toContain('resolveNetworkName('); - expect(src).not.toMatch(/\bresolveNetwork\(/); - }); -}); diff --git a/src/__tests__/network.test.ts b/packages/cli-core/src/__tests__/network.test.ts similarity index 98% rename from src/__tests__/network.test.ts rename to packages/cli-core/src/__tests__/network.test.ts index 295a3783..f5a6fb47 100644 --- a/src/__tests__/network.test.ts +++ b/packages/cli-core/src/__tests__/network.test.ts @@ -2,15 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import { - detectNetworkFromAddress, - isValidNetworkName, - getNetworkConfig, - getValidNetworkNames, - resolveNetworkConfig, - applyEndpointOverrides, - indexerHttpFromWs, -} from '@kuiralabs/midnight-cli-core/lib/network'; +import { detectNetworkFromAddress, isValidNetworkName, getNetworkConfig, getValidNetworkNames, resolveNetworkConfig, applyEndpointOverrides, indexerHttpFromWs } from '../lib/network.ts'; describe('detectNetworkFromAddress', () => { it('detects preprod from address prefix', () => { diff --git a/src/__tests__/offer-envelope.test.ts b/packages/cli-core/src/__tests__/offer-envelope.test.ts similarity index 86% rename from src/__tests__/offer-envelope.test.ts rename to packages/cli-core/src/__tests__/offer-envelope.test.ts index 903778a1..aa750785 100644 --- a/src/__tests__/offer-envelope.test.ts +++ b/packages/cli-core/src/__tests__/offer-envelope.test.ts @@ -2,10 +2,10 @@ // other than its transaction, and refused once past the maker's expiry. import { describe, it, expect } from 'vitest'; -import { assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, OfferExpiredError, type OfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; -import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; -import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, OfferExpiredError, type OfferEnvelope } from '../lib/offer-envelope.ts'; +import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '../lib/exit-codes.ts'; +import { NotAnOfferError } from '../lib/swap-offer.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; const A = '00'.repeat(31) + '01'; const B = '00'.repeat(31) + '02'; @@ -47,6 +47,6 @@ describe('the offer file', () => { const err = (() => { try { assertOfferUnexpired(ENVELOPE, ENVELOPE.expiresAt); } catch (e) { return e; } })() as OfferExpiredError; expect(err).toBeInstanceOf(OfferExpiredError); expect(err.message).toBe(`The offer ${'ab'.repeat(8)}… expired at 2026-11-03T12:00:00.000Z; ask the maker for a new one`); - expect(classifyError(err, installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_EXPIRED }); + expect(classifyError(err, CORE_CODES)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_EXPIRED }); }); }); diff --git a/src/__tests__/open-offers.test.ts b/packages/cli-core/src/__tests__/open-offers.test.ts similarity index 84% rename from src/__tests__/open-offers.test.ts rename to packages/cli-core/src/__tests__/open-offers.test.ts index e9eb4c14..54e5cd39 100644 --- a/src/__tests__/open-offers.test.ts +++ b/packages/cli-core/src/__tests__/open-offers.test.ts @@ -5,9 +5,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { assertSpendsNoOfferCoin, closeOpenOffers, OfferCoinsInUseError, openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { closeOpenOffers, OfferCoinsInUseError, openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '../lib/open-offers.ts'; +import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '../lib/exit-codes.ts'; +import { assertSpendsNoOfferCoin } from '../lib/open-offers.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; const WALLET = 'mn_addr_undeployed1maker'; const offer = (id: string, nullifiers: string[]): OpenOffer => ({ @@ -52,7 +53,7 @@ describe('open offers', () => { expect(err).toBeInstanceOf(OfferCoinsInUseError); expect(err.offerIds).toEqual(['a1'.repeat(16)]); expect(err.message).toBe(`This would spend coins held by an open swap offer (${'a1'.repeat(8)}…), cancelling it. Cancel it first, or wait until it is taken.`); - expect(classifyError(err, installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_COINS_IN_USE }); + expect(classifyError(err, CORE_CODES)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.OFFER_COINS_IN_USE }); expect(() => assertSpendsNoOfferCoin(open, ['aa11'], ['a1'.repeat(16)])).not.toThrow(); }); }); diff --git a/src/__tests__/phase-tracker.test.ts b/packages/cli-core/src/__tests__/phase-tracker.test.ts similarity index 97% rename from src/__tests__/phase-tracker.test.ts rename to packages/cli-core/src/__tests__/phase-tracker.test.ts index f8faa2e4..ab073bcd 100644 --- a/src/__tests__/phase-tracker.test.ts +++ b/packages/cli-core/src/__tests__/phase-tracker.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { createPhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; +import { createPhaseTracker } from '../lib/phase-tracker.ts'; describe('createPhaseTracker', () => { beforeEach(() => { diff --git a/src/__tests__/resolve-network.test.ts b/packages/cli-core/src/__tests__/resolve-network.test.ts similarity index 95% rename from src/__tests__/resolve-network.test.ts rename to packages/cli-core/src/__tests__/resolve-network.test.ts index 130c1cd7..31b367a5 100644 --- a/src/__tests__/resolve-network.test.ts +++ b/packages/cli-core/src/__tests__/resolve-network.test.ts @@ -2,10 +2,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import { resolveBlockfrostProjectId, resolveNetworkName, resolveNetwork, type NetworkResolutionContext } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { saveCliConfig, setConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { resolveBlockfrostProjectId, resolveNetworkName, resolveNetwork, type NetworkResolutionContext } from '../lib/resolve-network.ts'; +import { saveCliConfig, setConfigValue } from '../lib/cli-config.ts'; +import { parseArgs, type ParsedArgs } from '../lib/argv.ts'; +import { settingsFromEnvironment } from '../lib/settings.ts'; // The settings resolution is given: no Blockfrost id, and no local stack // detection (what docker runs on this machine must not matter). diff --git a/src/__tests__/sdk-errors.test.ts b/packages/cli-core/src/__tests__/sdk-errors.test.ts similarity index 91% rename from src/__tests__/sdk-errors.test.ts rename to packages/cli-core/src/__tests__/sdk-errors.test.ts index c8f65f08..1cef9378 100644 --- a/src/__tests__/sdk-errors.test.ts +++ b/packages/cli-core/src/__tests__/sdk-errors.test.ts @@ -6,13 +6,14 @@ import { describe, it, expect } from 'vitest'; import { Brand, Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { NodeClientError } from '@midnightntwrk/wallet-sdk/node-client/effect'; -import { dustShortfallOf, isColdStartRace, isDustShortage, mnCodeOf, nodeRefusalOf, refusalCodeOf, toEngineError, withDustShortfall, withEngineCode, withNodeReason } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { DustRequiredError, InsufficientBalanceError, NetworkError, ProofFailureError, ProofTimeoutError, StaleWalletStateError, SyncTimeoutError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { createApiError } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { installedCommands } from '../lib/installed-commands.ts'; -import { isTransportFailure } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; -import { closedPort } from './helpers/closed-port.ts'; +import { DustRequiredError, InsufficientBalanceError, NetworkError, ProofFailureError, StaleWalletStateError, SyncTimeoutError, TransactionRefusedError } from '../lib/errors.ts'; +import { classifyError } from '../lib/exit-codes.ts'; +import { createApiError } from '../lib/connector-api.ts'; +import { isTransportFailure } from '../lib/transport-failure.ts'; +import { dustShortfallOf, isColdStartRace, isDustShortage, mnCodeOf, nodeRefusalOf, refusalCodeOf, toEngineError, withDustShortfall, withEngineCode, withNodeReason } from '../lib/sdk-errors.ts'; +import { ProofTimeoutError } from '../lib/errors.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; +import { closedPort } from '../../../../test-support/closed-port.ts'; /** wallet-sdk 2.0's dust InsufficientFundsError: tagged, with the token it could not balance. */ function sdkInsufficientFunds(tokenType: string): Error { @@ -169,21 +170,21 @@ describe("the node's reason for refusing a transaction", () => { expect(reported).toBeInstanceOf(TransactionRefusedError); expect(reported.message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 170'); expect(reported.cause).toBe(thrown); - expect(classifyError(reported, installedCommands)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); + expect(classifyError(reported, CORE_CODES)).toEqual({ exitCode: 6, errorCode: 'INVALID_DUST_PROOF' }); // Unexplained, the same error is UNKNOWN. - expect(classifyError(thrown, installedCommands).errorCode).toBe('UNKNOWN'); + expect(classifyError(thrown, CORE_CODES).errorCode).toBe('UNKNOWN'); }); it("is the node client's own words when the node gave none", async () => { const thrown = await caught(refusal(new NodeClientError.TransactionInvalidError({ message: 'Transaction is invalid and was rejected by the node', txData: TX_DATA }))); expect(nodeRefusalOf(thrown)).toBe('Transaction is invalid and was rejected by the node'); - expect(classifyError(withNodeReason(thrown), installedCommands)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); + expect(classifyError(withNodeReason(thrown), CORE_CODES)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); }); it('classifies a reason no rule knows as TX_REJECTED, with the reason in the message', async () => { const reported = withNodeReason(await caught(refusal(new NodeClientError.SubmissionError({ message: 'Transaction submission failed', txData: TX_DATA, cause: new Error('1010: Invalid Transaction: Custom error: 199') })))); expect(reported.message).toContain('Custom error: 199'); - expect(classifyError(reported, installedCommands)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); + expect(classifyError(reported, CORE_CODES)).toEqual({ exitCode: 6, errorCode: 'TX_REJECTED' }); }); it('leaves any other error as it is, and a submission error with nothing under its wrapper', async () => { @@ -219,7 +220,7 @@ describe("the engine contract's reading of a failure", () => { // The ledger's words when a saved state is resumed on an indexer that numbers its events differently. const resumed = toEngineError(new Error('Failed applying dust events: commitment inserted non-linearly')) as Error; expect(resumed).toBeInstanceOf(StaleWalletStateError); - expect(classifyError(resumed, installedCommands)).toStrictEqual({ errorCode: 'STALE_CACHE', exitCode: 6 }); + expect(classifyError(resumed, CORE_CODES)).toStrictEqual({ errorCode: 'STALE_CACHE', exitCode: 6 }); }); it("leaves an error that carries its own code, a refusal already reported, and one it doesn't name, as they are", () => { @@ -243,8 +244,8 @@ describe("the engine contract's reading of a failure", () => { const fetched = await fetch(`http://127.0.0.1:${await closedPort()}/`).then(() => { throw new Error('expected fetch to fail'); }, (e: Error) => e); expect(fetched.message).toBe('fetch failed'); expect(isTransportFailure(Object.assign(new Error('the SDK said no more'), { cause: fetched }))).toBe(true); - expect(classifyError(toEngineError(fetched) as Error, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); - expect(classifyError(toEngineError(new Error('WebSocket connection to ws://127.0.0.1:8088 failed')) as Error, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + expect(classifyError(toEngineError(fetched) as Error, CORE_CODES)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + expect(classifyError(toEngineError(new Error('WebSocket connection to ws://127.0.0.1:8088 failed')) as Error, CORE_CODES)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); // A proof server out of reach is a failed proof, as the SDK says first. expect(toEngineError(new Error('Failed to prove transaction', { cause: socket }))).toBeInstanceOf(ProofFailureError); // An error with a code of its own keeps it, whatever its cause. diff --git a/src/__tests__/sdk-layout.test.ts b/packages/cli-core/src/__tests__/sdk-layout.test.ts similarity index 96% rename from src/__tests__/sdk-layout.test.ts rename to packages/cli-core/src/__tests__/sdk-layout.test.ts index d58b6d32..bc12f770 100644 --- a/src/__tests__/sdk-layout.test.ts +++ b/packages/cli-core/src/__tests__/sdk-layout.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { MixedSdkLayoutError, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { MixedSdkLayoutError, assertOneSdkCopy } from '../lib/sdk-layout.ts'; let dir: string; beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-sdk-layout-')); }); diff --git a/src/__tests__/sdk-warnings.test.ts b/packages/cli-core/src/__tests__/sdk-warnings.test.ts similarity index 98% rename from src/__tests__/sdk-warnings.test.ts rename to packages/cli-core/src/__tests__/sdk-warnings.test.ts index 4e62c763..63235266 100644 --- a/src/__tests__/sdk-warnings.test.ts +++ b/packages/cli-core/src/__tests__/sdk-warnings.test.ts @@ -3,7 +3,7 @@ // tested in a process of their own (process-safety.test.ts). import { describe, it, expect } from 'vitest'; -import { createSdkWarningRouter, sdkTransientWarning, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { createSdkWarningRouter, sdkTransientWarning, sdkWarningCallsOn } from '../lib/sdk-warnings.ts'; describe('the SDK-warning router', () => { it('gives a warning with a call\'s identity to that call\'s newest listener, and no other call\'s', () => { diff --git a/src/__tests__/shielded-policy.test.ts b/packages/cli-core/src/__tests__/shielded-policy.test.ts similarity index 94% rename from src/__tests__/shielded-policy.test.ts rename to packages/cli-core/src/__tests__/shielded-policy.test.ts index 25eaeaa4..0be32daa 100644 --- a/src/__tests__/shielded-policy.test.ts +++ b/packages/cli-core/src/__tests__/shielded-policy.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { networkHasShielded, shieldedSyncEnabled, shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; +import { networkHasShielded, shieldedSyncEnabled, shieldedDisabledReason } from '../lib/shielded-policy.ts'; describe('shielded-policy', () => { it('marks localnet (undeployed) as having shielded, hosted testnets as not', () => { diff --git a/src/__tests__/sign-data.test.ts b/packages/cli-core/src/__tests__/sign-data.test.ts similarity index 95% rename from src/__tests__/sign-data.test.ts rename to packages/cli-core/src/__tests__/sign-data.test.ts index 443c2174..be6052fa 100644 --- a/src/__tests__/sign-data.test.ts +++ b/packages/cli-core/src/__tests__/sign-data.test.ts @@ -2,7 +2,7 @@ // never signs bytes other than the ones the dApp meant. import { describe, expect, it } from 'vitest'; -import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; +import { decodeSignPayload, signedMessageBytes } from '../lib/sign-data.ts'; describe('signedMessageBytes', () => { it('puts "midnight_signed_message::" before the bytes', () => { diff --git a/src/__tests__/sleep.test.ts b/packages/cli-core/src/__tests__/sleep.test.ts similarity index 88% rename from src/__tests__/sleep.test.ts rename to packages/cli-core/src/__tests__/sleep.test.ts index 4b36a0a0..9db324cf 100644 --- a/src/__tests__/sleep.test.ts +++ b/packages/cli-core/src/__tests__/sleep.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { untilCancelled } from '@kuiralabs/midnight-cli-core/lib/sleep'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { untilCancelled } from '../lib/sleep.ts'; +import { CancelledError } from '../lib/errors.ts'; describe('untilCancelled', () => { it('gives what the work gives, and its error', async () => { diff --git a/src/__tests__/spinner-reporter.test.ts b/packages/cli-core/src/__tests__/spinner-reporter.test.ts similarity index 94% rename from src/__tests__/spinner-reporter.test.ts rename to packages/cli-core/src/__tests__/spinner-reporter.test.ts index aff5d47f..852a9a05 100644 --- a/src/__tests__/spinner-reporter.test.ts +++ b/packages/cli-core/src/__tests__/spinner-reporter.test.ts @@ -3,8 +3,8 @@ // steps say still reaches the call's report (the MCP server's progress). import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { createProgress, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { createProgress, spinnerReporter } from '../ui/spinner.ts'; +import { captureOutput, type CapturedOutput } from '../../../../test-support/capture-output.ts'; let io: CapturedOutput; const originalNoColor = process.env.NO_COLOR; diff --git a/src/__tests__/swap-offer.test.ts b/packages/cli-core/src/__tests__/swap-offer.test.ts similarity index 74% rename from src/__tests__/swap-offer.test.ts rename to packages/cli-core/src/__tests__/swap-offer.test.ts index aa8c7fd7..a506cf21 100644 --- a/src/__tests__/swap-offer.test.ts +++ b/packages/cli-core/src/__tests__/swap-offer.test.ts @@ -2,9 +2,10 @@ // its refusals classify: the caller's to fix. import { describe, it, expect } from 'vitest'; -import { checkTerms, NotAnOfferError, TermsMismatchError, type SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; -import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { checkTerms, TermsMismatchError, type SwapTerms } from '../lib/swap-offer.ts'; +import { classifyError, ERROR_CODES, EXIT_INVALID_ARGS } from '../lib/exit-codes.ts'; +import { NotAnOfferError } from '../lib/swap-offer.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; const A = '00'.repeat(31) + '01'; const B = '00'.repeat(31) + '02'; @@ -28,7 +29,7 @@ describe('checkTerms', () => { }); it('classifies a terms mismatch and bytes that are no offer as the caller\'s to fix', () => { - expect(classifyError(new TermsMismatchError(AGREED, AGREED), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.TERMS_MISMATCH }); - expect(classifyError(new NotAnOfferError('it is not hex'), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.NOT_AN_OFFER }); + expect(classifyError(new TermsMismatchError(AGREED, AGREED), CORE_CODES)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.TERMS_MISMATCH }); + expect(classifyError(new NotAnOfferError('it is not hex'), CORE_CODES)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.NOT_AN_OFFER }); }); }); diff --git a/src/__tests__/terminal-prompter.test.ts b/packages/cli-core/src/__tests__/terminal-prompter.test.ts similarity index 92% rename from src/__tests__/terminal-prompter.test.ts rename to packages/cli-core/src/__tests__/terminal-prompter.test.ts index 226f5588..7b1ba68c 100644 --- a/src/__tests__/terminal-prompter.test.ts +++ b/packages/cli-core/src/__tests__/terminal-prompter.test.ts @@ -6,10 +6,10 @@ import { describe, expect, it } from 'vitest'; import { spawnSync } from 'node:child_process'; import { resolve } from 'node:path'; import { PassThrough } from 'node:stream'; -import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; -import { PromptBusyError } from '@kuiralabs/midnight-cli-core/lib/prompter'; +import { PromptBusyError } from '../lib/prompter.ts'; +import { createTerminalPrompter } from '../ui/terminal-prompter.ts'; -const ROOT = resolve(import.meta.dirname, '..', '..'); +const ROOT = resolve(import.meta.dirname, '..', '..', '..', '..'); describe('the terminal prompter', () => { it('does not touch stdin when it is made, only when it asks', () => { @@ -17,7 +17,7 @@ describe('the terminal prompter', () => { let touched = 0; const own = Object.getOwnPropertyDescriptor(process, 'stdin'); Object.defineProperty(process, 'stdin', { configurable: true, get() { touched++; return own.get.call(process); } }); - const { createTerminalPrompter } = await import(${JSON.stringify(resolve(ROOT, 'packages/cli-core/src/ui/terminal-prompter.ts'))}); + const { createTerminalPrompter } = await import(${JSON.stringify(resolve(import.meta.dirname, '..', 'ui', 'terminal-prompter.ts'))}); const prompter = createTerminalPrompter(); const atCreation = touched; prompter.isInteractive(); diff --git a/src/__tests__/transport-failure.test.ts b/packages/cli-core/src/__tests__/transport-failure.test.ts similarity index 89% rename from src/__tests__/transport-failure.test.ts rename to packages/cli-core/src/__tests__/transport-failure.test.ts index f08c4947..7cb2085a 100644 --- a/src/__tests__/transport-failure.test.ts +++ b/packages/cli-core/src/__tests__/transport-failure.test.ts @@ -4,11 +4,11 @@ import { describe, expect, it } from 'vitest'; import { WebSocket } from 'ws'; -import { carriesOwnCode, isTransportFailure, withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; -import { DustRequiredError, NetworkError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; -import { closedPort } from './helpers/closed-port.ts'; +import { carriesOwnCode, isTransportFailure, withTransportCode } from '../lib/transport-failure.ts'; +import { DustRequiredError, NetworkError } from '../lib/errors.ts'; +import { classifyError } from '../lib/exit-codes.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; +import { closedPort } from '../../../../test-support/closed-port.ts'; /** What a WebSocket to a closed port fails with: the socket's own error, ECONNREFUSED its code. */ async function refusedWebSocket(): Promise { @@ -65,7 +65,7 @@ describe('withTransportCode', () => { expect(reported).toBeInstanceOf(NetworkError); expect(reported.message).toBe(refused.message); expect(reported.cause).toBe(refused); - expect(classifyError(reported, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + expect(classifyError(reported, CORE_CODES)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); }); it('leaves an error with a code of its own, and any other error, as it is', () => { diff --git a/src/__tests__/tx-serde.test.ts b/packages/cli-core/src/__tests__/tx-serde.test.ts similarity index 95% rename from src/__tests__/tx-serde.test.ts rename to packages/cli-core/src/__tests__/tx-serde.test.ts index e505bc10..359d58ab 100644 --- a/src/__tests__/tx-serde.test.ts +++ b/packages/cli-core/src/__tests__/tx-serde.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; +import { toHex, fromHex } from '../lib/tx-serde.ts'; describe('tx-serde', () => { describe('toHex', () => { diff --git a/src/__tests__/verbose.test.ts b/packages/cli-core/src/__tests__/verbose.test.ts similarity index 92% rename from src/__tests__/verbose.test.ts rename to packages/cli-core/src/__tests__/verbose.test.ts index 8e6c6049..1890db44 100644 --- a/src/__tests__/verbose.test.ts +++ b/packages/cli-core/src/__tests__/verbose.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { verboseLine } from '@kuiralabs/midnight-cli-core/lib/verbose'; +import { verboseLine } from '../lib/verbose.ts'; // The verbose line's format. Whether a call shows it is the call's own // (verbose-per-call.test.ts, call-context.test.ts). diff --git a/src/__tests__/wallet-cache.test.ts b/packages/cli-core/src/__tests__/wallet-cache.test.ts similarity index 97% rename from src/__tests__/wallet-cache.test.ts rename to packages/cli-core/src/__tests__/wallet-cache.test.ts index a9793f47..c0d03c48 100644 --- a/src/__tests__/wallet-cache.test.ts +++ b/packages/cli-core/src/__tests__/wallet-cache.test.ts @@ -4,13 +4,9 @@ import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { randomBytes } from 'node:crypto'; -import { - loadWalletCache, - saveWalletCache, - clearWalletCache, - getCachePath, -} from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { CACHE_VERSION } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { clearWalletCache } from '../lib/wallet-cache.ts'; +import { CACHE_VERSION } from '../lib/constants.ts'; +import { loadWalletCache, saveWalletCache, getCachePath } from '../lib/wallet-cache.ts'; const TEST_ADDRESS = 'mn_addr_preprod1mp06mtx1234567890abcdef'; const TEST_NETWORK = 'preprod'; diff --git a/packages/cli-core/src/commands.ts b/packages/cli-core/src/commands.ts new file mode 100644 index 00000000..53ce22c4 --- /dev/null +++ b/packages/cli-core/src/commands.ts @@ -0,0 +1,7 @@ +// @kuiralabs/midnight-cli-core/commands: core's own command (config), its +// codes and the code sets other packages' definitions name, and its agent +// guidance, for the shell that installs them. + +export { configDefinition } from './commands/config.definition.ts'; +export { coreCodes, ENGINE_SYNC, EVERY_COMMAND, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from './commands/core.codes.ts'; +export { coreGuidance } from './commands/core.guidance.ts'; diff --git a/packages/cli-core/src/engine.ts b/packages/cli-core/src/engine.ts new file mode 100644 index 00000000..b40e8687 --- /dev/null +++ b/packages/cli-core/src/engine.ts @@ -0,0 +1,47 @@ +// @kuiralabs/midnight-cli-core/engine: what an SDK engine is built against. +// The engine contract (the Engine interface and its parts), reading the SDK's +// and the node's errors (sdk-errors), the wallet cache, the Dust balancing and +// registration plans, the SDK layout check, transaction hex, and the constants +// and helpers the engines use that no other package does. + +export { type ApprovalOptions, promptApproval } from './lib/approval.ts'; +export { bindCachesToIndexer, describeIndexerChange } from './lib/cache-indexer.ts'; +export { + ABANDONED_TX_TIMEOUT_MS, DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, + DUST_REGISTRATION_RETRY_DELAY_MS, DUST_REGISTRATION_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, + DUST_RETRY_DELAY_MS, DUST_TIMEOUT_MS, INITIAL_DUST_GRACE_PERIOD_SECONDS, + INITIAL_GENERATION_DECAY_RATE, INITIAL_NIGHT_DUST_RATIO, MAX_RETRY_ATTEMPTS, MIN_DUST_FOR_TRANSFER, + PRE_SEND_SYNC_TIMEOUT_MS, PROOF_TIMEOUT_MS, STALE_UTXO_ERROR_CODE, SYNC_ATTEMPT_TIMEOUT_MS, + SYNC_TIMEOUT_MS, TOKEN_MULTIPLIER, TX_TTL_MINUTES +} from './lib/constants.ts'; +export { chooseDustCoins, type DustInput, planDustInputs, spreadFeeAcrossInputs } from './lib/dust-balancing-plan.ts'; +export { DustFeeNotGeneratedError, planRegistration } from './lib/dust-registration-plan.ts'; +export { awaitDustForFee, DUST_SHORT_WAIT_MS, type DustWaitPlan, payWhenDustCovers, planDustWait, sleep } from './lib/dust-wait.ts'; +export { + type AirdropParams, type BlockLimits, type CachedReadOptions, type CallScript, type DAppConnector, + type DAppConnectorCallbacks, type DeployScript, type DustBalance, type DustExportResult, + type DustRegisterOptions, type DustRegistration, type Engine, type EngineHost, type EngineWallet, + type EnsureDustResult, type OpenedConnector, type PrepWallet, type RawStateValue, type ReadOptions, + type ScriptParts, type ServedWalletSession, type ShieldedBalanceResult, type ShieldedCachedOptions, + type ShieldedTransferParams, type StateScript, type TransactionDetail, type TransferParams, + type TransferResult, type UnshieldedView +} from './lib/engine.ts'; +export { EngineError, ProofTimeoutError } from './lib/errors.ts'; +export { DEFAULT_FEE_LIMITS, feeLimitRefusal, type FeeLimits, pendingLimitRefusal } from './lib/fee-limits.ts'; +export { getNetworkId, networkIdForName } from './lib/network-id.ts'; +export { assertSpendsNoOfferCoin } from './lib/open-offers.ts'; +export { createPhaseTracker, type PhaseTracker } from './lib/phase-tracker.ts'; +export { dustCacheDir, getDustCachePath, getShieldedCachePath, nativeCheckpointName } from './lib/reader-cache-files.ts'; +export { + type DustShortfall, dustShortfallOf, isColdStartRace, isDustRelatedError, isDustShortage, + isSdkInsufficientFundsError, markingEngineCodes, refusalCodeOf, reportingEngineErrors, toEngineError, + withDustShortfall, withEngineCode +} from './lib/sdk-errors.ts'; +export { assertOneSdkCopy, MixedSdkLayoutError, resolvedPackageFolder } from './lib/sdk-layout.ts'; +export { decodeSignPayload, signedMessageBytes } from './lib/sign-data.ts'; +export { describeLeg, NotAnOfferError } from './lib/swap-offer.ts'; +export { fromHex, toHex } from './lib/tx-serde.ts'; +export { + cacheRootDir, clearWalletCache, getCachePath, loadWalletCache, networkCacheFolder, saveWalletCache, + validateWalletCacheChainId, type WalletCacheData +} from './lib/wallet-cache.ts'; diff --git a/packages/cli-core/src/index.ts b/packages/cli-core/src/index.ts new file mode 100644 index 00000000..22daf643 --- /dev/null +++ b/packages/cli-core/src/index.ts @@ -0,0 +1,115 @@ +// @kuiralabs/midnight-cli-core: the library a program and the packages above +// call. Typed errors and their codes, the host, networks and network targets, +// the payer, progress, amounts, arguments, settings and the state root, the +// wallet session and swap offer types, and the rest the packages above core +// import. Each name is listed, so the API is what this file says. +// Engine implementors also import "./engine"; terminal output is "./ui"; +// core's command, codes and guidance are "./commands". + +export { + assembleGuidance, codeGuidancePieces, GuidanceError, type GuidancePiece, type GuidanceText, + manualCodeRow, type PackageGuidance, sectionsWithAdded, skillCodeRow, type ToolsTableRow, wrapWords +} from './lib/agent-guidance.ts'; +export { nightAmountJson, nightAmountText, nightToMicro, parseAmount } from './lib/amount.ts'; +export { describeApprovalPolicy } from './lib/approval.ts'; +export { + FULL_FLAG, getFlag, hasFlag, isMinimalMode, MINIMAL_FLAG, parseArgs, type ParsedArgs, + rejectNoCacheForWrites, requireFlag +} from './lib/argv.ts'; +export { + assertEndpointUsable, blockfrostEndpoints, BlockfrostLimitError, BlockfrostProjectIdRejectedError, + BlockfrostProjectIdRequiredError, endpointRefusal, endpointRefusalFromWsError, EndpointShutDownError, + isBlockfrostUrl, isEndpointError, mayHoldProjectId, redactProjectId +} from './lib/blockfrost.ts'; +export { + type CallContext, callDiagnostics, type CallOutput, type CallProgress, type CommandHandler, + type CommandOutcome, createCallContext, runHandler, SecondResultError +} from './lib/call-context.ts'; +export { + type CliConfig, getConfigValue, getEndpointOverridesForNetwork, loadCliConfig, saveCliConfig, + setConfigValue +} from './lib/cli-config.ts'; +export { + type CommandDefinition, CommandDefinitionError, commandErrorCodes, commandExitCodes, + type CommandHelpSpec, commandHelpSpecs, commandOwnCodes, type CommandPackage, type CommandRegistry, + confirmationTarget, confirmationText, createCommandRegistry, createPackageRegistry, declaredCodes, + declaredCodeSets, declaredSets, ENDPOINT_PARAMS, type FlagDefinition, type GlobalFlagHelp, + introBriefs, needsConfirmation, NETWORK_PARAM, type RegisteredTool, type ToolAnnotations, toolArgv, + type ToolCheckCall, type ToolDefinition, type ToolInputSchema +} from './lib/command-definition.ts'; +export { assertKnownFlags, findMisplacedFlags, findUnknownFlags } from './lib/command-flags.ts'; +export { + type APIError, createApiError, type ErrorCode, OPERATOR_REJECTED_MESSAGE, type RpcHandler, + type RpcHandlerContext +} from './lib/connector-api.ts'; +export { + BALANCE_CHECK_TIMEOUT_MS, DASHBOARD_BASE_URL, DEFAULT_SERVE_PORT, DEFAULT_WALLET_FILENAME, + DEFAULT_WALLET_NAME, DIR_MODE, FILE_MODE, GENESIS_SEED, isValidWalletName, LOCALNET_DIR_NAME, + MIDNIGHT_DIR, NATIVE_TOKEN_TYPE, SYNC_HEAP_MIN_GAIN_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_TARGET_MB, + WALLETS_DIR_NAME +} from './lib/constants.ts'; +export { FileExistsError, readJsonIfPresent, writeJsonDurably } from './lib/durable-file.ts'; +export { formatWait } from './lib/duration.ts'; +export { dustShortError, OWN_COMMAND_DUST_WAIT_MS } from './lib/dust-wait.ts'; +export { + type BalanceSummary, type DAppConnector, type DAppConnectorCallbacks, type DustExportResult, + type Engine, type EngineContractScripts, type EngineKeys, type HostEngines, type OpenedConnector, + OtherSdkSetError, type RawStateValue, type ScriptParts, type SdkSet, sdkSetOf +} from './lib/engine.ts'; +export { + type CodeDefinition, CodeDefinitionError, type CodeRegistry, type CodeSet, defineCodes, + defineCodeSet +} from './lib/error-codes.ts'; +export { trimAgentMessage } from './lib/error-trim.ts'; +export { + asReported, CANCELLED_MESSAGE, CancelledError, CommandFailedError, DustRequiredError, + InsufficientBalanceError, isUsageError, NetworkError, ProofFailureError, SyncTimeoutError, + throwIfCancelled, TransactionRefusedError, UsageError +} from './lib/errors.ts'; +export { execProgram, type ExecRun, type ExecRunner, ProgramFailedError, ProgramTimedOutError } from './lib/exec-program.ts'; +export { + classifyError, ERROR_CODES, EXIT_CANCELLED, EXIT_GENERAL_ERROR, EXIT_INSUFFICIENT_BALANCE, + EXIT_INVALID_ARGS, EXIT_NETWORK_ERROR, EXIT_TX_REJECTED, EXIT_WALLET_NOT_FOUND, humanizeNetworkError +} from './lib/exit-codes.ts'; +export { parseFeeLimits } from './lib/fee-limits.ts'; +export { createHost, defineHostSlot, type Host, type HostOptions } from './lib/host.ts'; +export { writeJsonError, writeJsonResult } from './lib/json-output.ts'; +export { + freshDataKey, isSealedSecret, type KeyedSecret, openSecret, openWithKey, type SealedSecret, + sealSecret, sealWithKey, WrongPassphraseError +} from './lib/keystore.ts'; +export { + AmbiguousLocalStacksError, applyEndpointOverrides, detectLocalStacks, endpointFlags, + type EndpointOverrides, getNetworkConfig, getValidNetworkNames, isValidNetworkName, + LEDGER_9_FORK_VERSION, type NetworkConfig, type NetworkName, networksOnSdkSet, resolveNetworkConfig, + sdkSetOfNetwork +} from './lib/network.ts'; +export { type NetworkChoice, networkChoiceFromArgs, networkTargetOf } from './lib/network-target.ts'; +export { type NoticeSink } from './lib/notices.ts'; +export { + assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, + type OfferEnvelope, OfferExpiredError +} from './lib/offer-envelope.ts'; +export { closeOpenOffers, OfferCoinsInUseError, type OpenOffer, readOpenOffers, recordOpenOffer } from './lib/open-offers.ts'; +export { + type ConnectOptions, NoPayerError, type Payer, payerFor, type PayingTarget, resolvePayingTarget, + type ServedWallet +} from './lib/payer.ts'; +export { type PhaseTiming } from './lib/phase-tracker.ts'; +export { type ProgressEvent, type ProgressListener, type ProgressSteps, progressSteps } from './lib/progress.ts'; +export { type Prompter } from './lib/prompter.ts'; +export { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from './lib/reader-cache-files.ts'; +export { type NetworkSettings, resolveBlockfrostProjectId, resolveNetwork, resolveNetworkName } from './lib/resolve-network.ts'; +export { + type CallSdkWarnings, createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls, + withCallSdkWarnings +} from './lib/sdk-warnings.ts'; +export { PASSPHRASE_ENV, type Settings, settingsFromEnvironment } from './lib/settings.ts'; +export { shieldedDisabledReason, shieldedSyncEnabled } from './lib/shielded-policy.ts'; +export { sleep, untilCancelled } from './lib/sleep.ts'; +export { NoStateRootError } from './lib/state-root.ts'; +export { checkTerms, type OfferContents, type SwapLeg, type SwapTerms, TermsMismatchError } from './lib/swap-offer.ts'; +export { isTransportFailure, withTransportCode } from './lib/transport-failure.ts'; +export { type VerboseLog } from './lib/verbose.ts'; +export { clearWalletCache } from './lib/wallet-cache.ts'; +export { sessionOver, type WalletSession } from './lib/wallet-session.ts'; diff --git a/packages/cli-core/src/lib/exec-program.ts b/packages/cli-core/src/lib/exec-program.ts index 2ab1fcea..3f0b434e 100644 --- a/packages/cli-core/src/lib/exec-program.ts +++ b/packages/cli-core/src/lib/exec-program.ts @@ -21,10 +21,21 @@ const KILL_GRACE_MS = 2_000; /** Runs `file` with `args` and returns its stdout once it exits with code 0. */ export type ExecRunner = (file: string, args: readonly string[], run: ExecRun) => Promise; +// Fields are declared, not parameter properties, so Node's own TypeScript type +// stripping can load core's source (the tests' child processes do). /** The program exited with a code other than 0 (null: killed by a signal from elsewhere); its stderr is in the message, and what it printed is kept. */ export class ProgramFailedError extends Error { - constructor(readonly command: string, readonly exitCode: number | null, readonly stderr: string, readonly stdout: string) { + readonly command: string; + readonly exitCode: number | null; + readonly stderr: string; + readonly stdout: string; + + constructor(command: string, exitCode: number | null, stderr: string, stdout: string) { super(`Command failed: ${command}\n${stderr}`); + this.command = command; + this.exitCode = exitCode; + this.stderr = stderr; + this.stdout = stdout; this.name = 'ProgramFailedError'; Object.setPrototypeOf(this, ProgramFailedError.prototype); } @@ -32,10 +43,12 @@ export class ProgramFailedError extends Error { /** The program ran past its time limit and was killed. Its code is NETWORK_ERROR: the programs mn runs with a limit are Docker's, which hang when its daemon or the network does. */ export class ProgramTimedOutError extends Error { + readonly command: string; readonly code = 'NETWORK_ERROR'; - constructor(readonly command: string, timeoutMs: number) { + constructor(command: string, timeoutMs: number) { super(`Command timed out (ETIMEDOUT) after ${timeoutMs / 1000}s: ${command}`); + this.command = command; this.name = 'ProgramTimedOutError'; Object.setPrototypeOf(this, ProgramTimedOutError.prototype); } diff --git a/packages/cli-core/src/lib/shielded-policy.ts b/packages/cli-core/src/lib/shielded-policy.ts index 8c82a426..d491da1b 100644 --- a/packages/cli-core/src/lib/shielded-policy.ts +++ b/packages/cli-core/src/lib/shielded-policy.ts @@ -6,7 +6,7 @@ // keep shielded on. Overridable with `--force-shielded` for the rare case a // wallet did receive shielded funds out of band. -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { NetworkName } from './network.ts'; /** Networks with no shielded faucet — shielded sync is skipped by default. */ const NO_SHIELDED_FAUCET: readonly NetworkName[] = ['preview', 'preprod', 'stagenet']; diff --git a/packages/cli-core/src/ui.ts b/packages/cli-core/src/ui.ts new file mode 100644 index 00000000..561c9bd4 --- /dev/null +++ b/packages/cli-core/src/ui.ts @@ -0,0 +1,10 @@ +// @kuiralabs/midnight-cli-core/ui: terminal output for commands: formatting, +// colours, the spinner and progress reporter, and the terminal prompter. + +export { bold, dim, gray, green, isColorEnabled, purple, red, teal, white, yellow } from './ui/colors.ts'; +export { + divider, errorMessage, formatAddress, formatDust, formatNight, header, keyValue, roughDust, + successMessage, toDust, toNight, usageMessage +} from './ui/format.ts'; +export { silentSpinner, type Spinner, type SpinnerReporter, spinnerReporter, trackElapsed } from './ui/spinner.ts'; +export { createTerminalPrompter } from './ui/terminal-prompter.ts'; diff --git a/packages/cli-core/tsconfig.build.json b/packages/cli-core/tsconfig.build.json index cb6aadd5..34ddea51 100644 --- a/packages/cli-core/tsconfig.build.json +++ b/packages/cli-core/tsconfig.build.json @@ -15,5 +15,7 @@ "outDir": "dist", "types": ["node"] }, - "include": ["src/**/*.ts"] + "include": ["src/**/*.ts"], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": ["src/**/__tests__"] } diff --git a/packages/engine-beta/api-report.md b/packages/engine-beta/api-report.md index a6a7d087..6c0d8ac2 100644 --- a/packages/engine-beta/api-report.md +++ b/packages/engine-beta/api-report.md @@ -1,599 +1,14 @@ # API report: @kuiralabs/midnight-engine-beta -Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. ## `@kuiralabs/midnight-engine-beta` ```ts -import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; +import { type Engine, type EngineHost } from "@kuiralabs/midnight-cli-core/engine"; import { type RepoDeps } from "./wallet-data-repository.ts"; export interface BetaEngineOptions { readonly repository?: RepoDeps; } export declare function createBetaEngine(host: EngineHost, options?: BetaEngineOptions): Engine; ``` - -## `@kuiralabs/midnight-engine-beta/addresses` - -```ts -import { ShieldedAddress, UnshieldedAddress } from "@midnightntwrk/wallet-sdk-address-format"; -import type { NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress; -export declare function decodeUnshieldedAddress(address: string, network: NetworkName): UnshieldedAddress; -export declare function assertAddress(address: string, kind: "shielded" | "unshielded", network: NetworkName): void; -``` - -## `@kuiralabs/midnight-engine-beta/airdrop` - -```ts -import { type TransferResult } from "./transfer.ts"; -import type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -export type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/contract-providers` - -```ts -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function buildStateProvider(networkConfig: NetworkConfig): import("@midnight-ntwrk/midnight-js-indexer-public-data-provider").IndexerPublicDataProvider; -export declare function rawContractState(networkConfig: NetworkConfig, address: string): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/contract-scripts` - -```ts -import type { CallScript, DeployScript, ScriptParts, StateScript } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare const SCRIPT_PACKAGES: readonly [ - "@midnight-ntwrk/compact-js", - "@midnight-ntwrk/compact-runtime", - "@midnight-ntwrk/midnight-js-contracts", - "@midnight-ntwrk/midnight-js-http-client-proof-provider", - "@midnight-ntwrk/midnight-js-indexer-public-data-provider", - "@midnight-ntwrk/midnight-js-level-private-state-provider", - "@midnight-ntwrk/midnight-js-network-id", - "@midnight-ntwrk/midnight-js-node-zk-config-provider", - "@midnight-ntwrk/midnight-js-types", - "@midnight-ntwrk/midnight-js-utils", - "ws" -]; -export declare function packageFolder(name: string): string | null; -export declare const PROVIDER_IMPORTS = "\nimport { Transaction } from '@midnight-ntwrk/midnight-js-types';\nimport { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils';\nimport { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';\nimport { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';\nimport { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';\nimport { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';\n"; -export declare function walletProviderCode(): string; -export declare function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string, parts: ScriptParts): string; -export declare function generateDeployScript(opts: DeployScript, parts: ScriptParts): string; -export declare function generateCallScript(opts: CallScript, parts: ScriptParts): string; -export declare function generateStateScript(opts: StateScript, parts: ScriptParts): string; -``` - -## `@kuiralabs/midnight-engine-beta/dapp-connector` - -```ts -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import type { FacadeState, WalletEntry } from "@midnightntwrk/wallet-sdk-facade"; -import { type FacadeBundle } from "./facade.ts"; -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { ApprovalOptions } from "@kuiralabs/midnight-cli-core/lib/approval"; -import { type FeeLimits } from "@kuiralabs/midnight-cli-core/lib/fee-limits"; -import { type OpenOffer } from "@kuiralabs/midnight-cli-core/lib/open-offers"; -import { type SegmentResult } from "@kuiralabs/midnight-chain/lib/tx-segments"; -import type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; -export interface DAppConnectorOptions { - bundle: FacadeBundle; - networkConfig: NetworkConfig; - approvalOptions: ApprovalOptions; - notice: NoticeSink; - feeLimits?: FeeLimits; - openOffers?: () => readonly OpenOffer[]; - callbacks?: DAppConnectorCallbacks; - initialState?: FacadeState; - isCurrent?: (state: FacadeState) => boolean; - dustWaitMs?: number; -} -export type TokenKindsToBalance = "all" | Array<"dust" | "shielded" | "unshielded">; -export { OPERATOR_REJECTED_MESSAGE } from "@kuiralabs/midnight-cli-core/lib/connector-api"; -export type HistoryEntry = { - txHash: string; - txStatus: { - status: "finalized"; - executionStatus: Record; - } | { - status: "pending"; - } | { - status: "discarded"; - }; -}; -export declare function toHistoryEntry(entry: WalletEntry, segments?: readonly SegmentResult[]): HistoryEntry; -export declare function signatureScheme(tag: string): "schnorr_bip340"; -export declare function createDAppConnector(options: DAppConnectorOptions): DAppConnector; -``` - -## `@kuiralabs/midnight-engine-beta/derivation` - -```ts -export declare function deriveShieldedSeed(seedBuffer: Buffer): Uint8Array; -export declare function deriveUnshieldedSeed(seedBuffer: Buffer): Uint8Array; -export declare function deriveDustSeed(seedBuffer: Buffer): Uint8Array; -``` - -## `@kuiralabs/midnight-engine-beta/derive-address` - -```ts -import { ShieldedAddress } from "@midnightntwrk/wallet-sdk-address-format"; -import { type NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare function deriveUnshieldedAddress(seedBuffer: Buffer, networkName: NetworkName, keyIndex?: number): string; -export declare function deriveAllAddresses(seedBuffer: Buffer, keyIndex?: number): Record; -export declare function deriveAllShieldedAddresses(seedBuffer: Buffer): Record; -export declare function deriveShieldedAddressString(seedBuffer: Buffer, networkName: NetworkName): string; -export declare function deriveShieldedAddress(seedBuffer: Buffer): ShieldedAddress; -``` - -## `@kuiralabs/midnight-engine-beta/dust-collapse` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface CollapseOutcome { - state: ledger.DustLocalState; - collapsed: boolean; - rangesCollapsed: number; - reason?: string; -} -export declare function computeForeignRanges(ownedIndices: Iterable, frontier: bigint): Array<[ - bigint, - bigint -]>; -export declare function collapseForeignGenerations(state: ledger.DustLocalState, ownedIndices: Iterable, frontier: bigint): CollapseOutcome; -``` - -## `@kuiralabs/midnight-engine-beta/dust-direct` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface DustRetention { - ownedGenerationIndices: number[]; - generationFrontier: number; -} -export interface DustDirectResult { - balance: bigint; - availableCoins: number; - eventCount: number; - ownedUtxoCount: number; - syncTime: Date; - state: ledger.DustLocalState; - retention: DustRetention; - lastAppliedEventId: number; - partial: boolean; -} -export interface DustDirectOptions { - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - timeoutMs?: number; - idleMs?: number; - initialSilenceMs?: number; - signal?: AbortSignal; - initialState?: ledger.DustLocalState; - startFromId?: number; - initialRetention?: DustRetention; - collapse?: boolean; -} -export declare function readDustBalanceDirect(dustSecretKey: ledger.DustSecretKey, indexerWS: string, options?: DustDirectOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/dust-direct-cache` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -import { type DustRetention } from "./dust-direct.ts"; -export interface DustCacheEntry { - state: ledger.DustLocalState; - lastAppliedEventId: number; - retention: DustRetention; -} -export declare function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string; -export declare function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadDustCache(network: string, pubkeyHex: string, root: string): DustCacheEntry | null; -export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, root: string, chainId?: string, retention?: DustRetention): void; -export declare function validateDustCacheChainId(network: string, currentChainId: string | null, root: string): string[]; -``` - -## `@kuiralabs/midnight-engine-beta/dust-export` - -```ts -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export interface DustExportOptions { - root: string; - notice: NoticeSink; - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - signal?: AbortSignal; - repository: WalletDataRepository; - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; - log?: VerboseLog; -} -export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options: DustExportOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/dust-register` - -```ts -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function registerDust(repo: WalletDataRepository, seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/dust-sync-native` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; -import type { Settings } from "@kuiralabs/midnight-cli-core/lib/settings"; -export interface SidecarCheckpoint { - dust_state: string; - last_applied_event_id: number; - owned_generation_indices: number[]; - generation_frontier: number; - balance: string; - available_coins: number; - events_applied: number; - partial: boolean; -} -interface NativeFetchOptions { - startFromId: number; - initialState?: ledger.DustLocalState; - initialRetention?: DustRetention; - signal?: AbortSignal; - onProgress?: (applied: number, max: number) => void; - root: string; - settings: Settings; -} -export declare function resolveSidecarBinary(settings: Pick): string | null; -export declare function platformPackageBinary(fromUrl: string): string | null; -export declare function nativeDustSyncAvailable(settings: Pick): boolean; -export declare function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): "existing" | "seed" | "fresh"; -export declare function runDustSyncNative(seed: Buffer, network: NetworkConfig, opts: NativeFetchOptions): Promise; -export declare function adaptResult(cp: SidecarCheckpoint, settings: Pick): DustDirectResult; -``` - -## `@kuiralabs/midnight-engine-beta/dust-wallet` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -import { DustWallet as SdkDustWallet } from "@midnightntwrk/wallet-sdk-dust-wallet"; -import { Transacting } from "@midnightntwrk/wallet-sdk-dust-wallet/v1"; -type SdkTransacting = Transacting.TransactingCapabilityImplementation; -type RecipeArguments = Parameters; -type Recipe = ReturnType; -export declare class ConvergingDustTransacting extends Transacting.TransactingCapabilityImplementation { - #private; - computeBalancingRecipe(...args: RecipeArguments): Recipe; -} -export declare function DustWallet(configuration: Parameters[0]): ReturnType; -``` - -## `@kuiralabs/midnight-engine-beta/facade` - -```ts -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import { type UnshieldedKeystore } from "@midnightntwrk/wallet-sdk-unshielded-wallet"; -import { WalletFacade, type FacadeState } from "@midnightntwrk/wallet-sdk-facade"; -import * as ledger from "@midnightntwrk/ledger-v9"; -import * as rx from "rxjs"; -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; -import { type DustCacheEntry } from "./dust-direct-cache.ts"; -import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; -export type SyncMode = "full" | "lite" | "no-dust"; -export interface WalletSecretKeys { - shieldedSecretKeys: ledger.ZswapSecretKeys; - dustSecretKey: ledger.DustSecretKey; -} -export interface FacadeBundle { - facade: WalletFacade; - keystore: UnshieldedKeystore; - secretKeys: WalletSecretKeys; - keepAlive?: rx.Subscription; - restoredFromCache?: boolean; - indexerHttpUrl?: string; - indexerWsUrl?: string; - emptyStreams?: EmptyStreams; -} -export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, cache?: WalletCacheData | null, log?: VerboseLog): Promise; -export interface FacadeDustSnapshot { - publicKey: { - publicKey: string; - }; - state: string; - protocolVersion: string; - networkId: string; - offset?: string; -} -export declare function overlayDustDirectSnapshot(dustSnapshotJson: string, direct: Pick): string; -export interface EmptyStreams { - readonly zswap: boolean; - readonly dust: boolean; -} -export declare const NO_EMPTY_STREAMS: EmptyStreams; -export declare function isFacadeSynced(state: FacadeState, syncMode?: SyncMode, empty?: EmptyStreams): boolean; -export interface SyncOptions { - onProgress?: (applied: number, highest: number) => void; - onSyncDetail?: (detail: string) => void; - timeoutMs?: number; - syncMode?: SyncMode; - requireStrictSync?: boolean; - log?: VerboseLog; - signal?: AbortSignal; -} -export declare function startAndSyncFacade(bundle: FacadeBundle, options?: SyncOptions): Promise; -export declare class StaleCacheError extends Error { - readonly code = "STALE_CACHE"; - constructor(detail: string); -} -export declare function detectStaleCache(state: FacadeState): string | undefined; -export declare function waitForLiteSyncedState(bundle: FacadeBundle): Promise; -export declare function hasDustAvailable(state: FacadeState): boolean; -export declare function waitForDustAvailable(bundle: FacadeBundle, timeoutMs?: number, signal?: AbortSignal): Promise; -export declare function quickSync(bundle: FacadeBundle, syncMode?: SyncMode): Promise; -export declare function stopFacade(bundle: FacadeBundle): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/fee-only-check` - -```ts -import { Transaction, type Bindingish, type Proofish, type SignatureEnabled, type SignatureVerifyingKey } from "@midnightntwrk/ledger-v9"; -export type DAppTxStage = "unsealed" | "sealed"; -export type FeeCheckTransaction = Transaction; -export declare function readDAppTransaction(bytes: Uint8Array, stage: DAppTxStage): FeeCheckTransaction; -export declare function segmentsOf(tx: FeeCheckTransaction): Set; -export declare function expiredIntents(tx: FeeCheckTransaction, now: Date): Array<{ - segment: number; - ttl: Date; -}>; -export interface UnshieldedInputRef { - where: string; - owner: SignatureVerifyingKey; - signed: boolean; -} -export declare function unshieldedInputs(tx: FeeCheckTransaction): UnshieldedInputRef[]; -export declare function feeOnlyRefusals(tx: FeeCheckTransaction, walletKey: SignatureVerifyingKey): string[]; -``` - -## `@kuiralabs/midnight-engine-beta/index` - -```ts -import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; -import { type RepoDeps } from "./wallet-data-repository.ts"; -export interface BetaEngineOptions { - readonly repository?: RepoDeps; -} -export declare function createBetaEngine(host: EngineHost, options?: BetaEngineOptions): Engine; -``` - -## `@kuiralabs/midnight-engine-beta/ledger-parameters` - -```ts -import type { BlockLimits } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function blockLimitsOf(parametersHex: string): BlockLimits; -``` - -## `@kuiralabs/midnight-engine-beta/offer-reader` - -```ts -import { type OfferContents } from "@kuiralabs/midnight-cli-core/lib/swap-offer"; -export declare function readOffer(txHex: string): OfferContents; -export declare function spentNullifiers(txHex: string): string[]; -``` - -## `@kuiralabs/midnight-engine-beta/raw-state` - -```ts -import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; -interface StateValueLike { - type(): "null" | "cell" | "map" | "array" | "boundedMerkleTree"; - asCell(): { - value: Uint8Array[]; - }; - asMap(): { - keys(): unknown[]; - } | undefined; - asArray(): StateValueLike[] | undefined; - asBoundedMerkleTree(): { - height: number; - root(): { - value: Uint8Array[]; - } | undefined; - } | undefined; -} -export declare function describeRawState(state: StateValueLike): RawStateValue; -``` - -## `@kuiralabs/midnight-engine-beta/shielded-direct` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface ShieldedDirectResult { - balance: bigint; - availableCoins: number; - tokens: ReadonlyMap; - eventCount: number; - state: ledger.ZswapLocalState; - lastAppliedEventId: number; - partial: boolean; -} -export interface ShieldedDirectOptions { - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - onCheckpoint?: (state: ledger.ZswapLocalState, lastAppliedEventId: number) => void; - timeoutMs?: number; - idleMs?: number; - initialSilenceMs?: number; - signal?: AbortSignal; - initialState?: ledger.ZswapLocalState; - startFromId?: number; -} -export declare function readShieldedBalanceDirect(secretKeys: ledger.ZswapSecretKeys, indexerWS: string, options?: ShieldedDirectOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/shielded-direct-cache` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface ShieldedCacheEntry { - state: ledger.ZswapLocalState; - lastAppliedEventId: number; -} -export declare function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadShieldedCache(network: string, pubkeyHex: string, root: string, expectedChainId?: string): ShieldedCacheEntry | null; -export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, root: string, chainId?: string): void; -export type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options: ShieldedCachedOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/sign-recipe` - -```ts -import type { Signature } from "@midnightntwrk/ledger-v9"; -import type { BalancingRecipe, WalletFacade } from "@midnightntwrk/wallet-sdk-facade"; -import { type FeeCheckTransaction } from "./fee-only-check.ts"; -export type SignSegment = (data: Uint8Array) => Promise; -export type UnshieldedSignatures = "none" | "all" | "some"; -export declare function unshieldedSignatures(tx: FeeCheckTransaction): UnshieldedSignatures; -export declare class PartlySignedTransactionError extends Error { - constructor(); -} -export declare class SignedTransactionNeedsUnshieldedError extends Error { - constructor(segments: number[]); -} -export declare function unshieldedImbalanceSegments(tx: FeeCheckTransaction): number[]; -export declare function assertSignable(tx: FeeCheckTransaction, balancesUnshielded: boolean): void; -export declare function signRecipe(facade: WalletFacade, recipe: BalancingRecipe, signSegment: SignSegment): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/transfer` - -```ts -import { UnshieldedAddress, type DustAddress } from "@midnightntwrk/wallet-sdk-address-format"; -import { type FacadeState, type UtxoWithMeta } from "@midnightntwrk/wallet-sdk-facade"; -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type FacadeBundle } from "./facade.ts"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -export declare function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress; -export { isDustRelatedError, isSdkInsufficientFundsError } from "@kuiralabs/midnight-cli-core/lib/sdk-errors"; -import type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function registerNightUtxos(bundle: FacadeBundle, nightUtxos: readonly UtxoWithMeta[], dustReceiverAddress: DustAddress, onStatus?: (status: string) => void): Promise; -export declare function ensureDust(bundle: FacadeBundle, onStatus?: (status: string) => void, syncedState?: FacadeState): Promise; -export declare function executeTransfer(repo: WalletDataRepository, params: TransferParams): Promise; -``` - -## `@kuiralabs/midnight-engine-beta/tx-inspect` - -```ts -import type { TransactionDetail } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function inspectTxHex(txHex: string, stage: "unsealed" | "sealed"): TransactionDetail[]; -``` - -## `@kuiralabs/midnight-engine-beta/wallet` - -```ts -import type { EngineWallet } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -export declare function createBetaWallet(repo: WalletDataRepository): EngineWallet; -``` - -## `@kuiralabs/midnight-engine-beta/wallet-data-repository` - -```ts -import { Buffer } from "node:buffer"; -import * as ledger from "@midnightntwrk/ledger-v9"; -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import type { NetworkConfig, NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type FacadeState } from "@midnightntwrk/wallet-sdk-facade"; -import { type FacadeBundle, type SyncMode } from "./facade.ts"; -import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; -import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subscription"; -import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; -import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; -import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; -import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; -export interface DustView extends DustBalance { - state: ledger.DustLocalState; -} -export interface FacadeLease { - bundle: FacadeBundle; - state: FacadeState; -} -export interface InvalidationScope { - network: NetworkConfig; - root: string; - seed?: Buffer; - address?: string; - kinds?: ReadonlyArray<"dust" | "unshielded" | "facade">; -} -export interface FacadeOptions extends CachedReadOptions { - syncMode?: SyncMode; - requireStrictSync?: boolean; - readOnly?: boolean; - skipAutoSave?: boolean; - syncTimeoutMs?: number; - onSyncProgress?: (applied: number, highest: number) => void; - onSyncDetail?: (detail: string) => void; - onSyncWarning?: (tag: string, message: string) => void; - noPrime?: boolean; -} -export type TipFingerprint = string; -export interface RepoDeps { - now?: () => number; - fetchTip?: (network: NetworkConfig, signal?: AbortSignal) => Promise; - fetchUnshielded?: (address: string, network: NetworkConfig, onProgress?: (current: number, highest: number) => void, signal?: AbortSignal) => Promise; - fetchDust?: (seed: Buffer, network: NetworkConfig, opts: { - startFromId: number; - initialState?: ledger.DustLocalState; - initialRetention?: DustRetention; - signal?: AbortSignal; - onProgress?: (applied: number, max: number) => void; - onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - root: string; - log?: VerboseLog; - }) => Promise; - fetchChainId?: (nodeWsUrl: string) => Promise; - fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; - fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; -} -export declare class WalletDataRepository { - private readonly now; - private readonly fetchTip; - private readonly fetchUnshielded; - private readonly fetchDust; - private readonly fetchChainId; - private readonly fetchEventTip; - private readonly fetchProtocolVersion; - private readonly dustMemo; - private readonly unshieldedMemo; - private readonly tipMemo; - constructor(host: EngineHost, deps?: RepoDeps); - private keepCachesOfThisIndexer; - walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise; - private freshWalletOnDustCheckpoint; - dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise; - unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; - withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts: FacadeOptions): Promise; - invalidate(scope: InvalidationScope): void; - resetTipMemo(): void; - private tryMemo; - private memoize; - private getTip; - private deleteByPrefix; -} -``` diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index 17bc8238..44db09fd 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -21,11 +21,6 @@ "midnight-cli-source": "./src/index.ts", "types": "./dist/index.d.ts", "default": "./dist/index.js" - }, - "./*": { - "midnight-cli-source": "./src/*.ts", - "types": "./dist/*.d.ts", - "default": "./dist/*.js" } }, "files": [ diff --git a/src/__tests__/engine-beta-dapp-connector.test.ts b/packages/engine-beta/src/__tests__/dapp-connector.test.ts similarity index 82% rename from src/__tests__/engine-beta-dapp-connector.test.ts rename to packages/engine-beta/src/__tests__/dapp-connector.test.ts index 3ee79f42..bb1ce838 100644 --- a/src/__tests__/engine-beta-dapp-connector.test.ts +++ b/packages/engine-beta/src/__tests__/dapp-connector.test.ts @@ -5,13 +5,13 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; -import { createDAppConnector, signatureScheme, toHistoryEntry } from '@kuiralabs/midnight-engine-beta/dapp-connector'; -import { PartlySignedTransactionError } from '@kuiralabs/midnight-engine-beta/sign-recipe'; -import { deriveAllShieldedAddresses, deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-beta/derive-address'; -import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; -import { connectorSuite } from './helpers/connector-suite.ts'; +import { createDAppConnector, signatureScheme, toHistoryEntry } from '../dapp-connector.ts'; +import { PartlySignedTransactionError } from '../sign-recipe.ts'; +import { deriveAllShieldedAddresses, deriveShieldedAddress, deriveUnshieldedAddress } from '../derive-address.ts'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { connectorSuite } from '../../../../test-support/connector-suite.ts'; -const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +const ENGINE_DIR = new URL('../..', import.meta.url).pathname; /** A module of a package as the beta engine resolves it. */ const fromEngine = async (name: string, entry: string) => import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, name)!, entry)).href); diff --git a/src/__tests__/engine-beta.test.ts b/packages/engine-beta/src/__tests__/engine.test.ts similarity index 87% rename from src/__tests__/engine-beta.test.ts rename to packages/engine-beta/src/__tests__/engine.test.ts index ea22b153..6573d3d4 100644 --- a/src/__tests__/engine-beta.test.ts +++ b/packages/engine-beta/src/__tests__/engine.test.ts @@ -5,21 +5,19 @@ import { describe, it, expect, vi } from 'vitest'; import * as rx from 'rxjs'; -import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { createDAppConnector } from '@kuiralabs/midnight-engine-beta/dapp-connector'; -import type { FacadeBundle } from '@kuiralabs/midnight-engine-beta/facade'; -import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-beta/derive-address'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { NO_TERMINAL } from './helpers/connector-stub.ts'; +import { createBetaEngine } from '../index.ts'; +import { createHost, type NetworkConfig, type RpcHandlerContext } from '@kuiralabs/midnight-cli-core'; +import { createDAppConnector } from '../dapp-connector.ts'; +import type { FacadeBundle } from '../facade.ts'; +import { deriveShieldedAddress } from '../derive-address.ts'; +import { NO_TERMINAL } from '../../../../test-support/connector-stub.ts'; // A beta engine, for what every host's has alike: its keys, ledger and contracts. const betaEngine = createBetaEngine(createHost()); // The beta set's own address classes, as the engine resolves them: the // repository's root holds the rc set's. -const { DustAddress, UnshieldedAddress } = await import(new URL('../../packages/engine-beta/node_modules/@midnightntwrk/wallet-sdk-address-format/dist/index.js', import.meta.url).href) as typeof import('@midnightntwrk/wallet-sdk-address-format'); +const { DustAddress, UnshieldedAddress } = await import(new URL('../../node_modules/@midnightntwrk/wallet-sdk-address-format/dist/index.js', import.meta.url).href) as typeof import('@midnightntwrk/wallet-sdk-address-format'); const STAGENET: NetworkConfig = { indexer: 'http://localhost:8088/api/v4/graphql', diff --git a/src/__tests__/engine-beta-host.test.ts b/packages/engine-beta/src/__tests__/host.test.ts similarity index 87% rename from src/__tests__/engine-beta-host.test.ts rename to packages/engine-beta/src/__tests__/host.test.ts index f9a86511..97d0bd8c 100644 --- a/src/__tests__/engine-beta-host.test.ts +++ b/packages/engine-beta/src/__tests__/host.test.ts @@ -7,12 +7,10 @@ import { afterAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { OtherSdkSetError, type SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; -import type { RepoDeps } from '@kuiralabs/midnight-engine-beta/wallet-data-repository'; -import { startRefusingEndpoint } from './helpers/stand-in-indexer.ts'; +import { OtherSdkSetError, type SdkSet, createHost, type Host, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import { createBetaEngine } from '../index.ts'; +import type { RepoDeps } from '../wallet-data-repository.ts'; +import { startRefusingEndpoint } from '../../../../test-support/stand-in-indexer.ts'; // A state root with no config: stagenet runs the beta set, the rest the rc set. const ROOT = mkdtempSync(join(tmpdir(), 'mn-engine-beta-host-')); diff --git a/src/__tests__/engine-beta-offer-reader.test.ts b/packages/engine-beta/src/__tests__/offer-reader.test.ts similarity index 66% rename from src/__tests__/engine-beta-offer-reader.test.ts rename to packages/engine-beta/src/__tests__/offer-reader.test.ts index 0b465e8d..313378a8 100644 --- a/src/__tests__/engine-beta-offer-reader.test.ts +++ b/packages/engine-beta/src/__tests__/offer-reader.test.ts @@ -3,11 +3,11 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; -import { readOffer, spentNullifiers } from '@kuiralabs/midnight-engine-beta/offer-reader'; -import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; -import { offerReaderSuite } from './helpers/offer-reader-suite.ts'; +import { readOffer, spentNullifiers } from '../offer-reader.ts'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { offerReaderSuite } from '../../../../test-support/offer-reader-suite.ts'; -const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +const ENGINE_DIR = new URL('../..', import.meta.url).pathname; const ledger = await import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, '@midnightntwrk/ledger-v9')!, 'midnight_ledger_wasm_v9_fs.js')).href); offerReaderSuite({ set: 'beta', ledger, readOffer, spentNullifiers }); diff --git a/src/__tests__/engine-beta-shielded-direct.test.ts b/packages/engine-beta/src/__tests__/shielded-direct.test.ts similarity index 66% rename from src/__tests__/engine-beta-shielded-direct.test.ts rename to packages/engine-beta/src/__tests__/shielded-direct.test.ts index 304c66a6..cd68387a 100644 --- a/src/__tests__/engine-beta-shielded-direct.test.ts +++ b/packages/engine-beta/src/__tests__/shielded-direct.test.ts @@ -4,12 +4,12 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; -import { readShieldedBalanceDirect } from '@kuiralabs/midnight-engine-beta/shielded-direct'; -import { deriveShieldedSeed } from '@kuiralabs/midnight-engine-beta/derivation'; -import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; -import { shieldedDirectSuite } from './helpers/shielded-direct-suite.ts'; +import { readShieldedBalanceDirect } from '../shielded-direct.ts'; +import { deriveShieldedSeed } from '../derivation.ts'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { shieldedDirectSuite } from '../../../../test-support/shielded-direct-suite.ts'; -const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; +const ENGINE_DIR = new URL('../..', import.meta.url).pathname; const ledger = await import(pathToFileURL(join(resolvedPackageFolder(ENGINE_DIR, '@midnightntwrk/ledger-v9')!, 'midnight_ledger_wasm_v9_fs.js')).href); shieldedDirectSuite({ diff --git a/packages/engine-beta/src/__tests__/stale-cache.test.ts b/packages/engine-beta/src/__tests__/stale-cache.test.ts new file mode 100644 index 00000000..b012b237 --- /dev/null +++ b/packages/engine-beta/src/__tests__/stale-cache.test.ts @@ -0,0 +1,15 @@ +// The beta engine's stale-cache error, as the rc engine's stale-cache.test.ts +// checks the rc engine's: in a file of its own, since one process loads one SDK set. +// Approved (Y52): an escaped stale cache reports STALE_CACHE, where it was UNKNOWN. + +import { describe, expect, it } from 'vitest'; +import { classifyError } from '@kuiralabs/midnight-cli-core'; +import { StaleCacheError } from '../facade.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; + +describe("the beta engine's stale cache", () => { + it('reports STALE_CACHE (exit 6) through its code, where the message alone gave UNKNOWN', () => { + const err = new StaleCacheError('applied 120 of 80 events'); + expect(classifyError(err, CORE_CODES)).toStrictEqual({ exitCode: 6, errorCode: 'STALE_CACHE' }); + }); +}); diff --git a/packages/engine-beta/src/addresses.ts b/packages/engine-beta/src/addresses.ts index 7a714567..c57b7da2 100644 --- a/packages/engine-beta/src/addresses.ts +++ b/packages/engine-beta/src/addresses.ts @@ -2,8 +2,8 @@ // must be on. import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk-address-format'; -import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/engine'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core'; /** A shielded address on `network`, as the SDK reads it. Throws when it is not one. */ export function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress { diff --git a/packages/engine-beta/src/airdrop.ts b/packages/engine-beta/src/airdrop.ts index e8944c0d..c2be1f0a 100644 --- a/packages/engine-beta/src/airdrop.ts +++ b/packages/engine-beta/src/airdrop.ts @@ -2,13 +2,11 @@ // devnet. `mn airdrop` and `mn dev` both fund wallets through here; the // caller has already checked that the network is the local one. -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { EngineError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { EngineError, toEngineError, type AirdropParams } from '@kuiralabs/midnight-cli-core/engine'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; -import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { AirdropParams } from '@kuiralabs/midnight-cli-core/engine'; /** Sends `amount` micro-NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ diff --git a/packages/engine-beta/src/contract-providers.ts b/packages/engine-beta/src/contract-providers.ts index dd94b435..32c32d60 100644 --- a/packages/engine-beta/src/contract-providers.ts +++ b/packages/engine-beta/src/contract-providers.ts @@ -2,9 +2,8 @@ // Deploy/call use the runner (generated scripts in dApp context) which build their own providers. import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; -import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/engine'; +import { assertEndpointUsable, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; import { describeRawState } from './raw-state.ts'; /** diff --git a/packages/engine-beta/src/contract-scripts.ts b/packages/engine-beta/src/contract-scripts.ts index 7fbd2dac..c91b6985 100644 --- a/packages/engine-beta/src/contract-scripts.ts +++ b/packages/engine-beta/src/contract-scripts.ts @@ -8,8 +8,8 @@ import { existsSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; -import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; /** * Every package a generated script imports, and the compact runtime the diff --git a/packages/engine-beta/src/dapp-connector.ts b/packages/engine-beta/src/dapp-connector.ts index f7ed46b2..f102a620 100644 --- a/packages/engine-beta/src/dapp-connector.ts +++ b/packages/engine-beta/src/dapp-connector.ts @@ -2,38 +2,21 @@ // Factory function returns a handler map for ws-rpc.ts to dispatch import * as rx from 'rxjs'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { type ApprovalOptions, promptApproval, createPhaseTracker, type PhaseTracker, toHex, fromHex, getNetworkId, isDustShortage, markingEngineCodes, ProofTimeoutError, DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits, assertSpendsNoOfferCoin, NotAnOfferError, describeLeg, decodeSignPayload, signedMessageBytes, DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan, TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS, type DAppConnector, type DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/engine'; +import { type NoticeSink, type NetworkConfig, createApiError, type RpcHandler, type RpcHandlerContext, type OpenOffer, formatWait, OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core'; +import { dim, roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui'; import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk-address-format'; import * as ledger from '@midnightntwrk/ledger-v9'; import type { UnboundTransaction } from '@midnightntwrk/wallet-sdk-capabilities/proving'; import type { FacadeState, WalletEntry } from '@midnightntwrk/wallet-sdk-facade'; import { type FacadeBundle, hasDustAvailable } from './facade.ts'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { createApiError, type RpcHandler, type RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { createPhaseTracker, type PhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; -import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import { isDustShortage, markingEngineCodes } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { ProofTimeoutError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; import { readOffer, spentNullifiers } from './offer-reader.ts'; -import { assertSpendsNoOfferCoin, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import { NotAnOfferError, describeLeg } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; -import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; -import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; -import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { fetchPartialSuccessSegments, type SegmentResult } from '@kuiralabs/midnight-chain/lib/tx-segments'; -import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { fetchPartialSuccessSegments, type SegmentResult } from '@kuiralabs/midnight-chain'; +export type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/engine'; // ── Types ── @@ -153,8 +136,7 @@ function extractErrorDetail(err: unknown): string { return deduped.join(' → ') || 'Unknown error'; } -export { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +export { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core'; /** The connector API's history entry for one wallet history entry. */ export type HistoryEntry = { diff --git a/packages/engine-beta/src/derive-address.ts b/packages/engine-beta/src/derive-address.ts index 08fead2a..791ff05f 100644 --- a/packages/engine-beta/src/derive-address.ts +++ b/packages/engine-beta/src/derive-address.ts @@ -10,9 +10,9 @@ import { ShieldedEncryptionPublicKey, } from '@midnightntwrk/wallet-sdk-address-format'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { type NetworkName, getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/engine'; +import { type NetworkName, getValidNetworkNames } from '@kuiralabs/midnight-cli-core'; import { deriveShieldedSeed } from './derivation.ts'; -import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; /** * Derive an unshielded address from a seed buffer, network, and optional key index. diff --git a/packages/engine-beta/src/dust-direct-cache.ts b/packages/engine-beta/src/dust-direct-cache.ts index 7bda17bb..1f07d0c2 100644 --- a/packages/engine-beta/src/dust-direct-cache.ts +++ b/packages/engine-beta/src/dust-direct-cache.ts @@ -14,10 +14,10 @@ import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { dustCacheDir, getDustCachePath } from '@kuiralabs/midnight-cli-core/engine'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core'; import { deriveDustSeed } from './derivation.ts'; import { type DustRetention } from './dust-direct.ts'; -import { dustCacheDir, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; // v2 added the retention fields (owned generation indices + frontier) that the // generation-tree collapse needs. v1 caches lack them and are invalidated, so diff --git a/packages/engine-beta/src/dust-direct.ts b/packages/engine-beta/src/dust-direct.ts index 3d901581..d5d90df7 100644 --- a/packages/engine-beta/src/dust-direct.ts +++ b/packages/engine-beta/src/dust-direct.ts @@ -12,12 +12,8 @@ import WebSocket from 'ws'; import * as ledger from '@midnightntwrk/ledger-v9'; import { collapseForeignGenerations } from './dust-collapse.ts'; -import { - INITIAL_NIGHT_DUST_RATIO, - INITIAL_GENERATION_DECAY_RATE, - INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from '@kuiralabs/midnight-cli-core/lib/constants'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { INITIAL_NIGHT_DUST_RATIO, INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS } from '@kuiralabs/midnight-cli-core/engine'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain'; // MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): the repository then passes `collapse: false`, read from its host's settings. diff --git a/packages/engine-beta/src/dust-export.ts b/packages/engine-beta/src/dust-export.ts index 8524107e..8aeee77b 100644 --- a/packages/engine-beta/src/dust-export.ts +++ b/packages/engine-beta/src/dust-export.ts @@ -19,12 +19,10 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { DustExportResult } from '@kuiralabs/midnight-cli-core/engine'; +import type { NetworkConfig, VerboseLog, NoticeSink } from '@kuiralabs/midnight-cli-core'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; -import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustExportResult } from '@kuiralabs/midnight-cli-core/engine'; export interface DustExportOptions { diff --git a/packages/engine-beta/src/dust-register.ts b/packages/engine-beta/src/dust-register.ts index ce6cc699..4ed0c03f 100644 --- a/packages/engine-beta/src/dust-register.ts +++ b/packages/engine-beta/src/dust-register.ts @@ -2,14 +2,11 @@ // Dust to spend. `mn dust register` and `mn dev` both register through here. import { waitForLiteSyncedState } from './facade.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/engine'; +import { throwIfCancelled, type NetworkConfig, type CallSdkWarnings, type VerboseLog } from '@kuiralabs/midnight-cli-core'; import { ensureDust } from './transfer.ts'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/engine'; /** Registers a seed's NIGHT for Dust on the engine's repository `repo`, unless it has Dust already. */ diff --git a/packages/engine-beta/src/dust-sync-native.ts b/packages/engine-beta/src/dust-sync-native.ts index 8434bf70..04c70e76 100644 --- a/packages/engine-beta/src/dust-sync-native.ts +++ b/packages/engine-beta/src/dust-sync-native.ts @@ -4,7 +4,8 @@ // fails, callers fall back to the WASM path — the sidecar is an optional // accelerator, never a hard dependency. -import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { cacheRootDir, networkCacheFolder, nativeCheckpointName } from '@kuiralabs/midnight-cli-core/engine'; +import { assertEndpointUsable, DIR_MODE, FILE_MODE, type NetworkConfig, type Settings } from '@kuiralabs/midnight-cli-core'; import { spawn } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; @@ -13,15 +14,10 @@ import { fileURLToPath } from 'node:url'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveDustSeed } from './derivation.ts'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import type { Settings } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { cacheRootDir, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; /** Sidecar checkpoint JSON shape (snake_case — matches the Rust `Checkpoint`). */ export interface SidecarCheckpoint { diff --git a/packages/engine-beta/src/dust-wallet.ts b/packages/engine-beta/src/dust-wallet.ts index 601495f1..7ecea7d5 100644 --- a/packages/engine-beta/src/dust-wallet.ts +++ b/packages/engine-beta/src/dust-wallet.ts @@ -12,8 +12,7 @@ import { Imbalances, InsufficientFundsError as NoCoinsCoverIt, getBalanceRecipe import { CustomDustWallet, DustWallet as SdkDustWallet } from '@midnightntwrk/wallet-sdk-dust-wallet'; import { Transacting, V1Builder, WalletError } from '@midnightntwrk/wallet-sdk-dust-wallet/v1'; import { LedgerOps } from '@midnightntwrk/wallet-sdk-utilities'; -import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '@kuiralabs/midnight-cli-core/lib/dust-balancing-plan'; -import { type DustShortfall, withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs, type DustShortfall, withDustShortfall } from '@kuiralabs/midnight-cli-core/engine'; type SdkTransacting = Transacting.TransactingCapabilityImplementation; type RecipeArguments = Parameters; diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts index ab23a73d..e2ec3936 100644 --- a/packages/engine-beta/src/facade.ts +++ b/packages/engine-beta/src/facade.ts @@ -1,5 +1,6 @@ import { ShieldedWallet } from '@midnightntwrk/wallet-sdk-shielded'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { getNetworkId, type WalletCacheData, DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, SYNC_TIMEOUT_MS, PRE_SEND_SYNC_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/engine'; +import { type NoticeSink, type NetworkConfig, type VerboseLog, CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { UnshieldedWallet, createKeystore, @@ -17,21 +18,9 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk-abstractions'; import * as rx from 'rxjs'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; -import { type WalletCacheData } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; -import { - DUST_COST_OVERHEAD, - DUST_FEE_BLOCKS_MARGIN, - SYNC_TIMEOUT_MS, - PRE_SEND_SYNC_TIMEOUT_MS, -} from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; -import { isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; -import { CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { assertNetworkAnswers, isStreamEmpty } from '@kuiralabs/midnight-chain'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts index 63dc0d5d..7c57b8f9 100644 --- a/packages/engine-beta/src/index.ts +++ b/packages/engine-beta/src/index.ts @@ -5,8 +5,7 @@ import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { type Engine, type EngineHost, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/engine'; import * as ledger from '@midnightntwrk/ledger-v9'; import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; diff --git a/packages/engine-beta/src/ledger-parameters.ts b/packages/engine-beta/src/ledger-parameters.ts index decf682d..17a645a1 100644 --- a/packages/engine-beta/src/ledger-parameters.ts +++ b/packages/engine-beta/src/ledger-parameters.ts @@ -3,7 +3,7 @@ // normalizeFullness: normalized = value / limit, so limit = value / normalized. import * as ledger from '@midnightntwrk/ledger-v9'; -import type { BlockLimits } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { BlockLimits } from '@kuiralabs/midnight-cli-core/engine'; type Dimension = keyof BlockLimits; diff --git a/packages/engine-beta/src/offer-reader.ts b/packages/engine-beta/src/offer-reader.ts index a0baa7d2..00b94fc3 100644 --- a/packages/engine-beta/src/offer-reader.ts +++ b/packages/engine-beta/src/offer-reader.ts @@ -6,7 +6,8 @@ import { createHash } from 'node:crypto'; import { Transaction } from '@midnightntwrk/ledger-v9'; -import { NotAnOfferError, type OfferContents } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/engine'; +import type { OfferContents } from '@kuiralabs/midnight-cli-core'; export function readOffer(txHex: string): OfferContents { if (!/^(?:[0-9a-fA-F]{2})+$/.test(txHex)) throw new NotAnOfferError('it is not hex'); diff --git a/packages/engine-beta/src/raw-state.ts b/packages/engine-beta/src/raw-state.ts index 93b18a95..b7400982 100644 --- a/packages/engine-beta/src/raw-state.ts +++ b/packages/engine-beta/src/raw-state.ts @@ -3,7 +3,7 @@ // layout the fields have no names, so cells show their field-aligned bytes in // hex and maps show their size, as the parsed state does. -import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/engine'; const toHex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); diff --git a/packages/engine-beta/src/shielded-direct-cache.ts b/packages/engine-beta/src/shielded-direct-cache.ts index 40f4c6f4..dc15d11b 100644 --- a/packages/engine-beta/src/shielded-direct-cache.ts +++ b/packages/engine-beta/src/shielded-direct-cache.ts @@ -9,18 +9,17 @@ // Security: the cached state contains owned coins but NOT the secret keys. Same // sensitivity as the wallet file (mode 0o600). -import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { bindCachesToIndexer, getShieldedCachePath, type ShieldedBalanceResult, type ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/engine'; +import { DIR_MODE, FILE_MODE, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core'; import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveShieldedSeed } from './derivation.ts'; import { readShieldedBalanceDirect, type ShieldedDirectOptions } from './shielded-direct.ts'; -import { fetchEventTip, isCursorBeyondTip } from '@kuiralabs/midnight-chain/lib/event-tip'; -import { clearShieldedDirectCache, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { fetchEventTip, isCursorBeyondTip } from '@kuiralabs/midnight-chain'; // v2: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis // hash, so the chain-id guard can't keep a ledger-8 cache off a ledger-9 chain. @@ -123,8 +122,7 @@ export function saveShieldedCache( } -export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/engine'; /** * Read a wallet seed's shielded balances, using (and refreshing) the diff --git a/packages/engine-beta/src/shielded-direct.ts b/packages/engine-beta/src/shielded-direct.ts index 7dd56013..bde47bf3 100644 --- a/packages/engine-beta/src/shielded-direct.ts +++ b/packages/engine-beta/src/shielded-direct.ts @@ -14,7 +14,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain'; const SUBSCRIPTION_QUERY = ` subscription ZswapLedgerEvents($id: Int) { diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index dd097580..7c1a24d1 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -2,31 +2,15 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { ProofTimeoutError, getNetworkId, TOKEN_MULTIPLIER, TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_TIMEOUT_MS, MAX_RETRY_ATTEMPTS, STALE_UTXO_ERROR_CODE, DUST_REGISTRATION_TIMEOUT_MS, DUST_REGISTRATION_RETRY_DELAY_MS, SYNC_ATTEMPT_TIMEOUT_MS, DUST_COST_OVERHEAD, MIN_DUST_FOR_TRANSFER, isColdStartRace, isDustRelatedError, DustFeeNotGeneratedError, planRegistration, awaitDustForFee, sleep, type EnsureDustResult, type TransferParams, type TransferResult } from '@kuiralabs/midnight-cli-core/engine'; +import { DustRequiredError, InsufficientBalanceError, SyncTimeoutError, throwIfCancelled, type NetworkConfig, type VerboseLog, nightAmountText, NATIVE_TOKEN_TYPE, formatWait, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; +import { toDust } from '@kuiralabs/midnight-cli-core/ui'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk-address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk-facade'; import * as rx from 'rxjs'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; -import { - NATIVE_TOKEN_TYPE, - TOKEN_MULTIPLIER, - TX_TTL_MINUTES, - PROOF_TIMEOUT_MS, - DUST_TIMEOUT_MS, - MAX_RETRY_ATTEMPTS, - STALE_UTXO_ERROR_CODE, - DUST_REGISTRATION_TIMEOUT_MS, - DUST_REGISTRATION_RETRY_DELAY_MS, - SYNC_ATTEMPT_TIMEOUT_MS, - DUST_COST_OVERHEAD, - MIN_DUST_FOR_TRANSFER, -} from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -53,19 +37,12 @@ export function validateRecipientAddress(address: string, networkConfig: Network // SDK error classifiers moved to ./sdk-errors.ts so wallet-data-repository // can import them without a circular dependency. Re-exported for callers // that still import from this module. -export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { isColdStartRace, isDustRelatedError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; -import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; -import { awaitDustForFee, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midnight-cli-core/engine'; +import { assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain'; /** How long the transfer retry waits for Dust to grow when the fee is above the pre-flight threshold. */ const DUST_GROW_WAIT_MS = 10_000; -import { toDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/engine'; /** Format milliseconds as "Xs" or "Xm Ys" for human-friendly elapsed display. */ diff --git a/packages/engine-beta/src/tx-inspect.ts b/packages/engine-beta/src/tx-inspect.ts index 9f0c302d..2a740574 100644 --- a/packages/engine-beta/src/tx-inspect.ts +++ b/packages/engine-beta/src/tx-inspect.ts @@ -2,7 +2,7 @@ // Used by the DApp Connector approval prompt to show Lace-style transaction summaries import { Transaction } from '@midnightntwrk/ledger-v9'; -import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/engine'; /** * Try to extract structured details from a transaction hex string. diff --git a/packages/engine-beta/src/wallet-data-repository.ts b/packages/engine-beta/src/wallet-data-repository.ts index 489f1119..7a758da0 100644 --- a/packages/engine-beta/src/wallet-data-repository.ts +++ b/packages/engine-beta/src/wallet-data-repository.ts @@ -18,12 +18,10 @@ // tests against localnet — accepted scope per architecture-deepening.md. import { Buffer } from 'node:buffer'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { isColdStartRace, loadWalletCache, saveWalletCache, clearWalletCache, validateWalletCacheChainId, type WalletCacheData, bindCachesToIndexer, describeIndexerChange, type CachedReadOptions, type DustBalance, type EngineHost, type ReadOptions, type UnshieldedView } from '@kuiralabs/midnight-cli-core/engine'; +import { throwIfCancelled, type NoticeSink, type NetworkConfig, type NetworkName, isValidNetworkName, clearDustDirectCache, type VerboseLog } from '@kuiralabs/midnight-cli-core'; import * as ledger from '@midnightntwrk/ledger-v9'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; -import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { isValidNetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { type FacadeState } from '@midnightntwrk/wallet-sdk-facade'; import { buildFacade, @@ -34,29 +32,13 @@ import { type SyncMode, overlayDustDirectSnapshot, } from './facade.ts'; -import { isColdStartRace } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from './dust-direct-cache.ts'; -import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { - loadWalletCache, - saveWalletCache, - clearWalletCache, - validateWalletCacheChainId, - type WalletCacheData, -} from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; -import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { checkBalance, type BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { getChainGenesisHash, assertLedgerSupported, fetchProtocolVersion, checkBalance, type BalanceSummary, callNodeRpc, fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain'; import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; -import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; import { deriveDustSeed } from './derivation.ts'; import { deriveUnshieldedAddress } from './derive-address.ts'; -import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain/lib/event-tip'; -import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/engine'; // ── Public types ────────────────────────────────────────── diff --git a/packages/engine-beta/src/wallet.ts b/packages/engine-beta/src/wallet.ts index 8a282161..2d646a00 100644 --- a/packages/engine-beta/src/wallet.ts +++ b/packages/engine-beta/src/wallet.ts @@ -4,26 +4,13 @@ // themselves before the SDK moved behind the engine. import { deriveUnshieldedAddress } from './derive-address.ts'; -import { assertSpendsNoOfferCoin, readOpenOffers } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { assertSpendsNoOfferCoin, type DAppConnector, type EngineWallet, type OpenedConnector, type PrepWallet, type ServedWalletSession, type ShieldedTransferParams, reportingEngineErrors, getNetworkId, bindCachesToIndexer, describeIndexerChange, loadWalletCache, saveWalletCache, DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/engine'; +import { readOpenOffers, InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; +import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui'; import { spentNullifiers } from './offer-reader.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; import { MidnightBech32m } from '@midnightntwrk/wallet-sdk-address-format'; -import type { - DAppConnector, - EngineWallet, - OpenedConnector, - PrepWallet, - ServedWalletSession, - ShieldedTransferParams, -} from '@kuiralabs/midnight-cli-core/lib/engine'; -import { InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { reportingEngineErrors } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; -import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; -import { assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { assertLedgerSupported } from '@kuiralabs/midnight-chain'; import { decodeShieldedAddress } from './addresses.ts'; import { buildFacade, hasDustAvailable, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; import { ensureDust, executeTransfer } from './transfer.ts'; diff --git a/packages/engine-beta/tsconfig.build.json b/packages/engine-beta/tsconfig.build.json index 16f7d7d6..267c2417 100644 --- a/packages/engine-beta/tsconfig.build.json +++ b/packages/engine-beta/tsconfig.build.json @@ -24,5 +24,9 @@ }, "include": [ "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" ] } diff --git a/packages/engine-rc/api-report.md b/packages/engine-rc/api-report.md index 4906b483..f3b2ce94 100644 --- a/packages/engine-rc/api-report.md +++ b/packages/engine-rc/api-report.md @@ -1,609 +1,14 @@ # API report: @kuiralabs/midnight-engine-rc -Generated by `node scripts/api-report.mjs write` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand. +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. ## `@kuiralabs/midnight-engine-rc` ```ts -import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; +import { type Engine, type EngineHost } from "@kuiralabs/midnight-cli-core/engine"; import { type RepoDeps } from "./wallet-data-repository.ts"; export interface RcEngineOptions { readonly repository?: RepoDeps; } export declare function createRcEngine(host: EngineHost, options?: RcEngineOptions): Engine; ``` - -## `@kuiralabs/midnight-engine-rc/addresses` - -```ts -import { ShieldedAddress, UnshieldedAddress } from "@midnightntwrk/wallet-sdk/address-format"; -import type { NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress; -export declare function decodeUnshieldedAddress(address: string, network: NetworkName): UnshieldedAddress; -export declare function assertAddress(address: string, kind: "shielded" | "unshielded", network: NetworkName): void; -``` - -## `@kuiralabs/midnight-engine-rc/airdrop` - -```ts -import { type TransferResult } from "./transfer.ts"; -import type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -export type { AirdropParams } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function airdropNight(repo: WalletDataRepository, params: AirdropParams): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/contract-providers` - -```ts -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function buildStateProvider(networkConfig: NetworkConfig): import("@midnight-ntwrk/midnight-js-indexer-public-data-provider").IndexerPublicDataProvider; -export declare function rawContractState(networkConfig: NetworkConfig, address: string): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/contract-scripts` - -```ts -import type { CallScript, DeployScript, ScriptParts, StateScript } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare const SCRIPT_PACKAGES: readonly [ - "@midnight-ntwrk/compact-js", - "@midnight-ntwrk/compact-runtime", - "@midnight-ntwrk/midnight-js-contracts", - "@midnight-ntwrk/midnight-js-http-client-proof-provider", - "@midnight-ntwrk/midnight-js-indexer-public-data-provider", - "@midnight-ntwrk/midnight-js-level-private-state-provider", - "@midnight-ntwrk/midnight-js-network-id", - "@midnight-ntwrk/midnight-js-node-zk-config-provider", - "@midnight-ntwrk/midnight-js-types", - "@midnight-ntwrk/midnight-js-utils", - "ws" -]; -export declare function packageFolder(name: string): string | null; -export declare const PROVIDER_IMPORTS = "\nimport { createWalletProvider, createMidnightProvider, Transaction } from '@midnight-ntwrk/midnight-js-types';\nimport { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils';\nimport { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider';\nimport { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider';\nimport { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';\nimport { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';\n"; -export declare function walletProviderCode(): string; -export declare function providerSetupCode(networkConfig: NetworkConfig, privateStateKey: string, parts: ScriptParts): string; -export declare function generateDeployScript(opts: DeployScript, parts: ScriptParts): string; -export declare function generateCallScript(opts: CallScript, parts: ScriptParts): string; -export declare function generateStateScript(opts: StateScript, parts: ScriptParts): string; -``` - -## `@kuiralabs/midnight-engine-rc/dapp-connector` - -```ts -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import type { FacadeState, WalletEntry } from "@midnightntwrk/wallet-sdk/facade"; -import { type FacadeBundle } from "./facade.ts"; -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { ApprovalOptions } from "@kuiralabs/midnight-cli-core/lib/approval"; -import { type FeeLimits } from "@kuiralabs/midnight-cli-core/lib/fee-limits"; -import { type OpenOffer } from "@kuiralabs/midnight-cli-core/lib/open-offers"; -import { type SegmentResult } from "@kuiralabs/midnight-chain/lib/tx-segments"; -import type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DAppConnector, DAppConnectorCallbacks } from "@kuiralabs/midnight-cli-core/lib/engine"; -export interface DAppConnectorOptions { - bundle: FacadeBundle; - networkConfig: NetworkConfig; - approvalOptions: ApprovalOptions; - notice: NoticeSink; - feeLimits?: FeeLimits; - openOffers?: () => readonly OpenOffer[]; - callbacks?: DAppConnectorCallbacks; - initialState?: FacadeState; - isCurrent?: (state: FacadeState) => boolean; - dustWaitMs?: number; -} -export type TokenKindsToBalance = "all" | Array<"dust" | "shielded" | "unshielded">; -export { OPERATOR_REJECTED_MESSAGE } from "@kuiralabs/midnight-cli-core/lib/connector-api"; -export type HistoryEntry = { - txHash: string; - txStatus: { - status: "finalized"; - executionStatus: Record; - } | { - status: "pending"; - } | { - status: "discarded"; - }; -}; -export declare function toHistoryEntry(entry: WalletEntry, segments?: readonly SegmentResult[]): HistoryEntry; -export declare function signatureScheme(tag: string): "schnorr_bip340"; -export declare function createDAppConnector(options: DAppConnectorOptions): DAppConnector; -``` - -## `@kuiralabs/midnight-engine-rc/derivation` - -```ts -export declare function deriveShieldedSeed(seedBuffer: Buffer): Uint8Array; -export declare function deriveUnshieldedSeed(seedBuffer: Buffer): Uint8Array; -export declare function deriveDustSeed(seedBuffer: Buffer): Uint8Array; -``` - -## `@kuiralabs/midnight-engine-rc/derive-address` - -```ts -import { ShieldedAddress } from "@midnightntwrk/wallet-sdk/address-format"; -import { type NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -export declare function deriveUnshieldedAddress(seedBuffer: Buffer, networkName: NetworkName, keyIndex?: number): string; -export declare function deriveAllAddresses(seedBuffer: Buffer, keyIndex?: number): Record; -export declare function deriveAllShieldedAddresses(seedBuffer: Buffer): Record; -export declare function deriveShieldedAddressString(seedBuffer: Buffer, networkName: NetworkName): string; -export declare function deriveShieldedAddress(seedBuffer: Buffer): ShieldedAddress; -``` - -## `@kuiralabs/midnight-engine-rc/dust-collapse` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface CollapseOutcome { - state: ledger.DustLocalState; - collapsed: boolean; - rangesCollapsed: number; - reason?: string; -} -export declare function computeForeignRanges(ownedIndices: Iterable, frontier: bigint): Array<[ - bigint, - bigint -]>; -export declare function collapseForeignGenerations(state: ledger.DustLocalState, ownedIndices: Iterable, frontier: bigint): CollapseOutcome; -``` - -## `@kuiralabs/midnight-engine-rc/dust-direct` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface DustRetention { - ownedGenerationIndices: number[]; - generationFrontier: number; -} -export interface DustDirectResult { - balance: bigint; - availableCoins: number; - eventCount: number; - ownedUtxoCount: number; - syncTime: Date; - state: ledger.DustLocalState; - retention: DustRetention; - lastAppliedEventId: number; - partial: boolean; -} -export interface DustDirectOptions { - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - timeoutMs?: number; - idleMs?: number; - initialSilenceMs?: number; - signal?: AbortSignal; - initialState?: ledger.DustLocalState; - startFromId?: number; - initialRetention?: DustRetention; - collapse?: boolean; -} -export declare function readDustBalanceDirect(dustSecretKey: ledger.DustSecretKey, indexerWS: string, options?: DustDirectOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/dust-direct-cache` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -import { type DustRetention } from "./dust-direct.ts"; -export interface DustCacheEntry { - state: ledger.DustLocalState; - lastAppliedEventId: number; - retention: DustRetention; -} -export declare function dustPublicKeyHex(publicKey: ledger.DustPublicKey): string; -export declare function dustPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadDustCache(network: string, pubkeyHex: string, root: string): DustCacheEntry | null; -export declare function saveDustCache(network: string, pubkeyHex: string, state: ledger.DustLocalState, lastAppliedEventId: number, root: string, chainId?: string, retention?: DustRetention): void; -export declare function validateDustCacheChainId(network: string, currentChainId: string | null, root: string): string[]; -``` - -## `@kuiralabs/midnight-engine-rc/dust-export` - -```ts -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DustExportResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export interface DustExportOptions { - root: string; - notice: NoticeSink; - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - signal?: AbortSignal; - repository: WalletDataRepository; - buildBaseDust?: (seed: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, log?: VerboseLog) => Promise; - log?: VerboseLog; -} -export declare function exportDustSnapshot(seedBuffer: Buffer, network: string, networkConfig: NetworkConfig, options: DustExportOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/dust-register` - -```ts -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { DustRegisterOptions, DustRegistration } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function registerDust(repo: WalletDataRepository, seed: Buffer, networkConfig: NetworkConfig, options: DustRegisterOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/dust-sync-native` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -import type { NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; -import type { Settings } from "@kuiralabs/midnight-cli-core/lib/settings"; -export interface SidecarCheckpoint { - dust_state: string; - last_applied_event_id: number; - owned_generation_indices: number[]; - generation_frontier: number; - balance: string; - available_coins: number; - events_applied: number; - partial: boolean; -} -interface NativeFetchOptions { - startFromId: number; - initialState?: ledger.DustLocalState; - initialRetention?: DustRetention; - signal?: AbortSignal; - onProgress?: (applied: number, max: number) => void; - root: string; - settings: Settings; -} -export declare function resolveSidecarBinary(settings: Pick): string | null; -export declare function platformPackageBinary(fromUrl: string): string | null; -export declare function nativeDustSyncAvailable(settings: Pick): boolean; -export declare function resumeDecision(existingCursor: number, startFromId: number, hasInitialState: boolean): "existing" | "seed" | "fresh"; -export declare function runDustSyncNative(seed: Buffer, network: NetworkConfig, opts: NativeFetchOptions): Promise; -export declare function adaptResult(cp: SidecarCheckpoint, settings: Pick): DustDirectResult; -``` - -## `@kuiralabs/midnight-engine-rc/dust-wallet` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -import { DustWallet as SdkDustWallet } from "@midnightntwrk/wallet-sdk/dust"; -import { Transacting } from "@midnightntwrk/wallet-sdk/dust/v2"; -type SdkTransacting = Transacting.TransactingCapabilityImplementation; -type RecipeArguments = Parameters; -type Recipe = ReturnType; -export declare class ConvergingDustTransacting extends Transacting.TransactingCapabilityImplementation { - #private; - computeBalancingRecipe(...args: RecipeArguments): Recipe; -} -export declare function DustWallet(configuration: Parameters[0]): ReturnType; -``` - -## `@kuiralabs/midnight-engine-rc/facade` - -```ts -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import { type UnshieldedKeystore } from "@midnightntwrk/wallet-sdk/unshielded"; -import { WalletFacade, type FacadeState } from "@midnightntwrk/wallet-sdk/facade"; -import { type WalletSeeds } from "@midnightntwrk/wallet-sdk/hd"; -import * as rx from "rxjs"; -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; -import { type DustCacheEntry } from "./dust-direct-cache.ts"; -import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; -export type SyncMode = "full" | "lite" | "no-dust"; -interface SeedStartable { - startWithSeed(seed: Uint8Array): Promise; -} -export interface FacadeBundle { - facade: WalletFacade; - keystore: UnshieldedKeystore; - seeds: WalletSeeds; - seedStartable: { - shielded: SeedStartable; - dust: SeedStartable; - }; - keepAlive?: rx.Subscription; - restoredFromCache?: boolean; - indexerHttpUrl?: string; - indexerWsUrl?: string; - emptyStreams?: EmptyStreams; -} -export declare function buildFacade(seedBuffer: Buffer, networkConfig: NetworkConfig, root: string, notice: NoticeSink, cache?: WalletCacheData | null, log?: VerboseLog): Promise; -export interface FacadeDustSnapshot { - publicKey: { - publicKey: string; - }; - state: string; - protocolVersion: string; - networkId: string; - offset?: string; -} -export declare function overlayDustDirectSnapshot(dustSnapshotJson: string, direct: Pick): string; -export interface EmptyStreams { - readonly zswap: boolean; - readonly dust: boolean; -} -export declare const NO_EMPTY_STREAMS: EmptyStreams; -export declare function isFacadeSynced(state: FacadeState, syncMode?: SyncMode, empty?: EmptyStreams): boolean; -export interface SyncOptions { - onProgress?: (applied: number, highest: number) => void; - onSyncDetail?: (detail: string) => void; - timeoutMs?: number; - syncMode?: SyncMode; - requireStrictSync?: boolean; - log?: VerboseLog; - signal?: AbortSignal; -} -export declare function startAndSyncFacade(bundle: FacadeBundle, options?: SyncOptions): Promise; -export declare class StaleCacheError extends Error { - readonly code = "STALE_CACHE"; - constructor(detail: string); -} -export declare function detectStaleCache(state: FacadeState): string | undefined; -export declare function waitForLiteSyncedState(bundle: FacadeBundle): Promise; -export declare function hasDustAvailable(state: FacadeState): boolean; -export declare function waitForDustAvailable(bundle: FacadeBundle, timeoutMs?: number, signal?: AbortSignal): Promise; -export declare function quickSync(bundle: FacadeBundle, syncMode?: SyncMode): Promise; -export declare function stopFacade(bundle: FacadeBundle): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/fee-only-check` - -```ts -import { Transaction, type Bindingish, type Proofish, type SignatureEnabled, type SignatureVerifyingKey } from "@midnightntwrk/ledger-v9"; -export type DAppTxStage = "unsealed" | "sealed"; -export type FeeCheckTransaction = Transaction; -export declare function readDAppTransaction(bytes: Uint8Array, stage: DAppTxStage): FeeCheckTransaction; -export declare function segmentsOf(tx: FeeCheckTransaction): Set; -export declare function expiredIntents(tx: FeeCheckTransaction, now: Date): Array<{ - segment: number; - ttl: Date; -}>; -export interface UnshieldedInputRef { - where: string; - owner: SignatureVerifyingKey; - signed: boolean; -} -export declare function unshieldedInputs(tx: FeeCheckTransaction): UnshieldedInputRef[]; -export declare function feeOnlyRefusals(tx: FeeCheckTransaction, walletKey: SignatureVerifyingKey): string[]; -``` - -## `@kuiralabs/midnight-engine-rc/fork-schedule` - -```ts -import { ProtocolVersion } from "@midnightntwrk/wallet-sdk"; -export declare const FORK_SCHEDULE: ProtocolVersion.ForkSchedule; -``` - -## `@kuiralabs/midnight-engine-rc/index` - -```ts -import type { Engine, EngineHost } from "@kuiralabs/midnight-cli-core/lib/engine"; -import { type RepoDeps } from "./wallet-data-repository.ts"; -export interface RcEngineOptions { - readonly repository?: RepoDeps; -} -export declare function createRcEngine(host: EngineHost, options?: RcEngineOptions): Engine; -``` - -## `@kuiralabs/midnight-engine-rc/ledger-parameters` - -```ts -import type { BlockLimits } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function blockLimitsOf(parametersHex: string): BlockLimits; -``` - -## `@kuiralabs/midnight-engine-rc/offer-reader` - -```ts -import { type OfferContents } from "@kuiralabs/midnight-cli-core/lib/swap-offer"; -export declare function readOffer(txHex: string): OfferContents; -export declare function spentNullifiers(txHex: string): string[]; -``` - -## `@kuiralabs/midnight-engine-rc/raw-state` - -```ts -import type { RawStateValue } from "@kuiralabs/midnight-cli-core/lib/engine"; -interface StateValueLike { - type(): "null" | "cell" | "map" | "array" | "boundedMerkleTree"; - asCell(): { - value: Uint8Array[]; - }; - asMap(): { - keys(): unknown[]; - } | undefined; - asArray(): StateValueLike[] | undefined; - asBoundedMerkleTree(): { - height: number; - root(): { - value: Uint8Array[]; - } | undefined; - } | undefined; -} -export declare function describeRawState(state: StateValueLike): RawStateValue; -``` - -## `@kuiralabs/midnight-engine-rc/shielded-direct` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface ShieldedDirectResult { - balance: bigint; - availableCoins: number; - tokens: ReadonlyMap; - eventCount: number; - state: ledger.ZswapLocalState; - lastAppliedEventId: number; - partial: boolean; -} -export interface ShieldedDirectOptions { - onProgress?: (eventsApplied: number, maxIdSeen: number) => void; - onCheckpoint?: (state: ledger.ZswapLocalState, lastAppliedEventId: number) => void; - timeoutMs?: number; - idleMs?: number; - initialSilenceMs?: number; - signal?: AbortSignal; - initialState?: ledger.ZswapLocalState; - startFromId?: number; -} -export declare function readShieldedBalanceDirect(secretKeys: ledger.ZswapSecretKeys, indexerWS: string, options?: ShieldedDirectOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/shielded-direct-cache` - -```ts -import * as ledger from "@midnightntwrk/ledger-v9"; -export interface ShieldedCacheEntry { - state: ledger.ZswapLocalState; - lastAppliedEventId: number; -} -export declare function shieldedCoinPublicKeyHexFromSeed(seedBuffer: Buffer): string; -export declare function loadShieldedCache(network: string, pubkeyHex: string, root: string, expectedChainId?: string): ShieldedCacheEntry | null; -export declare function saveShieldedCache(network: string, pubkeyHex: string, state: ledger.ZswapLocalState, lastAppliedEventId: number, root: string, chainId?: string): void; -export type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { ShieldedBalanceResult, ShieldedCachedOptions } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function readShieldedBalanceCached(seedBuffer: Buffer, network: string, indexerWS: string, options: ShieldedCachedOptions): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/sign-recipe` - -```ts -import type { Signature } from "@midnightntwrk/ledger-v9"; -import type { BalancingRecipe, WalletFacade } from "@midnightntwrk/wallet-sdk/facade"; -import { type FeeCheckTransaction } from "./fee-only-check.ts"; -export type SignSegment = (data: Uint8Array) => Promise; -export type UnshieldedSignatures = "none" | "all" | "some"; -export declare function unshieldedSignatures(tx: FeeCheckTransaction): UnshieldedSignatures; -export declare class PartlySignedTransactionError extends Error { - constructor(); -} -export declare class SignedTransactionNeedsUnshieldedError extends Error { - constructor(segments: number[]); -} -export declare function unshieldedImbalanceSegments(tx: FeeCheckTransaction): number[]; -export declare function assertSignable(tx: FeeCheckTransaction, balancesUnshielded: boolean): void; -export declare function signRecipe(facade: WalletFacade, recipe: BalancingRecipe, signSegment: SignSegment): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/transfer` - -```ts -import { UnshieldedAddress, type DustAddress } from "@midnightntwrk/wallet-sdk/address-format"; -import { type FacadeState, type UtxoWithMeta } from "@midnightntwrk/wallet-sdk/facade"; -import { type NetworkConfig } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type FacadeBundle } from "./facade.ts"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -export declare function validateRecipientAddress(address: string, networkConfig: NetworkConfig): UnshieldedAddress; -export { isDustRelatedError, isSdkInsufficientFundsError } from "@kuiralabs/midnight-cli-core/lib/sdk-errors"; -import type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { EnsureDustResult, TransferParams, TransferResult } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function registerNightUtxos(bundle: FacadeBundle, nightUtxos: readonly UtxoWithMeta[], dustReceiverAddress: DustAddress, onStatus?: (status: string) => void): Promise; -export declare function ensureDust(bundle: FacadeBundle, onStatus?: (status: string) => void, syncedState?: FacadeState): Promise; -export declare function executeTransfer(repo: WalletDataRepository, params: TransferParams): Promise; -``` - -## `@kuiralabs/midnight-engine-rc/tx-inspect` - -```ts -import type { TransactionDetail } from "@kuiralabs/midnight-cli-core/lib/engine"; -export declare function inspectTxHex(txHex: string, stage: "unsealed" | "sealed"): TransactionDetail[]; -``` - -## `@kuiralabs/midnight-engine-rc/wallet` - -```ts -import type { EngineWallet } from "@kuiralabs/midnight-cli-core/lib/engine"; -import type { WalletDataRepository } from "./wallet-data-repository.ts"; -export declare function createRcWallet(repo: WalletDataRepository): EngineWallet; -``` - -## `@kuiralabs/midnight-engine-rc/wallet-data-repository` - -```ts -import { Buffer } from "node:buffer"; -import * as ledger from "@midnightntwrk/ledger-v9"; -import type { NetworkConfig, NetworkName } from "@kuiralabs/midnight-cli-core/lib/network"; -import { type FacadeState } from "@midnightntwrk/wallet-sdk/facade"; -import { type FacadeBundle, type SyncMode } from "./facade.ts"; -import { type WalletCacheData } from "@kuiralabs/midnight-cli-core/lib/wallet-cache"; -import { type BalanceSummary } from "@kuiralabs/midnight-chain/lib/balance-subscription"; -import { type DustDirectResult, type DustRetention } from "./dust-direct.ts"; -import type { VerboseLog } from "@kuiralabs/midnight-cli-core/lib/verbose"; -import type { NoticeSink } from "@kuiralabs/midnight-cli-core/lib/notices"; -import { type LedgerEventStream } from "@kuiralabs/midnight-chain/lib/event-tip"; -import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; -export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from "@kuiralabs/midnight-cli-core/lib/engine"; -export interface DustView extends DustBalance { - state: ledger.DustLocalState; -} -export interface FacadeLease { - bundle: FacadeBundle; - state: FacadeState; -} -export interface InvalidationScope { - network: NetworkConfig; - root: string; - seed?: Buffer; - address?: string; - kinds?: ReadonlyArray<"dust" | "unshielded" | "facade">; -} -export interface FacadeOptions extends CachedReadOptions { - syncMode?: SyncMode; - requireStrictSync?: boolean; - readOnly?: boolean; - skipAutoSave?: boolean; - syncTimeoutMs?: number; - onSyncProgress?: (applied: number, highest: number) => void; - onSyncDetail?: (detail: string) => void; - onSyncWarning?: (tag: string, message: string) => void; - noPrime?: boolean; -} -export type TipFingerprint = string; -export interface RepoDeps { - now?: () => number; - fetchTip?: (network: NetworkConfig, signal?: AbortSignal) => Promise; - fetchUnshielded?: (address: string, network: NetworkConfig, onProgress?: (current: number, highest: number) => void, signal?: AbortSignal) => Promise; - fetchDust?: (seed: Buffer, network: NetworkConfig, opts: { - startFromId: number; - initialState?: ledger.DustLocalState; - initialRetention?: DustRetention; - signal?: AbortSignal; - onProgress?: (applied: number, max: number) => void; - onCheckpoint?: (state: ledger.DustLocalState, lastAppliedEventId: number, retention: DustRetention) => void; - root: string; - log?: VerboseLog; - }) => Promise; - fetchChainId?: (nodeWsUrl: string) => Promise; - fetchEventTip?: (indexerWS: string, stream: LedgerEventStream) => Promise; - fetchProtocolVersion?: (indexerHttpUrl: string, signal?: AbortSignal) => Promise; -} -export declare class WalletDataRepository { - private readonly now; - private readonly fetchTip; - private readonly fetchUnshielded; - private readonly fetchDust; - private readonly fetchChainId; - private readonly fetchEventTip; - private readonly fetchProtocolVersion; - private readonly dustMemo; - private readonly unshieldedMemo; - private readonly tipMemo; - constructor(host: EngineHost, deps?: RepoDeps); - private keepCachesOfThisIndexer; - walletStateToRestore(seed: Buffer, network: NetworkConfig, networkName: NetworkName, root: string, notice: NoticeSink, log?: VerboseLog): Promise; - private freshWalletOnDustCheckpoint; - dust(seed: Buffer, network: NetworkConfig, opts: CachedReadOptions): Promise; - unshielded(identity: string | Buffer, network: NetworkConfig, opts?: ReadOptions): Promise; - withFacade(seed: Buffer, network: NetworkConfig, fn: (lease: FacadeLease) => Promise, opts: FacadeOptions): Promise; - invalidate(scope: InvalidationScope): void; - resetTipMemo(): void; - private tryMemo; - private memoize; - private getTip; - private deleteByPrefix; -} -``` diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index b9c82f4b..29d3267a 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -21,11 +21,6 @@ "midnight-cli-source": "./src/index.ts", "types": "./dist/index.d.ts", "default": "./dist/index.js" - }, - "./*": { - "midnight-cli-source": "./src/*.ts", - "types": "./dist/*.d.ts", - "default": "./dist/*.js" } }, "files": [ diff --git a/src/__tests__/contract-raw-state.test.ts b/packages/engine-rc/src/__tests__/contract-raw-state.test.ts similarity index 96% rename from src/__tests__/contract-raw-state.test.ts rename to packages/engine-rc/src/__tests__/contract-raw-state.test.ts index fd317a43..d2251c9f 100644 --- a/src/__tests__/contract-raw-state.test.ts +++ b/packages/engine-rc/src/__tests__/contract-raw-state.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { ChargedState, ContractState, StateBoundedMerkleTree, StateMap, StateValue } from '@midnight-ntwrk/compact-runtime'; -import { describeRawState } from '@kuiralabs/midnight-engine-rc/raw-state'; +import { describeRawState } from '../raw-state.ts'; const atom = (bytes: number[]) => ({ value: [new Uint8Array(bytes)], alignment: [{ tag: 'atom' as const, value: { tag: 'bytes' as const, length: bytes.length } }] }); diff --git a/packages/engine-rc/src/__tests__/contract-scripts.test.ts b/packages/engine-rc/src/__tests__/contract-scripts.test.ts new file mode 100644 index 00000000..31c67880 --- /dev/null +++ b/packages/engine-rc/src/__tests__/contract-scripts.test.ts @@ -0,0 +1,226 @@ +// The rc engine's contract scripts emit provider fragments; these tests +// evaluate them against the engine's midnight-js 5 / ledger-v9 packages. Only +// the mn serve RPC (`rpcCall`) is stubbed, and the script parts the contract +// runner gives every engine are plain values here (TEST_PARTS): the fragments +// read only the names of the indexer's environment variables from them. + +import { describe, it, expect, beforeAll, afterEach } from 'vitest'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { ScriptParts } from '@kuiralabs/midnight-cli-core/engine'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { + createWalletProvider, + createMidnightProvider, + assertSeamsSupportEra, + Transaction, + type WalletProvider, + type MidnightProvider, + type UnboundTransaction, +} from '@midnight-ntwrk/midnight-js-types'; +import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils'; +import { CURRENT_LEDGER_VERSION } from '@midnight-ntwrk/midnight-js-protocol/version'; +import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; +import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; +import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; +import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; +import { PROVIDER_IMPORTS, generateCallScript, generateDeployScript, providerSetupCode as providerSetupCodeFor, walletProviderCode } from '../contract-scripts.ts'; + +/** The script parts, as plain values: the fragments under test read only the indexer's environment variable names. */ +const TEST_PARTS: ScriptParts = { + prelude: '', + rpcClientCode: () => '', + coerceArgFn: '', + privateStateSecretFn: '', + witnessCandidates: [], + indexerUrlEnv: 'MN_TEST_INDEXER_URL', + indexerWsUrlEnv: 'MN_TEST_INDEXER_WS_URL', +}; + +const providerSetupCode = (networkConfig: NetworkConfig, key: string): string => providerSetupCodeFor(networkConfig, key, TEST_PARTS); + +/** The indexer's URLs in the environment, as the contract runner gives a script's process them. */ +const indexerEnvironment = (networkConfig: NetworkConfig): Record => ({ + [TEST_PARTS.indexerUrlEnv]: networkConfig.indexer, + [TEST_PARTS.indexerWsUrlEnv]: networkConfig.indexerWS!, +}); + +const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new ( + ...params: string[] +) => (...args: unknown[]) => Promise; + +const COIN_PK = 'aa'.repeat(32); +const ENC_PK = 'bb'.repeat(32); + +const NETWORK: NetworkConfig = { + indexer: 'http://127.0.0.1:1/api/v4/graphql', + indexerWS: 'ws://127.0.0.1:1/api/v4/graphql/ws', + node: 'ws://127.0.0.1:1', + proofServer: 'http://127.0.0.1:1', + networkId: 'Undeployed', +}; + +type RpcRecord = { method: string; params: Record }; + +/** Stub of the mn serve JSON-RPC boundary: records calls, answers from `replies`. */ +function makeRpcStub(replies: Record) { + const calls: RpcRecord[] = []; + const rpcCall = async (method: string, params: Record = {}) => { + calls.push({ method, params }); + if (!(method in replies)) throw new Error(`unexpected RPC ${method}`); + return replies[method]; + }; + return { calls, rpcCall }; +} + +/** Run the generated wallet/midnight provider fragment with the bindings PROVIDER_IMPORTS gives it. */ +async function evalWalletProviders(rpcCall: unknown) { + const fn = new AsyncFunction( + 'rpcCall', 'createWalletProvider', 'createMidnightProvider', 'Transaction', 'toHex', 'fromHex', + `${walletProviderCode()}\nreturn { walletProvider, midnightProvider };`, + ); + return await fn(rpcCall, createWalletProvider, createMidnightProvider, Transaction, toHex, fromHex) as { + walletProvider: WalletProvider; + midnightProvider: MidnightProvider; + }; +} + +// Real ledger-v9 txs built offline: an empty intent needs no circuit proofs, +// so prove() never reaches the proving provider. +let unboundTx: UnboundTransaction; +let finalizedTx: ledger.FinalizedTransaction; + +beforeAll(async () => { + const neverProves = async () => { throw new Error('proving provider must not be called'); }; + const unproven = ledger.Transaction.fromParts( + 'undeployed', undefined, undefined, ledger.Intent.new(new Date(Date.UTC(2030, 0, 1))), + ); + unboundTx = await unproven.prove( + { check: neverProves, prove: neverProves, lookupKey: neverProves }, + ledger.CostModel.initialCostModel(), + ); + finalizedTx = ledger.Transaction.fromParts( + 'undeployed', undefined, undefined, ledger.Intent.new(new Date(Date.UTC(2030, 0, 1))), + ).mockProve(); +}); + +describe('generated walletProvider', () => { + it('declares the current ledger era so midnight-js 5 does not refuse it', async () => { + const { rpcCall } = makeRpcStub({ + getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, + }); + const { walletProvider, midnightProvider } = await evalWalletProviders(rpcCall); + + expect(walletProvider.supportedEras).toContain(CURRENT_LEDGER_VERSION); + expect(midnightProvider.supportedEras).toContain(CURRENT_LEDGER_VERSION); + }); + + it('returns the keys mn serve reports', async () => { + const { rpcCall } = makeRpcStub({ + getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, + }); + const { walletProvider } = await evalWalletProviders(rpcCall); + + expect(walletProvider.getCoinPublicKey()).toBe(COIN_PK); + expect(walletProvider.getEncryptionPublicKey()).toBe(ENC_PK); + }); + + it('balances a v9-tagged tx via balanceUnsealedTransaction and returns the sealed tx v9-tagged', async () => { + const sealedHex = toHex(finalizedTx.serialize()); + const { calls, rpcCall } = makeRpcStub({ + getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, + balanceUnsealedTransaction: { tx: sealedHex }, + }); + const { walletProvider } = await evalWalletProviders(rpcCall); + + const balanced = await walletProvider.balanceTx({ version: 'v9', tx: unboundTx }); + + const balanceCall = calls.find((c) => c.method === 'balanceUnsealedTransaction'); + expect(balanceCall?.params).toEqual({ tx: toHex(unboundTx.serialize()) }); + expect(balanced.version).toBe('v9'); + if (balanced.version !== 'v9') throw new Error('unreachable'); + expect(balanced.tx).toBeInstanceOf(Transaction); + expect(toHex(balanced.tx.serialize())).toBe(sealedHex); + }); + + it('surfaces an RPC rejection from mn serve', async () => { + const { rpcCall } = makeRpcStub({ + getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, + }); + const { walletProvider } = await evalWalletProviders(rpcCall); + + await expect(walletProvider.balanceTx({ version: 'v9', tx: unboundTx })) + .rejects.toThrow('unexpected RPC balanceUnsealedTransaction'); + }); +}); + +describe('generated midnightProvider', () => { + it('submits the unwrapped tx hex via submitTransaction and returns its first identifier', async () => { + const { calls, rpcCall } = makeRpcStub({ + getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, + submitTransaction: { txHash: 'ignored-by-provider' }, + }); + const { midnightProvider } = await evalWalletProviders(rpcCall); + + const txId = await midnightProvider.submitTx({ version: 'v9', tx: finalizedTx }); + + const submitCall = calls.find((c) => c.method === 'submitTransaction'); + expect(submitCall?.params).toEqual({ tx: toHex(finalizedTx.serialize()) }); + expect(txId).toBe(finalizedTx.identifiers()[0]); + }); +}); + +describe('generated providers object', () => { + let dir: string | undefined; + afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = undefined; }); + + it('passes the era check deployContract/findDeployedContract run first', async () => { + dir = mkdtempSync(join(tmpdir(), 'mn-runner-')); + const { rpcCall } = makeRpcStub({ + getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, + }); + const { walletProvider, midnightProvider } = await evalWalletProviders(rpcCall); + const fn = new AsyncFunction( + 'MANAGED_DIR', 'walletProvider', 'midnightProvider', + 'NodeZkConfigProvider', 'httpClientProofProvider', 'indexerPublicDataProvider', 'levelPrivateStateProvider', + `${providerSetupCode(NETWORK, 'counterPrivateState')}\nreturn providers;`, + ); + // The generated code reads the indexer's URLs from its environment, as the script's process is given them. + const environment = indexerEnvironment(NETWORK); + Object.assign(process.env, environment); + try { + const providers = await fn( + dir, walletProvider, midnightProvider, + NodeZkConfigProvider, httpClientProofProvider, indexerPublicDataProvider, levelPrivateStateProvider, + ); + try { + expect(() => assertSeamsSupportEra(CURRENT_LEDGER_VERSION, providers)).not.toThrow(); + expect(providers.midnightProvider).toBe(midnightProvider); + } finally { + await providers.publicDataProvider.dispose(); + } + } finally { + for (const name of Object.keys(environment)) delete process.env[name]; + } + }); +}); + +describe('generated scripts', () => { + const scripts = { + deploy: generateDeployScript({ + networkConfig: NETWORK, managedDir: '/tmp/dapp/managed/counter', + contractName: 'counter', servePort: 9932, args: [1, 'x'], + }, TEST_PARTS), + call: generateCallScript({ + networkConfig: NETWORK, managedDir: '/tmp/dapp/managed/counter', + contractName: 'counter', servePort: 9932, contractAddress: 'ab'.repeat(32), circuit: 'increment', args: [], + }, TEST_PARTS), + }; + + it('includes the provider imports in deploy and call scripts', () => { + expect(scripts.deploy).toContain(PROVIDER_IMPORTS); + expect(scripts.call).toContain(PROVIDER_IMPORTS); + }); +}); diff --git a/src/__tests__/dapp-connector.test.ts b/packages/engine-rc/src/__tests__/dapp-connector.test.ts similarity index 77% rename from src/__tests__/dapp-connector.test.ts rename to packages/engine-rc/src/__tests__/dapp-connector.test.ts index 7d252a76..605cfef2 100644 --- a/src/__tests__/dapp-connector.test.ts +++ b/packages/engine-rc/src/__tests__/dapp-connector.test.ts @@ -1,15 +1,15 @@ // The DApp connector's tests over the rc engine (preprod, preview, undeployed). // The tests are the suite both engines run: helpers/connector-suite.ts. -import { createDAppConnector, signatureScheme, toHistoryEntry } from '@kuiralabs/midnight-engine-rc/dapp-connector'; -import { PartlySignedTransactionError } from '@kuiralabs/midnight-engine-rc/sign-recipe'; -import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { deriveAllShieldedAddresses, deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createDAppConnector, signatureScheme, toHistoryEntry } from '../dapp-connector.ts'; +import { PartlySignedTransactionError } from '../sign-recipe.ts'; +import { FORK_SCHEDULE } from '../fork-schedule.ts'; +import { deriveAllShieldedAddresses, deriveShieldedAddress, deriveUnshieldedAddress } from '../derive-address.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; import { createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; import { DustAddress, MidnightBech32m, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; -import { connectorSuite } from './helpers/connector-suite.ts'; +import { connectorSuite } from '../../../../test-support/connector-suite.ts'; connectorSuite({ set: 'rc', diff --git a/src/__tests__/derive-address.test.ts b/packages/engine-rc/src/__tests__/derive-address.test.ts similarity index 97% rename from src/__tests__/derive-address.test.ts rename to packages/engine-rc/src/__tests__/derive-address.test.ts index 87cae70f..396454a1 100644 --- a/src/__tests__/derive-address.test.ts +++ b/packages/engine-rc/src/__tests__/derive-address.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { deriveUnshieldedAddress, deriveAllShieldedAddresses } from '../derive-address.ts'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); diff --git a/src/__tests__/dust-collapse.test.ts b/packages/engine-rc/src/__tests__/dust-collapse.test.ts similarity index 99% rename from src/__tests__/dust-collapse.test.ts rename to packages/engine-rc/src/__tests__/dust-collapse.test.ts index 1ecc80d1..66d5c373 100644 --- a/src/__tests__/dust-collapse.test.ts +++ b/packages/engine-rc/src/__tests__/dust-collapse.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { computeForeignRanges, collapseForeignGenerations } from '@kuiralabs/midnight-engine-rc/dust-collapse'; +import { computeForeignRanges, collapseForeignGenerations } from '../dust-collapse.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; // Same initial dust params the sync path uses (dust-direct.ts). diff --git a/src/__tests__/dust-direct-cache.test.ts b/packages/engine-rc/src/__tests__/dust-direct-cache.test.ts similarity index 98% rename from src/__tests__/dust-direct-cache.test.ts rename to packages/engine-rc/src/__tests__/dust-direct-cache.test.ts index a4547701..2c7f0194 100644 --- a/src/__tests__/dust-direct-cache.test.ts +++ b/packages/engine-rc/src/__tests__/dust-direct-cache.test.ts @@ -7,8 +7,9 @@ import * as path from 'path'; import * as os from 'os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { loadDustCache, saveDustCache, dustPublicKeyHex } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; -import { clearDustDirectCache, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { loadDustCache, saveDustCache, dustPublicKeyHex } from '../dust-direct-cache.ts'; +import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core'; +import { getDustCachePath } from '@kuiralabs/midnight-cli-core/engine'; const STATE_ROOT = path.join(os.tmpdir(), `midnight-dust-cache-test-${process.pid}-${Date.now()}`); const NETWORK = 'undeployed'; diff --git a/src/__tests__/dust-export.test.ts b/packages/engine-rc/src/__tests__/dust-export.test.ts similarity index 94% rename from src/__tests__/dust-export.test.ts rename to packages/engine-rc/src/__tests__/dust-export.test.ts index 410ab832..9b38c258 100644 --- a/src/__tests__/dust-export.test.ts +++ b/packages/engine-rc/src/__tests__/dust-export.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { overlayDustDirectSnapshot } from '@kuiralabs/midnight-engine-rc/facade'; -import type { DustCacheEntry } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; +import { overlayDustDirectSnapshot } from '../facade.ts'; +import type { DustCacheEntry } from '../dust-direct-cache.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; // overlayDustDirectSnapshot is the seam behind `dust export` (and the write-command @@ -96,11 +96,11 @@ import { beforeEach, afterEach } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { exportDustSnapshot } from '@kuiralabs/midnight-engine-rc/dust-export'; -import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; -import { testHost } from './helpers/test-host.ts'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { DustDirectResult } from '@kuiralabs/midnight-engine-rc/dust-direct'; +import { exportDustSnapshot } from '../dust-export.ts'; +import { WalletDataRepository } from '../wallet-data-repository.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { DustDirectResult } from '../dust-direct.ts'; const EXPORT_NETWORK: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', diff --git a/src/__tests__/dust-logic.test.ts b/packages/engine-rc/src/__tests__/dust-logic.test.ts similarity index 98% rename from src/__tests__/dust-logic.test.ts rename to packages/engine-rc/src/__tests__/dust-logic.test.ts index d9c8fe3b..a14f906f 100644 --- a/src/__tests__/dust-logic.test.ts +++ b/packages/engine-rc/src/__tests__/dust-logic.test.ts @@ -4,9 +4,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import * as rx from 'rxjs'; -import { isDustRelatedError, ensureDust, registerNightUtxos } from '@kuiralabs/midnight-engine-rc/transfer'; -import { DustFeeNotGeneratedError } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; -import type { FacadeBundle } from '@kuiralabs/midnight-engine-rc/facade'; +import { isDustRelatedError, ensureDust, registerNightUtxos } from '../transfer.ts'; +import { DustFeeNotGeneratedError } from '@kuiralabs/midnight-cli-core/engine'; +import type { FacadeBundle } from '../facade.ts'; import type { DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; @@ -377,8 +377,8 @@ describe('registerNightUtxos', () => { }); it('refuses before estimating anything while the chain\'s clock lags this computer\'s', async () => { - const { startLocalIndexer } = await import('./helpers/local-indexer.ts'); - const { ChainClockBehindError } = await import('@kuiralabs/midnight-chain/lib/chain-clock'); + const { startLocalIndexer } = await import('../../../../test-support/local-indexer.ts'); + const { ChainClockBehindError } = await import('@kuiralabs/midnight-chain'); vi.useRealTimers(); const indexer = await startLocalIndexer(() => JSON.stringify({ data: { block: { timestamp: Date.now() - 14 * 3_600_000 } } })); try { diff --git a/src/__tests__/dust-sync-native.test.ts b/packages/engine-rc/src/__tests__/dust-sync-native.test.ts similarity index 88% rename from src/__tests__/dust-sync-native.test.ts rename to packages/engine-rc/src/__tests__/dust-sync-native.test.ts index 443c043e..f79d7204 100644 --- a/src/__tests__/dust-sync-native.test.ts +++ b/packages/engine-rc/src/__tests__/dust-sync-native.test.ts @@ -1,18 +1,12 @@ import { describe, it, expect, afterEach, vi } from 'vitest'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { - resumeDecision, - adaptResult, - resolveSidecarBinary, - nativeDustSyncAvailable, - runDustSyncNative, - type SidecarCheckpoint, -} from '@kuiralabs/midnight-engine-rc/dust-sync-native'; +import { pathToFileURL } from 'node:url'; +import { resumeDecision, adaptResult, resolveSidecarBinary, nativeDustSyncAvailable, runDustSyncNative, platformPackageBinary, type SidecarCheckpoint } from '../dust-sync-native.ts'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core'; // The settings a host reading the environment gives its engine: what each test sets there. const envSettings = () => settingsFromEnvironment(process.env); @@ -221,3 +215,21 @@ describe('adaptResult — native-path generation-tree collapse', () => { expect(on.state.generatingTreeRoot()).toBe(off.state.generatingTreeRoot()); // root invariant held }); }); + +describe("the sidecar's platform package", () => { + let dir: string; + afterEach(() => { rmSync(dir, { recursive: true, force: true }); }); + + it('is found from a folder it is installed under, and is null where it is not', () => { + dir = realpathSync(mkdtempSync(join(tmpdir(), 'mn-sidecar-package-'))); + const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; + const pkg = join(dir, 'node_modules', '@nel349', `dust-sync-${process.platform}-${process.arch}`); + mkdirSync(pkg, { recursive: true }); + writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name: `@nel349/dust-sync-${process.platform}-${process.arch}`, version: '0.0.0' })); + writeFileSync(join(pkg, exe), ''); + const from = pathToFileURL(join(dir, 'app', 'index.js')).href; + + expect(platformPackageBinary(from)).toBe(join(pkg, exe)); + expect(platformPackageBinary(pathToFileURL(join(tmpdir(), 'nowhere', 'index.js')).href)).toBeNull(); + }); +}); diff --git a/src/__tests__/dust-wallet.test.ts b/packages/engine-rc/src/__tests__/dust-wallet.test.ts similarity index 97% rename from src/__tests__/dust-wallet.test.ts rename to packages/engine-rc/src/__tests__/dust-wallet.test.ts index f22b0cd9..46feacac 100644 --- a/src/__tests__/dust-wallet.test.ts +++ b/packages/engine-rc/src/__tests__/dust-wallet.test.ts @@ -10,9 +10,9 @@ import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import { Transacting } from '@midnightntwrk/wallet-sdk/dust/v2'; import { WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk/facade'; import { EitherOps } from '@midnightntwrk/wallet-sdk/utilities'; -import { ConvergingDustTransacting, DustWallet } from '@kuiralabs/midnight-engine-rc/dust-wallet'; -import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { dustShortfallOf, isDustShortage } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { ConvergingDustTransacting, DustWallet } from '../dust-wallet.ts'; +import { FORK_SCHEDULE } from '../fork-schedule.ts'; +import { dustShortfallOf, isDustShortage } from '@kuiralabs/midnight-cli-core/engine'; import { CAPTURED_AT, type FeeRange, coinsAt, computeArguments, feeRange, paymentToBalance, timeWhenSmallestReaches, transacting, } from './helpers/dust-balancing-case.ts'; @@ -69,7 +69,7 @@ describe('the SDK\'s own choice of fee coins', () => { // Node itself, loading tsx, not the tsx command: that one runs the script // in a child of its own, which a kill of the command leaves looping. const child = spawn(process.execPath, ['--import', 'tsx', canary], { - cwd: fileURLToPath(new URL('../..', import.meta.url)), + cwd: fileURLToPath(new URL('../../../..', import.meta.url)), stdio: ['ignore', 'pipe', 'inherit'], }); const exited = new Promise((resolve) => { child.once('exit', () => resolve()); }); diff --git a/src/__tests__/facade.test.ts b/packages/engine-rc/src/__tests__/facade.test.ts similarity index 95% rename from src/__tests__/facade.test.ts rename to packages/engine-rc/src/__tests__/facade.test.ts index 35d09185..793439e2 100644 --- a/src/__tests__/facade.test.ts +++ b/packages/engine-rc/src/__tests__/facade.test.ts @@ -7,7 +7,7 @@ import { WebSocketServer } from 'ws'; import { SyncProgress } from '@midnightntwrk/wallet-sdk'; import { SyncProgress as UnshieldedSyncProgress } from '@midnightntwrk/wallet-sdk/unshielded/v2'; import type { FacadeState } from '@midnightntwrk/wallet-sdk/facade'; -import { isFacadeSynced, detectStaleCache } from '@kuiralabs/midnight-engine-rc/facade'; +import { isFacadeSynced, detectStaleCache } from '../facade.ts'; type IndexProgress = ReturnType; type TxProgress = ReturnType; @@ -157,7 +157,7 @@ describe('startAndSyncFacade: starting the wallets exactly once', () => { async function startWith(restoredFromCache: boolean) { const { vi } = await import('vitest'); const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('@kuiralabs/midnight-engine-rc/facade'); + const { startAndSyncFacade } = await import('../facade.ts'); const seeds = { shielded: new Uint8Array([1]), unshielded: new Uint8Array([2]), dust: new Uint8Array([3]) }; const calls = { facadeStart: vi.fn(async () => {}), @@ -231,7 +231,7 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { async function syncWith(indexerWsUrl: string) { const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('@kuiralabs/midnight-engine-rc/facade'); + const { startAndSyncFacade } = await import('../facade.ts'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, seeds: {}, @@ -260,8 +260,8 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const url = await indexerWith({ zswapLedgerEvents: { id: 0, maxId: 384 }, dustLedgerEvents: { id: 0, maxId: 385 } }); const rx = await import('rxjs'); - const { startAndSyncFacade } = await import('@kuiralabs/midnight-engine-rc/facade'); - const { CancelledError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); + const { startAndSyncFacade } = await import('../facade.ts'); + const { CancelledError } = await import('@kuiralabs/midnight-cli-core'); const bundle: any = { facade: { start: async () => {}, state: () => rx.concat(rx.of(state({ shielded: indexed(0n, 0n, false) })), rx.NEVER) }, seeds: {}, seedStartable: {}, keystore: {}, restoredFromCache: false, indexerWsUrl: url, @@ -281,8 +281,8 @@ describe('startAndSyncFacade: a wallet that has heard nothing yet', () => { describe('waitForDustAvailable', () => { it('stops waiting with CancelledError when the call is cancelled, long before its timeout', async () => { const rx = await import('rxjs'); - const { waitForDustAvailable } = await import('@kuiralabs/midnight-engine-rc/facade'); - const { CancelledError } = await import('@kuiralabs/midnight-cli-core/lib/errors'); + const { waitForDustAvailable } = await import('../facade.ts'); + const { CancelledError } = await import('@kuiralabs/midnight-cli-core'); // A wallet with no Dust, and no later state. const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; @@ -293,7 +293,7 @@ describe('waitForDustAvailable', () => { it('returns the latest state when its timeout passes without Dust, as before', async () => { const rx = await import('rxjs'); - const { waitForDustAvailable } = await import('@kuiralabs/midnight-engine-rc/facade'); + const { waitForDustAvailable } = await import('../facade.ts'); const noDust = { ...state(), dust: { progress: SYNCED, availableCoins: [], balance: () => 0n } } as unknown as FacadeState; const bundle: any = { facade: { state: () => rx.concat(rx.of(noDust), rx.NEVER) } }; await expect(waitForDustAvailable(bundle, 50, new AbortController().signal)).resolves.toBe(noDust); diff --git a/src/__tests__/fee-only-check.test.ts b/packages/engine-rc/src/__tests__/fee-only-check.test.ts similarity index 98% rename from src/__tests__/fee-only-check.test.ts rename to packages/engine-rc/src/__tests__/fee-only-check.test.ts index ff818f8a..70253ae6 100644 --- a/src/__tests__/fee-only-check.test.ts +++ b/packages/engine-rc/src/__tests__/fee-only-check.test.ts @@ -14,11 +14,11 @@ import { shieldedToken, signData, } from '@midnightntwrk/ledger-v9'; -import { expiredIntents, feeOnlyRefusals, readDAppTransaction } from '@kuiralabs/midnight-engine-rc/fee-only-check'; +import { expiredIntents, feeOnlyRefusals, readDAppTransaction } from '../fee-only-check.ts'; import { AGENT_SK, AGENT_VK, NETWORK, NIGHT, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, sealedBytes, spend, unsealedBytes, -} from './helpers/ledger-tx.ts'; +} from '../../../../test-support/ledger-tx.ts'; describe('readDAppTransaction', () => { it('reads proven pre-binding bytes as unsealed and bound bytes as sealed', async () => { diff --git a/src/__tests__/fee-only-signing.test.ts b/packages/engine-rc/src/__tests__/fee-only-signing.test.ts similarity index 97% rename from src/__tests__/fee-only-signing.test.ts rename to packages/engine-rc/src/__tests__/fee-only-signing.test.ts index 31ce4a5e..bfc0afa6 100644 --- a/src/__tests__/fee-only-signing.test.ts +++ b/packages/engine-rc/src/__tests__/fee-only-signing.test.ts @@ -23,12 +23,12 @@ import { type SignatureVerifyingKey, } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { feeOnlyRefusals, readDAppTransaction } from '@kuiralabs/midnight-engine-rc/fee-only-check'; -import { signRecipe } from '@kuiralabs/midnight-engine-rc/sign-recipe'; +import { feeOnlyRefusals, readDAppTransaction } from '../fee-only-check.ts'; +import { signRecipe } from '../sign-recipe.ts'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, spend, unsealedBytes, -} from './helpers/ledger-tx.ts'; +} from '../../../../test-support/ledger-tx.ts'; import { initOfflineFacade, keystore } from './helpers/offline-facade.ts'; let facade: WalletFacade; diff --git a/src/__tests__/fixtures/dust-state-owned.ts b/packages/engine-rc/src/__tests__/fixtures/dust-state-owned.ts similarity index 100% rename from src/__tests__/fixtures/dust-state-owned.ts rename to packages/engine-rc/src/__tests__/fixtures/dust-state-owned.ts diff --git a/src/__tests__/fixtures/dust-state-two-coins.ts b/packages/engine-rc/src/__tests__/fixtures/dust-state-two-coins.ts similarity index 100% rename from src/__tests__/fixtures/dust-state-two-coins.ts rename to packages/engine-rc/src/__tests__/fixtures/dust-state-two-coins.ts diff --git a/src/__tests__/helpers/dust-balancing-case.ts b/packages/engine-rc/src/__tests__/helpers/dust-balancing-case.ts similarity index 96% rename from src/__tests__/helpers/dust-balancing-case.ts rename to packages/engine-rc/src/__tests__/helpers/dust-balancing-case.ts index f530cd70..5537f179 100644 --- a/src/__tests__/helpers/dust-balancing-case.ts +++ b/packages/engine-rc/src/__tests__/helpers/dust-balancing-case.ts @@ -5,10 +5,10 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { CoinsAndBalances, CoreWallet, Keys, Transacting } from '@midnightntwrk/wallet-sdk/dust/v2'; -import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/engine'; import { TWO_COIN_DUST_CAPTURED_AT, TWO_COIN_DUST_SEED_HEX, TWO_COIN_DUST_STATE_HEX } from '../fixtures/dust-state-two-coins.ts'; -import { LEDGER9_PARAMETERS_HEX } from '../fixtures/ledger9-parameters.ts'; -import { NETWORK, TTL, agentPaysMerchant, unsealedBytes } from './ledger-tx.ts'; +import { LEDGER9_PARAMETERS_HEX } from '../../../../../test-support/fixtures/ledger9-parameters.ts'; +import { NETWORK, TTL, agentPaysMerchant, unsealedBytes } from '../../../../../test-support/ledger-tx.ts'; type SdkTransacting = Transacting.TransactingCapabilityImplementation; type TransactingClass = new (...args: ConstructorParameters>) => SdkTransacting; diff --git a/src/__tests__/helpers/offline-facade.ts b/packages/engine-rc/src/__tests__/helpers/offline-facade.ts similarity index 91% rename from src/__tests__/helpers/offline-facade.ts rename to packages/engine-rc/src/__tests__/helpers/offline-facade.ts index 80020a20..5fa1e35a 100644 --- a/src/__tests__/helpers/offline-facade.ts +++ b/packages/engine-rc/src/__tests__/helpers/offline-facade.ts @@ -7,13 +7,13 @@ // loopback port. import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; -import { DustWallet } from '@kuiralabs/midnight-engine-rc/dust-wallet'; +import { DustWallet } from '../../dust-wallet.ts'; import { WalletFacade, WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk/facade'; import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; import { PublicKey, UnshieldedWallet, createKeystore } from '@midnightntwrk/wallet-sdk/unshielded'; -import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { NETWORK } from './ledger-tx.ts'; +import { FORK_SCHEDULE } from '../../fork-schedule.ts'; +import { DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN } from '@kuiralabs/midnight-cli-core/engine'; +import { NETWORK } from '../../../../../test-support/ledger-tx.ts'; /** The secret behind ledger-tx's WALLET_SK, as mn's schnorr keystore takes it. */ export const keystore = createKeystore({ kind: 'schnorr', secret: new Uint8Array(32).fill(1) }, NETWORK); diff --git a/src/__tests__/helpers/sdk-dust-loop-canary.ts b/packages/engine-rc/src/__tests__/helpers/sdk-dust-loop-canary.ts similarity index 100% rename from src/__tests__/helpers/sdk-dust-loop-canary.ts rename to packages/engine-rc/src/__tests__/helpers/sdk-dust-loop-canary.ts diff --git a/src/__tests__/network-id.test.ts b/packages/engine-rc/src/__tests__/network-id.test.ts similarity index 87% rename from src/__tests__/network-id.test.ts rename to packages/engine-rc/src/__tests__/network-id.test.ts index 198ceb36..c2775885 100644 --- a/src/__tests__/network-id.test.ts +++ b/packages/engine-rc/src/__tests__/network-id.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; +import { getNetworkId } from '@kuiralabs/midnight-cli-core/engine'; import { NetworkId } from '@midnightntwrk/wallet-sdk'; describe('getNetworkId', () => { @@ -27,7 +27,7 @@ describe('getNetworkId', () => { describe('the plain values the base keeps match the SDK', () => { it("names each network by the SDK's NetworkId", async () => { - const { networkIdForName } = await import('@kuiralabs/midnight-cli-core/lib/network-id'); + const { networkIdForName } = await import('@kuiralabs/midnight-cli-core/engine'); expect(networkIdForName('preprod')).toBe(NetworkId.NetworkId.PreProd); expect(networkIdForName('preview')).toBe(NetworkId.NetworkId.Preview); expect(networkIdForName('undeployed')).toBe(NetworkId.NetworkId.Undeployed); @@ -35,8 +35,8 @@ describe('the plain values the base keeps match the SDK', () => { it("keeps the ledger-9 fork at the SDK's version, and the facade's schedule starts there", async () => { const { ProtocolVersion } = await import('@midnightntwrk/wallet-sdk'); - const { LEDGER_9_FORK_VERSION } = await import('@kuiralabs/midnight-cli-core/lib/network'); - const { FORK_SCHEDULE } = await import('@kuiralabs/midnight-engine-rc/fork-schedule'); + const { LEDGER_9_FORK_VERSION } = await import('@kuiralabs/midnight-cli-core'); + const { FORK_SCHEDULE } = await import('../fork-schedule.ts'); expect(LEDGER_9_FORK_VERSION).toBe(ProtocolVersion.V9NativeForkVersion); expect(FORK_SCHEDULE.v9).toBe(LEDGER_9_FORK_VERSION); }); diff --git a/src/__tests__/offer-reader.test.ts b/packages/engine-rc/src/__tests__/offer-reader.test.ts similarity index 59% rename from src/__tests__/offer-reader.test.ts rename to packages/engine-rc/src/__tests__/offer-reader.test.ts index f637e6da..4beacf1d 100644 --- a/src/__tests__/offer-reader.test.ts +++ b/packages/engine-rc/src/__tests__/offer-reader.test.ts @@ -1,7 +1,7 @@ // The offer reader on the rc engine. The tests are the suite both engines run: helpers/offer-reader-suite.ts. import * as ledger from '@midnightntwrk/ledger-v9'; -import { readOffer, spentNullifiers } from '@kuiralabs/midnight-engine-rc/offer-reader'; -import { offerReaderSuite } from './helpers/offer-reader-suite.ts'; +import { readOffer, spentNullifiers } from '../offer-reader.ts'; +import { offerReaderSuite } from '../../../../test-support/offer-reader-suite.ts'; offerReaderSuite({ set: 'rc', ledger, readOffer, spentNullifiers }); diff --git a/packages/engine-rc/src/__tests__/repository-cancellation.test.ts b/packages/engine-rc/src/__tests__/repository-cancellation.test.ts new file mode 100644 index 00000000..2016eabe --- /dev/null +++ b/packages/engine-rc/src/__tests__/repository-cancellation.test.ts @@ -0,0 +1,52 @@ +// The rc engine's wallet data repository takes the call's signal: cancelled +// while it checks a memoized read, it stops with CANCELLED; and it passes the +// signal on to its fetches. (The chain's reads, cancelled, are the chain's +// tests: packages/chain/src/__tests__/read-cancellation.test.ts.) + +import { describe, expect, it } from 'vitest'; +import { getNetworkConfig, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain'; +import { WalletDataRepository } from '../wallet-data-repository.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; + +describe('the wallet data repository, cancelled while it checks a memoized read', () => { + it('stops with CANCELLED rather than serving the memo as if the node were down', async () => { + let clock = 0; + const summary: BalanceSummary = { balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }; + const call = new AbortController(); + let tipChecks = 0; + const repo = new WalletDataRepository(testHost(), { + now: () => clock, + // The first check answers; the second waits until its call is cancelled, as a node that doesn't answer. + fetchTip: (_network, signal) => { + tipChecks += 1; + if (tipChecks === 1) return Promise.resolve('tip-1'); + return new Promise((_resolve, reject) => { + signal!.addEventListener('abort', () => reject(signal!.reason), { once: true }); + call.abort(); + }); + }, + fetchUnshielded: async () => summary, + }); + const network: NetworkConfig = getNetworkConfig('undeployed'); + + await repo.unshielded('mn_addr_undeployed1x', network); + clock += 60_000; // past the tip probe's memo, so the next read checks the tip again + + await expect(repo.unshielded('mn_addr_undeployed1x', network, { signal: call.signal })).rejects.toMatchObject({ code: 'CANCELLED' }); + }); + + it('passes the call\'s signal on to its unshielded fetch', async () => { + const seen: Array = []; + const repo = new WalletDataRepository(testHost(), { + fetchTip: async () => 'tip', + fetchUnshielded: async (_address, _network, _onProgress, signal) => { + seen.push(signal); + return { balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }; + }, + }); + const signal = new AbortController().signal; + await repo.unshielded('mn_addr_undeployed1x', getNetworkConfig('undeployed'), { signal }); + expect(seen).toEqual([signal]); + }); +}); diff --git a/src/__tests__/shielded-direct-cache.test.ts b/packages/engine-rc/src/__tests__/shielded-direct-cache.test.ts similarity index 96% rename from src/__tests__/shielded-direct-cache.test.ts rename to packages/engine-rc/src/__tests__/shielded-direct-cache.test.ts index eb00b501..faf435ea 100644 --- a/src/__tests__/shielded-direct-cache.test.ts +++ b/packages/engine-rc/src/__tests__/shielded-direct-cache.test.ts @@ -3,8 +3,9 @@ import { mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync, mkdirSync import { join } from 'node:path'; import { tmpdir } from 'node:os'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { shieldedCoinPublicKeyHexFromSeed, loadShieldedCache, saveShieldedCache } from '@kuiralabs/midnight-engine-rc/shielded-direct-cache'; -import { getShieldedCachePath, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { shieldedCoinPublicKeyHexFromSeed, loadShieldedCache, saveShieldedCache } from '../shielded-direct-cache.ts'; +import { clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core'; +import { getShieldedCachePath } from '@kuiralabs/midnight-cli-core/engine'; const PUBKEY = 'aabbccddeeff00112233445566778899aabbccddeeff001122334455667788ff'; const OTHER_PUBKEY = '1122334455667788112233445566778811223344556677881122334455667788'; diff --git a/src/__tests__/shielded-direct.test.ts b/packages/engine-rc/src/__tests__/shielded-direct.test.ts similarity index 63% rename from src/__tests__/shielded-direct.test.ts rename to packages/engine-rc/src/__tests__/shielded-direct.test.ts index 302cb104..a287286c 100644 --- a/src/__tests__/shielded-direct.test.ts +++ b/packages/engine-rc/src/__tests__/shielded-direct.test.ts @@ -2,9 +2,9 @@ // suite both engines run: helpers/shielded-direct-suite.ts. import * as ledger from '@midnightntwrk/ledger-v9'; -import { readShieldedBalanceDirect } from '@kuiralabs/midnight-engine-rc/shielded-direct'; -import { deriveShieldedSeed } from '@kuiralabs/midnight-engine-rc/derivation'; -import { shieldedDirectSuite } from './helpers/shielded-direct-suite.ts'; +import { readShieldedBalanceDirect } from '../shielded-direct.ts'; +import { deriveShieldedSeed } from '../derivation.ts'; +import { shieldedDirectSuite } from '../../../../test-support/shielded-direct-suite.ts'; shieldedDirectSuite({ set: 'rc', diff --git a/src/__tests__/sign-recipe.test.ts b/packages/engine-rc/src/__tests__/sign-recipe.test.ts similarity index 97% rename from src/__tests__/sign-recipe.test.ts rename to packages/engine-rc/src/__tests__/sign-recipe.test.ts index 9a4b3386..c77b9c53 100644 --- a/src/__tests__/sign-recipe.test.ts +++ b/packages/engine-rc/src/__tests__/sign-recipe.test.ts @@ -20,14 +20,12 @@ import { type SignatureVerifyingKey, } from '@midnightntwrk/ledger-v9'; import type { BalancingRecipe, WalletFacade } from '@midnightntwrk/wallet-sdk/facade'; -import { feeOnlyRefusals, readDAppTransaction } from '@kuiralabs/midnight-engine-rc/fee-only-check'; -import { - PartlySignedTransactionError, SignedTransactionNeedsUnshieldedError, assertSignable, signRecipe, unshieldedImbalanceSegments, unshieldedSignatures, -} from '@kuiralabs/midnight-engine-rc/sign-recipe'; +import { feeOnlyRefusals, readDAppTransaction } from '../fee-only-check.ts'; +import { PartlySignedTransactionError, SignedTransactionNeedsUnshieldedError, assertSignable, signRecipe, unshieldedImbalanceSegments, unshieldedSignatures } from '../sign-recipe.ts'; import { AGENT_SK, AGENT_VK, NETWORK, TTL, WALLET_SK, WALLET_VK, agentPaysMerchant, buildTx, pay, spend, unsealedBytes, -} from './helpers/ledger-tx.ts'; +} from '../../../../test-support/ledger-tx.ts'; import { initOfflineFacade, keystore } from './helpers/offline-facade.ts'; let facade: WalletFacade; diff --git a/packages/engine-rc/src/__tests__/stale-cache.test.ts b/packages/engine-rc/src/__tests__/stale-cache.test.ts new file mode 100644 index 00000000..391bc65a --- /dev/null +++ b/packages/engine-rc/src/__tests__/stale-cache.test.ts @@ -0,0 +1,16 @@ +// The rc engine's stale-cache error, the error-code parity table's row for it +// (src/__tests__/error-code-parity.test.ts lists every typed error where mn +// throws it; this one is the engine's own). +// Approved (Y52): an escaped stale cache reports STALE_CACHE, where it was UNKNOWN. + +import { describe, expect, it } from 'vitest'; +import { classifyError } from '@kuiralabs/midnight-cli-core'; +import { StaleCacheError } from '../facade.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; + +describe("the rc engine's stale cache", () => { + it('reports STALE_CACHE (exit 6) through its code, where the message alone gave UNKNOWN', () => { + const err = new StaleCacheError('applied 120 of 80 events'); + expect(classifyError(err, CORE_CODES)).toStrictEqual({ exitCode: 6, errorCode: 'STALE_CACHE' }); + }); +}); diff --git a/packages/engine-rc/src/__tests__/transfer.test.ts b/packages/engine-rc/src/__tests__/transfer.test.ts new file mode 100644 index 00000000..f8d94019 --- /dev/null +++ b/packages/engine-rc/src/__tests__/transfer.test.ts @@ -0,0 +1,83 @@ +// The rc engine's checks around a transfer: a recipient's address for the +// network, and which SDK failures are a shortage of Dust. + +import { describe, it, expect } from 'vitest'; +import { getNetworkConfig, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; +import { validateRecipientAddress, isDustRelatedError } from '../transfer.ts'; +import { deriveUnshieldedAddress } from '../derive-address.ts'; + +describe('validateRecipientAddress', () => { + const genesisSeed = Buffer.from(GENESIS_SEED, 'hex'); + + it('accepts a valid undeployed address', () => { + const address = deriveUnshieldedAddress(genesisSeed, 'undeployed'); + const config = getNetworkConfig('undeployed'); + expect(() => validateRecipientAddress(address, config)).not.toThrow(); + }); + + it('accepts a valid preprod address', () => { + const address = deriveUnshieldedAddress(genesisSeed, 'preprod'); + const config = getNetworkConfig('preprod'); + expect(() => validateRecipientAddress(address, config)).not.toThrow(); + }); + + it('accepts a valid preview address', () => { + const address = deriveUnshieldedAddress(genesisSeed, 'preview'); + const config = getNetworkConfig('preview'); + expect(() => validateRecipientAddress(address, config)).not.toThrow(); + }); + + it('rejects an address for the wrong network', () => { + const preprodAddr = deriveUnshieldedAddress(genesisSeed, 'preprod'); + const undeployedConfig = getNetworkConfig('undeployed'); + expect(() => validateRecipientAddress(preprodAddr, undeployedConfig)).toThrow('Invalid recipient address'); + }); + + it('rejects a garbage string', () => { + const config = getNetworkConfig('undeployed'); + expect(() => validateRecipientAddress('not-an-address', config)).toThrow('Invalid recipient address'); + }); + + it('rejects an empty string', () => { + const config = getNetworkConfig('undeployed'); + expect(() => validateRecipientAddress('', config)).toThrow('Invalid recipient address'); + }); +}); + +describe('isDustRelatedError', () => { + it('matches "not enough dust" errors', () => { + expect(isDustRelatedError(new Error('Not enough dust to pay fees'))).toBe(true); + }); + + it('matches "dust generated" errors', () => { + expect(isDustRelatedError(new Error('dust generated capacity insufficient'))).toBe(true); + }); + + it('matches "insufficient funds" errors', () => { + expect(isDustRelatedError(new Error('Insufficient funds: dust wallet sync timed out'))).toBe(true); + }); + + it('matches "no dust tokens" errors', () => { + expect(isDustRelatedError(new Error('No dust tokens found in the wallet state'))).toBe(true); + }); + + it('matches transaction submission errors', () => { + expect(isDustRelatedError(new Error('Transaction submission error'))).toBe(true); + }); + + it('matches errors with _tag TransactionInvalidError', () => { + const err = new Error('fail'); + (err as any)._tag = 'TransactionInvalidError'; + expect(isDustRelatedError(err)).toBe(true); + }); + + it('does not match unrelated errors', () => { + expect(isDustRelatedError(new Error('Network timeout'))).toBe(false); + expect(isDustRelatedError(new Error('Invalid address format'))).toBe(false); + }); + + it('handles null/undefined errors', () => { + expect(isDustRelatedError(null)).toBe(false); + expect(isDustRelatedError(undefined)).toBe(false); + }); +}); diff --git a/src/__tests__/wallet-data-repository.test.ts b/packages/engine-rc/src/__tests__/wallet-data-repository.test.ts similarity index 98% rename from src/__tests__/wallet-data-repository.test.ts rename to packages/engine-rc/src/__tests__/wallet-data-repository.test.ts index 160274d0..7456016d 100644 --- a/src/__tests__/wallet-data-repository.test.ts +++ b/packages/engine-rc/src/__tests__/wallet-data-repository.test.ts @@ -10,12 +10,11 @@ import { join } from 'node:path'; import { Buffer } from 'node:buffer'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; -import { testHost } from './helpers/test-host.ts'; -import { UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import type { DustDirectResult } from '@kuiralabs/midnight-engine-rc/dust-direct'; +import { WalletDataRepository, type DustView, type UnshieldedView, type RepoDeps } from '../wallet-data-repository.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; +import { UnsupportedLedgerError, type BalanceSummary } from '@kuiralabs/midnight-chain'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { DustDirectResult } from '../dust-direct.ts'; // ── Test fixtures ───────────────────────────────────────── diff --git a/src/__tests__/wallet-session.test.ts b/packages/engine-rc/src/__tests__/wallet-session.test.ts similarity index 85% rename from src/__tests__/wallet-session.test.ts rename to packages/engine-rc/src/__tests__/wallet-session.test.ts index 16c75fd7..9b6265c5 100644 --- a/src/__tests__/wallet-session.test.ts +++ b/packages/engine-rc/src/__tests__/wallet-session.test.ts @@ -5,18 +5,16 @@ import { describe, it, expect, vi, beforeAll } from 'vitest'; import * as rx from 'rxjs'; import { DustAddress, MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; -import { sessionOver, type WalletSession } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; -import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { deriveShieldedAddress, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; -import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; -import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; +import { sessionOver, type WalletSession, DustRequiredError, TransactionRefusedError, classifyError } from '@kuiralabs/midnight-cli-core'; +import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/engine'; +import { deriveShieldedAddress, deriveUnshieldedAddress } from '../derive-address.ts'; +import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from '../../../../test-support/connector-stub.ts'; +import { createDAppConnector } from '../dapp-connector.ts'; +import { FORK_SCHEDULE } from '../fork-schedule.ts'; +import { agentPaysMerchant, unsealedBytes } from '../../../../test-support/ledger-tx.ts'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; -import { DustRequiredError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; const { WALLET_SHIELDED, WALLET_UNSHIELDED, createBundleStub, mockState } = connectorStub({ createDAppConnector, deriveShieldedAddress, DustAddress, UnshieldedAddress, ledger9ProtocolVersion: FORK_SCHEDULE.v9, @@ -223,7 +221,7 @@ describe('wallet session', () => { expect(err).toBeInstanceOf(TransactionRefusedError); expect((err as Error).message).toBe('The node refused the transaction: 1010: Invalid Transaction: Custom error: 115'); - expect(classifyError(err as Error, installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + expect(classifyError(err as Error, CORE_CODES)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); await session.close(); }); @@ -237,7 +235,7 @@ describe('wallet session', () => { expect(err).toBeInstanceOf(DustRequiredError); expect((err as Error).message).toContain("The wallet has no Dust available that covers this transaction's fee (No dust tokens found in the wallet state)"); - expect(classifyError(err as Error, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + expect(classifyError(err as Error, CORE_CODES)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); await session.close(); } finally { vi.useRealTimers(); @@ -245,3 +243,27 @@ describe('wallet session', () => { }); }); }); + +// The error-code parity table's row for a program's wallet session (src/__tests__/error-code-parity.test.ts +// lists every typed error where mn throws it; this one is the rc engine's connector's own). +describe("a program's wallet session, in the error-code parity table", () => { + it('reports a spent coin the node refused as STALE_UTXO, exit 6, as before codes were owned per package', async () => { + const refusal = Effect.runPromise(Effect.fail(new SubmissionError({ message: 'Transaction submission error', cause: new Error('1010: Invalid Transaction: Custom error: 115') }))); + refusal.catch(() => {}); + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({})), submitTransaction: () => refusal }); + (bundle.facade as unknown as { revert: () => Promise }).revert = async () => {}; + const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); + const session = sessionOver('undeployed', { connector, stop: async () => { connector.dispose(); } }, () => []); + const err = await (async () => { + try { + await session.submit(await session.balanceTransaction(Buffer.from(await unsealedBytes(agentPaysMerchant())).toString('hex'))); + return undefined; + } catch (error) { + return error as Error; + } finally { + await session.close(); + } + })(); + expect(classifyError(err!, CORE_CODES)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + }); +}); diff --git a/src/__tests__/wallet-state-to-restore.live.test.ts b/packages/engine-rc/src/__tests__/wallet-state-to-restore.live.test.ts similarity index 86% rename from src/__tests__/wallet-state-to-restore.live.test.ts rename to packages/engine-rc/src/__tests__/wallet-state-to-restore.live.test.ts index ddd8edaf..aa28ea2c 100644 --- a/src/__tests__/wallet-state-to-restore.live.test.ts +++ b/packages/engine-rc/src/__tests__/wallet-state-to-restore.live.test.ts @@ -11,13 +11,11 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; -import { dustPublicKeyHexFromSeed, saveDustCache } from '@kuiralabs/midnight-engine-rc/dust-direct-cache'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { WalletDataRepository } from '../wallet-data-repository.ts'; +import { dustPublicKeyHexFromSeed, saveDustCache } from '../dust-direct-cache.ts'; +import { type NetworkConfig, parseArgs, resolveNetwork } from '@kuiralabs/midnight-cli-core'; import { DUST_STATE_OWNED_HEX } from './fixtures/dust-state-owned.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; let NETWORK: NetworkConfig; diff --git a/packages/engine-rc/src/addresses.ts b/packages/engine-rc/src/addresses.ts index e103402b..8d9044c8 100644 --- a/packages/engine-rc/src/addresses.ts +++ b/packages/engine-rc/src/addresses.ts @@ -2,8 +2,8 @@ // must be on. import { MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; -import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/engine'; +import type { NetworkName } from '@kuiralabs/midnight-cli-core'; /** A shielded address on `network`, as the SDK reads it. Throws when it is not one. */ export function decodeShieldedAddress(address: string, network: NetworkName): ShieldedAddress { diff --git a/packages/engine-rc/src/airdrop.ts b/packages/engine-rc/src/airdrop.ts index e8944c0d..c2be1f0a 100644 --- a/packages/engine-rc/src/airdrop.ts +++ b/packages/engine-rc/src/airdrop.ts @@ -2,13 +2,11 @@ // devnet. `mn airdrop` and `mn dev` both fund wallets through here; the // caller has already checked that the network is the local one. -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { EngineError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { EngineError, toEngineError, type AirdropParams } from '@kuiralabs/midnight-cli-core/engine'; +import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; import { executeTransfer, type TransferParams, type TransferResult } from './transfer.ts'; -import type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -export type { AirdropParams } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { AirdropParams } from '@kuiralabs/midnight-cli-core/engine'; /** Sends `amount` micro-NIGHT from genesis to `recipientAddress`, on the engine's repository `repo`. */ diff --git a/packages/engine-rc/src/contract-providers.ts b/packages/engine-rc/src/contract-providers.ts index dd94b435..32c32d60 100644 --- a/packages/engine-rc/src/contract-providers.ts +++ b/packages/engine-rc/src/contract-providers.ts @@ -2,9 +2,8 @@ // Deploy/call use the runner (generated scripts in dApp context) which build their own providers. import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; -import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/engine'; +import { assertEndpointUsable, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; import { describeRawState } from './raw-state.ts'; /** diff --git a/packages/engine-rc/src/contract-scripts.ts b/packages/engine-rc/src/contract-scripts.ts index 584d55e0..b1b64cc0 100644 --- a/packages/engine-rc/src/contract-scripts.ts +++ b/packages/engine-rc/src/contract-scripts.ts @@ -8,8 +8,8 @@ import { existsSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; -import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/engine'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; /** * Every package a generated script imports, and the compact runtime the diff --git a/packages/engine-rc/src/dapp-connector.ts b/packages/engine-rc/src/dapp-connector.ts index 93047ec0..a37a3fb2 100644 --- a/packages/engine-rc/src/dapp-connector.ts +++ b/packages/engine-rc/src/dapp-connector.ts @@ -2,39 +2,21 @@ // Factory function returns a handler map for ws-rpc.ts to dispatch import * as rx from 'rxjs'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { type ApprovalOptions, promptApproval, createPhaseTracker, type PhaseTracker, toHex, fromHex, getNetworkId, isDustShortage, markingEngineCodes, ProofTimeoutError, DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits, assertSpendsNoOfferCoin, NotAnOfferError, describeLeg, decodeSignPayload, signedMessageBytes, DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan, TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS, type DAppConnector, type DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/engine'; +import { type NoticeSink, LEDGER_9_FORK_VERSION, type NetworkConfig, createApiError, type RpcHandler, type RpcHandlerContext, type OpenOffer, formatWait, OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core'; +import { dim, roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui'; import { MidnightBech32m, UnshieldedAddress, ShieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; import type { TransactionStage, WalletTransaction } from '@midnightntwrk/wallet-sdk'; import type { FacadeState, WalletEntry } from '@midnightntwrk/wallet-sdk/facade'; import type { FinalizedTx } from '@midnightntwrk/wallet-sdk'; import { type FacadeBundle, hasDustAvailable } from './facade.ts'; -import { LEDGER_9_FORK_VERSION, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { createApiError, type RpcHandler, type RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { createPhaseTracker, type PhaseTracker } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; -import { toHex, fromHex } from '@kuiralabs/midnight-cli-core/lib/tx-serde'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import { isDustShortage, markingEngineCodes } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { ProofTimeoutError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { DEFAULT_FEE_LIMITS, feeLimitRefusal, pendingLimitRefusal, type FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; import { inspectTxHex } from './tx-inspect.ts'; import { readOffer, spentNullifiers } from './offer-reader.ts'; -import { assertSpendsNoOfferCoin, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import { NotAnOfferError, describeLeg } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; import { expiredIntents, feeOnlyRefusals, readDAppTransaction, type DAppTxStage, type FeeCheckTransaction } from './fee-only-check.ts'; import { PartlySignedTransactionError, assertSignable, signRecipe } from './sign-recipe.ts'; -import { decodeSignPayload, signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; -import { DUST_SHORT_WAIT_MS, planDustWait, sleep, type DustWaitPlan } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; -import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { fetchPartialSuccessSegments, type SegmentResult } from '@kuiralabs/midnight-chain/lib/tx-segments'; -import { walletsBelowLedger9 } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_RETRY_ATTEMPTS, DUST_RETRY_DELAY_MS, ABANDONED_TX_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { roughDust, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { fetchPartialSuccessSegments, type SegmentResult, walletsBelowLedger9 } from '@kuiralabs/midnight-chain'; +export type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/engine'; // ── Types ── @@ -151,8 +133,7 @@ function extractErrorDetail(err: unknown): string { return deduped.join(' → ') || 'Unknown error'; } -export { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; +export { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core'; /** The connector API's history entry for one wallet history entry. */ export type HistoryEntry = { diff --git a/packages/engine-rc/src/derive-address.ts b/packages/engine-rc/src/derive-address.ts index 7a6cb8c7..deef6668 100644 --- a/packages/engine-rc/src/derive-address.ts +++ b/packages/engine-rc/src/derive-address.ts @@ -10,9 +10,9 @@ import { ShieldedEncryptionPublicKey, } from '@midnightntwrk/wallet-sdk/address-format'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { type NetworkName, getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; +import { networkIdForName } from '@kuiralabs/midnight-cli-core/engine'; +import { type NetworkName, getValidNetworkNames } from '@kuiralabs/midnight-cli-core'; import { deriveShieldedSeed } from './derivation.ts'; -import { networkIdForName } from '@kuiralabs/midnight-cli-core/lib/network-id'; /** * Derive an unshielded address from a seed buffer, network, and optional key index. diff --git a/packages/engine-rc/src/dust-direct-cache.ts b/packages/engine-rc/src/dust-direct-cache.ts index 7bda17bb..1f07d0c2 100644 --- a/packages/engine-rc/src/dust-direct-cache.ts +++ b/packages/engine-rc/src/dust-direct-cache.ts @@ -14,10 +14,10 @@ import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { dustCacheDir, getDustCachePath } from '@kuiralabs/midnight-cli-core/engine'; +import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core'; import { deriveDustSeed } from './derivation.ts'; import { type DustRetention } from './dust-direct.ts'; -import { dustCacheDir, getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; // v2 added the retention fields (owned generation indices + frontier) that the // generation-tree collapse needs. v1 caches lack them and are invalidated, so diff --git a/packages/engine-rc/src/dust-direct.ts b/packages/engine-rc/src/dust-direct.ts index 3d901581..d5d90df7 100644 --- a/packages/engine-rc/src/dust-direct.ts +++ b/packages/engine-rc/src/dust-direct.ts @@ -12,12 +12,8 @@ import WebSocket from 'ws'; import * as ledger from '@midnightntwrk/ledger-v9'; import { collapseForeignGenerations } from './dust-collapse.ts'; -import { - INITIAL_NIGHT_DUST_RATIO, - INITIAL_GENERATION_DECAY_RATE, - INITIAL_DUST_GRACE_PERIOD_SECONDS, -} from '@kuiralabs/midnight-cli-core/lib/constants'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { INITIAL_NIGHT_DUST_RATIO, INITIAL_GENERATION_DECAY_RATE, INITIAL_DUST_GRACE_PERIOD_SECONDS } from '@kuiralabs/midnight-cli-core/engine'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain'; // MN_DISABLE_DUST_COLLAPSE=1 disables the dust generation-tree collapse (debugging / safety valve): the repository then passes `collapse: false`, read from its host's settings. diff --git a/packages/engine-rc/src/dust-export.ts b/packages/engine-rc/src/dust-export.ts index 8524107e..8aeee77b 100644 --- a/packages/engine-rc/src/dust-export.ts +++ b/packages/engine-rc/src/dust-export.ts @@ -19,12 +19,10 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { buildFacade, stopFacade, overlayDustDirectSnapshot } from './facade.ts'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import type { DustExportResult } from '@kuiralabs/midnight-cli-core/engine'; +import type { NetworkConfig, VerboseLog, NoticeSink } from '@kuiralabs/midnight-cli-core'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; -import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustExportResult } from '@kuiralabs/midnight-cli-core/engine'; export interface DustExportOptions { diff --git a/packages/engine-rc/src/dust-register.ts b/packages/engine-rc/src/dust-register.ts index ce6cc699..4ed0c03f 100644 --- a/packages/engine-rc/src/dust-register.ts +++ b/packages/engine-rc/src/dust-register.ts @@ -2,14 +2,11 @@ // Dust to spend. `mn dust register` and `mn dev` both register through here. import { waitForLiteSyncedState } from './facade.ts'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/engine'; +import { throwIfCancelled, type NetworkConfig, type CallSdkWarnings, type VerboseLog } from '@kuiralabs/midnight-cli-core'; import { ensureDust } from './transfer.ts'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { DustRegisterOptions, DustRegistration } from '@kuiralabs/midnight-cli-core/engine'; /** Registers a seed's NIGHT for Dust on the engine's repository `repo`, unless it has Dust already. */ diff --git a/packages/engine-rc/src/dust-sync-native.ts b/packages/engine-rc/src/dust-sync-native.ts index 8434bf70..04c70e76 100644 --- a/packages/engine-rc/src/dust-sync-native.ts +++ b/packages/engine-rc/src/dust-sync-native.ts @@ -4,7 +4,8 @@ // fails, callers fall back to the WASM path — the sidecar is an optional // accelerator, never a hard dependency. -import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { cacheRootDir, networkCacheFolder, nativeCheckpointName } from '@kuiralabs/midnight-cli-core/engine'; +import { assertEndpointUsable, DIR_MODE, FILE_MODE, type NetworkConfig, type Settings } from '@kuiralabs/midnight-cli-core'; import { spawn } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; @@ -13,15 +14,10 @@ import { fileURLToPath } from 'node:url'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveDustSeed } from './derivation.ts'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { type DustDirectResult, type DustRetention } from './dust-direct.ts'; import { collapseForeignGenerations } from './dust-collapse.ts'; import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import type { Settings } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { cacheRootDir, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { nativeCheckpointName } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; /** Sidecar checkpoint JSON shape (snake_case — matches the Rust `Checkpoint`). */ export interface SidecarCheckpoint { diff --git a/packages/engine-rc/src/dust-wallet.ts b/packages/engine-rc/src/dust-wallet.ts index b011a7f4..ef684fa6 100644 --- a/packages/engine-rc/src/dust-wallet.ts +++ b/packages/engine-rc/src/dust-wallet.ts @@ -13,8 +13,7 @@ import { CustomForkingDustWallet, DustWallet as SdkDustWallet, asV8DustParameter import { V1Builder } from '@midnightntwrk/wallet-sdk/dust/v1'; import { Migration, Transacting, V2Builder, WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; import { LedgerOps } from '@midnightntwrk/wallet-sdk/utilities'; -import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs } from '@kuiralabs/midnight-cli-core/lib/dust-balancing-plan'; -import { type DustShortfall, withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { type DustInput, chooseDustCoins, planDustInputs, spreadFeeAcrossInputs, type DustShortfall, withDustShortfall } from '@kuiralabs/midnight-cli-core/engine'; type SdkTransacting = Transacting.TransactingCapabilityImplementation; type RecipeArguments = Parameters; diff --git a/packages/engine-rc/src/facade.ts b/packages/engine-rc/src/facade.ts index 68b2d9cd..acb83845 100644 --- a/packages/engine-rc/src/facade.ts +++ b/packages/engine-rc/src/facade.ts @@ -1,5 +1,6 @@ import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; +import { getNetworkId, type WalletCacheData, DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, SYNC_TIMEOUT_MS, PRE_SEND_SYNC_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/engine'; +import { type NoticeSink, type NetworkConfig, type VerboseLog, CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { UnshieldedWallet, createKeystore, @@ -18,22 +19,10 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import * as rx from 'rxjs'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { FORK_SCHEDULE } from './fork-schedule.ts'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; -import { type WalletCacheData } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; -import { - DUST_COST_OVERHEAD, - DUST_FEE_BLOCKS_MARGIN, - SYNC_TIMEOUT_MS, - PRE_SEND_SYNC_TIMEOUT_MS, -} from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { assertNetworkAnswers } from '@kuiralabs/midnight-chain/lib/endpoint-check'; -import { isStreamEmpty } from '@kuiralabs/midnight-chain/lib/event-tip'; -import { CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { assertNetworkAnswers, isStreamEmpty } from '@kuiralabs/midnight-chain'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index 22e01ff4..a271be3c 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -4,8 +4,7 @@ import { readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { type Engine, type EngineHost, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/engine'; import * as ledger from '@midnightntwrk/ledger-v9'; import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; diff --git a/packages/engine-rc/src/ledger-parameters.ts b/packages/engine-rc/src/ledger-parameters.ts index decf682d..17a645a1 100644 --- a/packages/engine-rc/src/ledger-parameters.ts +++ b/packages/engine-rc/src/ledger-parameters.ts @@ -3,7 +3,7 @@ // normalizeFullness: normalized = value / limit, so limit = value / normalized. import * as ledger from '@midnightntwrk/ledger-v9'; -import type { BlockLimits } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { BlockLimits } from '@kuiralabs/midnight-cli-core/engine'; type Dimension = keyof BlockLimits; diff --git a/packages/engine-rc/src/offer-reader.ts b/packages/engine-rc/src/offer-reader.ts index a0baa7d2..00b94fc3 100644 --- a/packages/engine-rc/src/offer-reader.ts +++ b/packages/engine-rc/src/offer-reader.ts @@ -6,7 +6,8 @@ import { createHash } from 'node:crypto'; import { Transaction } from '@midnightntwrk/ledger-v9'; -import { NotAnOfferError, type OfferContents } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/engine'; +import type { OfferContents } from '@kuiralabs/midnight-cli-core'; export function readOffer(txHex: string): OfferContents { if (!/^(?:[0-9a-fA-F]{2})+$/.test(txHex)) throw new NotAnOfferError('it is not hex'); diff --git a/packages/engine-rc/src/raw-state.ts b/packages/engine-rc/src/raw-state.ts index 93b18a95..b7400982 100644 --- a/packages/engine-rc/src/raw-state.ts +++ b/packages/engine-rc/src/raw-state.ts @@ -3,7 +3,7 @@ // layout the fields have no names, so cells show their field-aligned bytes in // hex and maps show their size, as the parsed state does. -import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { RawStateValue } from '@kuiralabs/midnight-cli-core/engine'; const toHex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); diff --git a/packages/engine-rc/src/shielded-direct-cache.ts b/packages/engine-rc/src/shielded-direct-cache.ts index 40f4c6f4..dc15d11b 100644 --- a/packages/engine-rc/src/shielded-direct-cache.ts +++ b/packages/engine-rc/src/shielded-direct-cache.ts @@ -9,18 +9,17 @@ // Security: the cached state contains owned coins but NOT the secret keys. Same // sensitivity as the wallet file (mode 0o600). -import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; +import { bindCachesToIndexer, getShieldedCachePath, type ShieldedBalanceResult, type ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/engine'; +import { DIR_MODE, FILE_MODE, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core'; import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, renameSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { randomBytes } from 'node:crypto'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; import { deriveShieldedSeed } from './derivation.ts'; import { readShieldedBalanceDirect, type ShieldedDirectOptions } from './shielded-direct.ts'; -import { fetchEventTip, isCursorBeyondTip } from '@kuiralabs/midnight-chain/lib/event-tip'; -import { clearShieldedDirectCache, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { fetchEventTip, isCursorBeyondTip } from '@kuiralabs/midnight-chain'; // v2: ledger-9 states replace ledger-8 ones. Dev-preset localnets share a genesis // hash, so the chain-id guard can't keep a ledger-8 cache off a ledger-9 chain. @@ -123,8 +122,7 @@ export function saveShieldedCache( } -export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { ShieldedBalanceResult, ShieldedCachedOptions } from '@kuiralabs/midnight-cli-core/engine'; /** * Read a wallet seed's shielded balances, using (and refreshing) the diff --git a/packages/engine-rc/src/shielded-direct.ts b/packages/engine-rc/src/shielded-direct.ts index 7dd56013..bde47bf3 100644 --- a/packages/engine-rc/src/shielded-direct.ts +++ b/packages/engine-rc/src/shielded-direct.ts @@ -14,7 +14,7 @@ import * as ledger from '@midnightntwrk/ledger-v9'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; +import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain'; const SUBSCRIPTION_QUERY = ` subscription ZswapLedgerEvents($id: Int) { diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index a038ae52..10136b34 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -2,31 +2,15 @@ // Handles: facade lifecycle, sync, balance check, dust, tx build/sign/prove/submit, retries import * as ledger from '@midnightntwrk/ledger-v9'; -import { DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { ProofTimeoutError, getNetworkId, TOKEN_MULTIPLIER, TX_TTL_MINUTES, PROOF_TIMEOUT_MS, DUST_TIMEOUT_MS, MAX_RETRY_ATTEMPTS, STALE_UTXO_ERROR_CODE, DUST_REGISTRATION_TIMEOUT_MS, DUST_REGISTRATION_RETRY_DELAY_MS, SYNC_ATTEMPT_TIMEOUT_MS, DUST_COST_OVERHEAD, MIN_DUST_FOR_TRANSFER, isColdStartRace, isDustRelatedError, DustFeeNotGeneratedError, planRegistration, awaitDustForFee, sleep, type EnsureDustResult, type TransferParams, type TransferResult } from '@kuiralabs/midnight-cli-core/engine'; +import { DustRequiredError, InsufficientBalanceError, SyncTimeoutError, throwIfCancelled, type NetworkConfig, type VerboseLog, nightAmountText, NATIVE_TOKEN_TYPE, formatWait, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; +import { toDust } from '@kuiralabs/midnight-cli-core/ui'; import { MidnightBech32m, UnshieldedAddress, type DustAddress } from '@midnightntwrk/wallet-sdk/address-format'; import { type FacadeState, type UtxoWithMeta } from '@midnightntwrk/wallet-sdk/facade'; import * as rx from 'rxjs'; -import { type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; import { type FacadeBundle, hasDustAvailable, quickSync } from './facade.ts'; import type { WalletDataRepository } from './wallet-data-repository.ts'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import { nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; -import { - NATIVE_TOKEN_TYPE, - TOKEN_MULTIPLIER, - TX_TTL_MINUTES, - PROOF_TIMEOUT_MS, - DUST_TIMEOUT_MS, - MAX_RETRY_ATTEMPTS, - STALE_UTXO_ERROR_CODE, - DUST_REGISTRATION_TIMEOUT_MS, - DUST_REGISTRATION_RETRY_DELAY_MS, - SYNC_ATTEMPT_TIMEOUT_MS, - DUST_COST_OVERHEAD, - MIN_DUST_FOR_TRANSFER, -} from '@kuiralabs/midnight-cli-core/lib/constants'; @@ -53,19 +37,12 @@ export function validateRecipientAddress(address: string, networkConfig: Network // SDK error classifiers moved to ./sdk-errors.ts so wallet-data-repository // can import them without a circular dependency. Re-exported for callers // that still import from this module. -export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { isColdStartRace, isDustRelatedError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; -import { formatWait } from '@kuiralabs/midnight-cli-core/lib/duration'; -import { assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain/lib/chain-clock'; -import { awaitDustForFee, sleep } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; +export { isDustRelatedError, isSdkInsufficientFundsError } from '@kuiralabs/midnight-cli-core/engine'; +import { assertChainClockCurrent, fetchChainTime } from '@kuiralabs/midnight-chain'; /** How long the transfer retry waits for Dust to grow when the fee is above the pre-flight threshold. */ const DUST_GROW_WAIT_MS = 10_000; -import { toDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { EnsureDustResult, TransferParams, TransferResult } from '@kuiralabs/midnight-cli-core/engine'; /** Format milliseconds as "Xs" or "Xm Ys" for human-friendly elapsed display. */ diff --git a/packages/engine-rc/src/tx-inspect.ts b/packages/engine-rc/src/tx-inspect.ts index 9f0c302d..2a740574 100644 --- a/packages/engine-rc/src/tx-inspect.ts +++ b/packages/engine-rc/src/tx-inspect.ts @@ -2,7 +2,7 @@ // Used by the DApp Connector approval prompt to show Lace-style transaction summaries import { Transaction } from '@midnightntwrk/ledger-v9'; -import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/engine'; /** * Try to extract structured details from a transaction hex string. diff --git a/packages/engine-rc/src/wallet-data-repository.ts b/packages/engine-rc/src/wallet-data-repository.ts index ee1cb7a9..dd3bf9a5 100644 --- a/packages/engine-rc/src/wallet-data-repository.ts +++ b/packages/engine-rc/src/wallet-data-repository.ts @@ -18,11 +18,10 @@ // tests against localnet — accepted scope per architecture-deepening.md. import { Buffer } from 'node:buffer'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { isColdStartRace, loadWalletCache, saveWalletCache, clearWalletCache, validateWalletCacheChainId, type WalletCacheData, bindCachesToIndexer, describeIndexerChange, type CachedReadOptions, type DustBalance, type EngineHost, type ReadOptions, type UnshieldedView } from '@kuiralabs/midnight-cli-core/engine'; +import { throwIfCancelled, type NetworkConfig, type NetworkName, isValidNetworkName, clearDustDirectCache, type VerboseLog, type NoticeSink } from '@kuiralabs/midnight-cli-core'; import * as ledger from '@midnightntwrk/ledger-v9'; -import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { isValidNetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; import { type FacadeState } from '@midnightntwrk/wallet-sdk/facade'; import { buildFacade, @@ -33,30 +32,13 @@ import { type SyncMode, overlayDustDirectSnapshot, } from './facade.ts'; -import { isColdStartRace } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { loadDustCache, saveDustCache, dustPublicKeyHexFromSeed, validateDustCacheChainId } from './dust-direct-cache.ts'; -import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { - loadWalletCache, - saveWalletCache, - clearWalletCache, - validateWalletCacheChainId, - type WalletCacheData, -} from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { getChainGenesisHash } from '@kuiralabs/midnight-chain/lib/chain-id'; -import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { checkBalance, type BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { getChainGenesisHash, assertLedgerSupported, fetchProtocolVersion, checkBalance, type BalanceSummary, callNodeRpc, fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain'; import { readDustBalanceDirect, type DustDirectResult, type DustRetention } from './dust-direct.ts'; -import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { nativeDustSyncAvailable, runDustSyncNative } from './dust-sync-native.ts'; -import type { VerboseLog } from '@kuiralabs/midnight-cli-core/lib/verbose'; -import type { NoticeSink } from '@kuiralabs/midnight-cli-core/lib/notices'; -import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; import { deriveDustSeed } from './derivation.ts'; import { deriveUnshieldedAddress } from './derive-address.ts'; -import { fetchEventTip, isCursorBeyondTip, type LedgerEventStream } from '@kuiralabs/midnight-chain/lib/event-tip'; -import type { CachedReadOptions, DustBalance, EngineHost, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; -export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/lib/engine'; +export type { CachedReadOptions, DustBalance, ReadOptions, UnshieldedView } from '@kuiralabs/midnight-cli-core/engine'; // ── Public types ────────────────────────────────────────── diff --git a/packages/engine-rc/src/wallet.ts b/packages/engine-rc/src/wallet.ts index 008da50e..0f03e2c7 100644 --- a/packages/engine-rc/src/wallet.ts +++ b/packages/engine-rc/src/wallet.ts @@ -4,26 +4,13 @@ // themselves before the SDK moved behind the engine. import { deriveUnshieldedAddress } from './derive-address.ts'; -import { assertSpendsNoOfferCoin, readOpenOffers } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { assertSpendsNoOfferCoin, type DAppConnector, type EngineWallet, type OpenedConnector, type PrepWallet, type ServedWalletSession, type ShieldedTransferParams, reportingEngineErrors, getNetworkId, bindCachesToIndexer, describeIndexerChange, loadWalletCache, saveWalletCache, DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/engine'; +import { readOpenOffers, InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; +import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui'; import { spentNullifiers } from './offer-reader.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; import { MidnightBech32m } from '@midnightntwrk/wallet-sdk/address-format'; -import type { - DAppConnector, - EngineWallet, - OpenedConnector, - PrepWallet, - ServedWalletSession, - ShieldedTransferParams, -} from '@kuiralabs/midnight-cli-core/lib/engine'; -import { InsufficientBalanceError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { reportingEngineErrors } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { getNetworkId } from '@kuiralabs/midnight-cli-core/lib/network-id'; -import { bindCachesToIndexer, describeIndexerChange } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; -import { loadWalletCache, saveWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { DUST_SHORT_WAIT_MS, payWhenDustCovers } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; -import { assertLedgerSupported } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { trackElapsed } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { assertLedgerSupported } from '@kuiralabs/midnight-chain'; import { decodeShieldedAddress } from './addresses.ts'; import { buildFacade, hasDustAvailable, isFacadeSynced, startAndSyncFacade, stopFacade, waitForDustAvailable } from './facade.ts'; import { ensureDust, executeTransfer } from './transfer.ts'; diff --git a/packages/engine-rc/tsconfig.build.json b/packages/engine-rc/tsconfig.build.json index 16f7d7d6..267c2417 100644 --- a/packages/engine-rc/tsconfig.build.json +++ b/packages/engine-rc/tsconfig.build.json @@ -24,5 +24,9 @@ }, "include": [ "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" ] } diff --git a/scripts/api-report.mjs b/scripts/api-report.mjs index 808478fe..9e500558 100644 --- a/scripts/api-report.mjs +++ b/scripts/api-report.mjs @@ -2,7 +2,9 @@ // Each public package's API, as a report checked in beside it: every module a // program can import through the package's exports map, with the declarations // it exports (functions, types, classes, constants and their signatures), as -// TypeScript emits them, without comments. A change to an export shows in the +// TypeScript emits them, without comments. An entry point that is a barrel +// (only `export { … } from` lists) shows each name it exports, resolved by the +// type checker to the declaration in the module that defines it. A change to an export shows in the // report's diff, and the suite fails until the report is written again. // // Usage: @@ -14,6 +16,7 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import ts from 'typescript'; +import { barrelExports } from './check-layering.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); @@ -26,8 +29,8 @@ export function reportPath(dir) { } /** - * The modules the exports map lets a program import, as [subpath, source file] - * pairs: a subpath pattern (`./*`) stands for every source module it matches. + * The entry points the exports map lets a program import, as [subpath, source + * file] pairs: a subpath pattern (`./*`) stands for every source module it matches. */ function entryModules(pkgDir, srcFiles) { const pkg = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')); @@ -68,7 +71,48 @@ function emitDeclarations(pkgDir) { }, undefined, true); const errors = result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); if (errors.length > 0) throw new Error(ts.formatDiagnostics(errors, { getCanonicalFileName: (f) => f, getCurrentDirectory: () => pkgDir, getNewLine: () => '\n' })); - return { declarations, srcFiles: parsed.fileNames }; + return { program, declarations, srcFiles: parsed.fileNames }; +} + +const DECLARATION_KINDS = [ts.SyntaxKind.FunctionDeclaration, ts.SyntaxKind.ClassDeclaration, ts.SyntaxKind.InterfaceDeclaration, ts.SyntaxKind.TypeAliasDeclaration, ts.SyntaxKind.EnumDeclaration, ts.SyntaxKind.ModuleDeclaration]; + +/** + * The statements of an emitted declaration file that declare `name` (a + * function's overloads, a merged interface's parts), or the re-export of it + * from another package. + */ +function statementsDeclaring(text, name) { + const file = ts.createSourceFile('x.d.ts', text, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS); + const found = file.statements.filter((statement) => { + if (ts.isVariableStatement(statement)) return statement.declarationList.declarations.some((d) => ts.isIdentifier(d.name) && d.name.text === name); + return DECLARATION_KINDS.includes(statement.kind) && statement.name?.text === name; + }); + if (found.length > 0) return found.map((statement) => printer.printNode(ts.EmitHint.Unspecified, statement, file)); + const reExport = file.statements.find((statement) => ts.isExportDeclaration(statement) && statement.moduleSpecifier !== undefined && statement.exportClause !== undefined && ts.isNamedExports(statement.exportClause) && statement.exportClause.elements.some((element) => element.name.text === name)); + return reExport === undefined ? [] : [`export ${reExport.isTypeOnly ? 'type ' : ''}{ ${name} } from ${reExport.moduleSpecifier.getText(file)};`]; +} + +/** + * The declarations a barrel exports, walked with the type checker: each name + * resolved to the module that defines it, and printed from that module's + * emitted declarations, in the barrel's order. + */ +function barrelDeclarations(program, declarations, barrel) { + const checker = program.getTypeChecker(); + const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(barrel)); + const printed = []; + for (const exported of checker.getExportsOfModule(moduleSymbol)) { + const symbol = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported; + if (symbol.name !== exported.name) throw new Error(`${relative(ROOT, barrel)} exports ${symbol.name} as ${exported.name}: a barrel re-exports each name as it is`); + // A name another package defines is shown as re-exported by the module the barrel lists. + const declared = symbol.declarations?.[0]?.getSourceFile().fileName; + const definer = declarations.has(declared) ? declared : barrelExports(barrel).get(exported.name)?.file; + const text = definer === undefined ? undefined : declarations.get(definer); + const statements = text === undefined ? [] : statementsDeclaring(text, symbol.name); + if (statements.length === 0) throw new Error(`${relative(ROOT, barrel)}: no declaration found for ${exported.name}`); + printed.push(...statements); + } + return printed.join('\n'); } const printer = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed }); @@ -83,12 +127,12 @@ function normalise(text) { export function apiReport(dir) { const pkgDir = join(ROOT, 'packages', dir); const name = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')).name; - const { declarations, srcFiles } = emitDeclarations(pkgDir); - let report = `# API report: ${name}\n\nGenerated by \`node scripts/api-report.mjs write\` from the code: every module the exports map makes importable, with what it exports. Don't edit it by hand.\n`; + const { program, declarations, srcFiles } = emitDeclarations(pkgDir); + let report = `# API report: ${name}\n\nGenerated by \`node scripts/api-report.mjs write\` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand.\n`; for (const [subpath, source] of entryModules(pkgDir, srcFiles)) { const text = declarations.get(source); if (text === undefined) throw new Error(`${name}: export ${subpath} has no declarations (${relative(ROOT, source)})`); - const body = normalise(text); + const body = barrelExports(source) === undefined ? normalise(text) : barrelDeclarations(program, declarations, source); report += `\n## \`${name}${subpath === '.' ? '' : subpath.slice(1)}\`\n\n` + (body === '' ? '(exports nothing)\n' : '```ts\n' + body + '\n```\n'); } return report; diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index 1e3c5480..da773e11 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -4,12 +4,36 @@ export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; export function importRule(fromRel: string, toRel: string): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; +/** The imports of a test file that break a rule: a test imports its own package relatively, every other by an entry point. */ +export function testProblems(file: string): { home: string; rule: string; where: string; specifier: string }[]; +/** The TypeScript files of every `__tests__` folder, the layering check's own fixtures left out. */ +export function testFiles(): string[]; +/** The TypeScript files of test-support/. */ +export function testSupportFiles(): string[]; +/** The imports of a test-support file that break a rule: packages by entry point only, and of mn's code only lib/installed-engines.ts. */ +export function testSupportProblems(file: string): { home: string; rule: string; where: string; specifier: string }[]; +/** The repository's scripts (scripts/*.ts and *.mjs), those the scan leaves out (with why) excepted. */ +export function scriptFiles(): string[]; /** The workspace packages carved out of src/: their names and source folders. */ -export const WORKSPACE_PACKAGES: readonly { name: string; dir: string; prefix?: string }[]; +export const WORKSPACE_PACKAGES: readonly { name: string; root: string; dir: string; prefix?: string; home: string }[]; +/** The entry points a workspace package's exports map lists. */ +export function entryPoints(pkg: { name: string; root: string }): string[]; +/** The source file a workspace package's subpath names through its exports map; undefined when the map lacks it. */ +export function entrySource(pkg: { name: string; root: string }, subpath: string): string | undefined; /** A file's path as the homes read it: under its package's source folder, or under src/. */ export function relOf(file: string): string; -/** A file's imports: each specifier, its line, whether it is an `import()`, and whether it brings in types alone. */ -export function importsOf(file: string): { specifier: string; line: number; dynamic: boolean; typeOnly: boolean }[]; -/** The source file an import of `file` names; undefined for an outside package. */ +/** A name an import brings in, and whether it is a type alone. */ +export interface ImportedName { name: string; typeOnly: boolean } +/** An import of a file. */ +export interface FileImport { specifier: string; line: number; dynamic: boolean; typeOnly: boolean; names: ImportedName[] | null } +/** A file's imports: each specifier, its line, whether it is an `import()`, whether it brings in types alone, and the names it brings in (null for a whole module). */ +export function importsOf(file: string): FileImport[]; +/** The source file an import of `file` names; undefined for an outside package, or a subpath a workspace package's exports map lacks. */ export function importTarget(file: string, specifier: string): string | undefined; +/** The TypeScript source an import's target is, with its .ts or index.ts filled in; undefined for a file that isn't there. */ +export function tsSourceOf(target: string): string | undefined; +/** A barrel's re-exports (exported name → the module defining it and its name there); undefined for a module that is not a barrel. */ +export function barrelExports(file: string): Map | undefined; +/** The modules an import brings in (through a barrel, the modules defining its names); { refused } for a deep import; undefined for an outside package. */ +export function importedModules(file: string, imported: Pick): { modules: { file: string; typeOnly: boolean }[]; refused?: undefined } | { refused: string[]; modules?: undefined } | undefined; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index a0fbf591..cfa69890 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -9,18 +9,46 @@ // and the MCP server dispatch to one. A package's codes file is data, not a // command: a package below lends its sets of codes to the definitions above. // +// A workspace package is imported by its entry points only: an import of +// `@kuiralabs//` resolves through that package's exports map, +// and a subpath the map lacks is a deep import, refused. An import of an entry +// point that is a barrel (only `export { … } from` lists) is judged by the +// modules defining the names it imports, so the rules above hold through it. +// Tests (`__tests__`) and scripts/*.{ts,mjs} are scanned too: a test imports +// its own package relatively and every other package by entry point; a script +// imports a package by entry point. A test of a package's internals lives in +// that package. test-support/ holds what tests of several packages share (the +// suites both engines run, the test host, stand-in servers); it is published +// with nothing. Any test may import it; it imports a package by entry point +// only, and of mn's own code only the shell's list of engines, which the test +// host makes its engines with. +// // Usage: node scripts/check-layering.mjs // Imported, it exports sourceFiles and homeOf: which package each file of src/ is in; // importRule and guidanceRule: the rule an import breaks; findLayeringProblems, -// which the suite runs; and importsOf and importTarget, a file's imports and the -// files they name (scripts/code-reach.mjs walks them). Exits 1 when a file has no package, or an import breaks a rule. +// which the suite runs, and testProblems, one test file's; importsOf and +// importedModules, a file's imports and the modules they bring in +// (scripts/code-reach.mjs walks them); and the workspace packages' entry +// points (entryPoints, entrySource). Exits 1 when a file has no package, or an import breaks a rule. -import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { codeOnly } from './check-process-safety.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const SRC = join(ROOT, 'src'); +const SCRIPTS = join(ROOT, 'scripts'); +const TEST_SUPPORT = join(ROOT, 'test-support'); +const TEST_SUPPORT_MAY_IMPORT = [join(SRC, 'lib', 'installed-engines.ts')]; + +// Scripts the scan leaves out, each with why. +const UNSCANNED_SCRIPTS = { +}; + +// The layering check's own fixtures: test files that break the rules on +// purpose, which src/__tests__/layering.test.ts checks one by one. +const LAYERING_FIXTURES = join(SRC, '__tests__', 'fixtures', 'layering'); // The packages of the split, in the layering's order. const PACKAGES = ['core', 'chain', 'wallet', 'contract', 'connect', 'swap', 'dev', 'grant']; @@ -31,7 +59,8 @@ const HOMES = [ ['shell', /^wallet\.ts$/], // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], - ['shell', /^lib\/(heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|code-tables)\.ts$/], + // pkg reads mn's own package.json: its name, version and repository. + ['shell', /^lib\/(pkg|heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|code-tables)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], @@ -44,7 +73,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|pkg|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], @@ -119,20 +148,67 @@ const SDK_ERROR_READERS = /^lib\/(sdk-errors|wallet-session|dust-wait)\.ts$/; // import ... from 'x', export ... from 'x', import 'x', import('x'). const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; -// The workspace packages carved out of src/, each with its source folder and -// the home it is. A file's path in a package (lib/argv.ts) reads as it did -// under src/, so the homes and rules above apply to it unchanged. +// The workspace packages carved out of src/, each with its folder, its source +// folder and the home it is. A file's path in a package (lib/argv.ts) reads as +// it did under src/, so the homes and rules above apply to it unchanged. export const WORKSPACE_PACKAGES = [ - { name: '@kuiralabs/midnight-cli-core', dir: join(ROOT, 'packages', 'cli-core', 'src') }, - { name: '@kuiralabs/midnight-chain', dir: join(ROOT, 'packages', 'chain', 'src') }, + { name: '@kuiralabs/midnight-cli-core', root: join(ROOT, 'packages', 'cli-core'), dir: join(ROOT, 'packages', 'cli-core', 'src'), home: 'core' }, + { name: '@kuiralabs/midnight-chain', root: join(ROOT, 'packages', 'chain'), dir: join(ROOT, 'packages', 'chain', 'src'), home: 'chain' }, // The rc engine: its files read as engine/rc/, its index the package itself. - { name: '@kuiralabs/midnight-engine-rc', dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/' }, - { name: '@kuiralabs/midnight-engine-beta', dir: join(ROOT, 'packages', 'engine-beta', 'src'), prefix: 'engine/beta/' }, + { name: '@kuiralabs/midnight-engine-rc', root: join(ROOT, 'packages', 'engine-rc'), dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/', home: 'engine' }, + { name: '@kuiralabs/midnight-engine-beta', root: join(ROOT, 'packages', 'engine-beta'), dir: join(ROOT, 'packages', 'engine-beta', 'src'), prefix: 'engine/beta/', home: 'engine' }, ]; /** The package source folder a file is in, or undefined for one under src/. */ const packageOf = (file) => WORKSPACE_PACKAGES.find((pkg) => file.startsWith(pkg.dir + '/')); +/** The workspace package a specifier names (`@kuiralabs/midnight-cli-core` or a subpath of it), or undefined. */ +const packageNamed = (specifier) => WORKSPACE_PACKAGES.find((p) => specifier === p.name || specifier.startsWith(p.name + '/')); + +/** The subpath of a package a specifier names: `.` for the package itself, `./lib/errors` for `/lib/errors`. */ +const subpathOf = (pkg, specifier) => (specifier === pkg.name ? '.' : `.${specifier.slice(pkg.name.length)}`); + +/** A package's exports map, as its package.json has it now. */ +const exportsOf = (pkg) => JSON.parse(readFileSync(join(pkg.root, 'package.json'), 'utf8')).exports ?? {}; + +/** The source module an export names: the workspace's source condition. */ +function exportSource(pkg, subpath, target) { + const source = typeof target === 'string' ? target : target['midnight-cli-source']; + if (typeof source !== 'string') throw new Error(`${pkg.name}: export ${subpath} names no source module`); + return source; +} + +/** The entry points a workspace package's exports map lists (a pattern such as `./*` among them). */ +export function entryPoints(pkg) { + return Object.keys(exportsOf(pkg)); +} + +/** + * The source file a workspace package's subpath (`.`, `./ui`) names through + * its exports map: an entry of its own, or one a pattern entry (`./*`) matches; + * undefined when the map has no entry for it, which makes an import of it a + * deep import. + */ +export function entrySource(pkg, subpath) { + const map = exportsOf(pkg); + if (map[subpath] !== undefined) return join(pkg.root, exportSource(pkg, subpath, map[subpath])); + for (const [key, target] of Object.entries(map)) { + if (!key.includes('*')) continue; + const [before, after] = key.split('*'); + if (subpath.length <= before.length + after.length || !subpath.startsWith(before) || !subpath.endsWith(after)) continue; + const stem = subpath.slice(before.length, subpath.length - after.length); + return join(pkg.root, exportSource(pkg, key, target).replace('*', stem)); + } + return undefined; +} + +/** Whether a file is one a package's exports map names outright (not through a pattern): an entry point's module. */ +function isEntryModule(file) { + const pkg = packageOf(file); + if (pkg === undefined) return false; + return Object.entries(exportsOf(pkg)).some(([key, target]) => !key.includes('*') && join(pkg.root, exportSource(pkg, key, target)) === file); +} + /** A file's path as the homes read it: under its package's source folder, or under src/. */ export function relOf(file) { const pkg = packageOf(file); @@ -157,9 +233,35 @@ export function sourceFiles(dir) { return files; } +/** The TypeScript files of every `__tests__` folder of src/ and of the workspace packages, the layering check's own fixtures left out. */ +export function testFiles() { + const walk = (dir, inTests) => readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return path === LAYERING_FIXTURES ? [] : walk(path, inTests || name === '__tests__'); + return inTests && name.endsWith('.ts') ? [path] : []; + }); + return [SRC, ...WORKSPACE_PACKAGES.map((pkg) => pkg.dir)].flatMap((dir) => walk(dir, false)); +} + +/** The repository's scripts (scripts/*.ts and *.mjs), those UNSCANNED_SCRIPTS names left out. */ +export function scriptFiles() { + return readdirSync(SCRIPTS).filter((name) => /\.(ts|mjs)$/.test(name) && UNSCANNED_SCRIPTS[name] === undefined).map((name) => join(SCRIPTS, name)); +} + +/** The TypeScript files of test-support/. */ +export function testSupportFiles() { + const walk = (dir) => readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + return statSync(path).isDirectory() ? walk(path) : name.endsWith('.ts') ? [path] : []; + }); + return walk(TEST_SUPPORT); +} + export function homeOf(file) { const rel = relOf(file); - return HOMES.find(([, pattern]) => pattern.test(rel))?.[0]; + const home = HOMES.find(([, pattern]) => pattern.test(rel))?.[0]; + // A package's entry points (its index, its barrels) are its own. + return home ?? (isEntryModule(file) ? packageOf(file).home : undefined); } const isGuidance = (rel) => /\.guidance\.ts$/.test(rel); @@ -215,58 +317,242 @@ function isTypeOnly(source, match) { return start >= 0 && /^(import|export)\s+type\s/.test(source.slice(start, match.index)); } -/** A file's imports: each specifier, its line, whether it is an `import()`, and whether it brings in types alone. */ +/** + * The names an import brings in, each with whether it is a type alone, read + * from the code (`code`, with strings and comments blanked): `import { a, type + * B } from`, `import x from` (default), `export { a } from`, and for an + * `import()` the names destructured from it or the one read off it. null when + * it brings in a whole module: `import * as`, `export * from`, `import 'x'`, + * or an `import()` used whole. + */ +function importedNames(code, match) { + const at = match.index; + if (match[0].includes('(')) { + const after = code.slice(at + match[0].length); + const read = /^\s*\)\s*\)?\s*\.\s*(\w+)/.exec(after); + if (read !== null) return [{ name: read[1], typeOnly: false }]; + const destructured = /\{([^{}]*)\}\s*=\s*await\s*$/.exec(code.slice(0, at)); + if (destructured === null) return null; + return destructured[1].split(',').map((part) => part.trim()).filter(Boolean).map((part) => ({ name: part.split(':')[0].trim(), typeOnly: false })); + } + if (!/^from\b/.test(match[0])) return null; + const keywords = [...code.slice(0, at).matchAll(/\b(import|export)\b/g)]; + const keyword = keywords[keywords.length - 1]; + if (keyword === undefined) return null; + const clause = code.slice(keyword.index + keyword[0].length, at).trim(); + const allTypes = /^type\s/.test(clause); + const rest = allTypes ? clause.slice(4).trim() : clause; + if (rest.startsWith('*')) return null; + const names = []; + const defaultName = /^(\w+)\s*(,|$)/.exec(rest); + if (defaultName !== null) names.push({ name: 'default', typeOnly: allTypes }); + const braces = /\{([^}]*)\}/.exec(rest); + for (const part of braces === null ? [] : braces[1].split(',')) { + const each = /^(type\s+)?(\w+)(\s+as\s+\w+)?$/.exec(part.trim()); + if (each !== null) names.push({ name: each[2], typeOnly: allTypes || each[1] !== undefined }); + } + return names; +} + +/** + * A file's imports: each specifier, its line, whether it is an `import()`, + * whether it brings in types alone, and the names it brings in (null for a + * whole module; importedNames). + */ export function importsOf(file) { const source = readFileSync(file, 'utf8'); + const code = codeOnly(source); const found = []; for (const match of source.matchAll(IMPORT)) { const line = source.slice(0, match.index).split('\n').length; - found.push({ specifier: match[2], line, dynamic: match[0].includes('('), typeOnly: isTypeOnly(source, match) }); + found.push({ specifier: match[2], line, dynamic: match[0].includes('('), typeOnly: isTypeOnly(source, match), names: importedNames(code, match) }); } return found; } /** * The source file an import of `file` names: a relative path, or a workspace - * package's (`@kuiralabs/midnight-cli-core/lib/errors` is its src/lib/errors.ts, - * the package name alone its index); undefined for an outside package. + * package's entry point, through its exports map (`@kuiralabs/midnight-cli-core` + * is the module its `.` entry names); undefined for an outside package, or for + * a subpath the exports map lacks (a deep import). */ export function importTarget(file, specifier) { - const pkg = WORKSPACE_PACKAGES.find((p) => specifier === p.name || specifier.startsWith(p.name + '/')); - if (pkg !== undefined) return join(pkg.dir, `${specifier === pkg.name ? 'index' : specifier.slice(pkg.name.length + 1)}.ts`); + const pkg = packageNamed(specifier); + if (pkg !== undefined) return entrySource(pkg, subpathOf(pkg, specifier)); return specifier.startsWith('.') ? resolve(dirname(file), specifier) : undefined; } -/** Files with no package, and imports that break a rule. */ -export function findLayeringProblems() { - const unhomed = []; +/** The TypeScript source an import's target is, with its .ts or index.ts filled in; undefined for a file that isn't there. */ +export function tsSourceOf(target) { + for (const candidate of [target, `${target}.ts`, join(target, 'index.ts')]) { + if (existsSync(candidate) && statSync(candidate).isFile() && candidate.endsWith('.ts')) return candidate; + } + return undefined; +} + +// `export { a, type B } from '…'` and `export type { … } from '…'`, in code with string contents blanked. +const RE_EXPORT = /\bexport\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])/g; + +/** + * A barrel's re-exports, exported name → { file, name, typeOnly }: the module + * defining it and its name there. undefined for a module that is not a barrel + * (one holding anything besides `export { … } from` lists). + */ +export function barrelExports(file) { + const source = readFileSync(file, 'utf8'); + const code = codeOnly(source); + if (!/^\s*(export\s+(type\s+)?\{[^}]*\}\s*from\s*(['"])\s*\3\s*;?\s*)+$/.test(code)) return undefined; + const names = new Map(); + for (const match of code.matchAll(RE_EXPORT)) { + const quote = match.index + match[0].length - 1; + const specifier = source.slice(quote + 1, source.indexOf(source[quote], quote + 1)); + const target = tsSourceOf(resolve(dirname(file), specifier)); + if (target === undefined) throw new Error(`${shown(file)} re-exports from ${specifier}, which is not a source file`); + for (const part of match[2].split(',').map((each) => each.trim()).filter(Boolean)) { + const each = /^(type\s+)?(\w+)(?:\s+as\s+(\w+))?$/.exec(part); + if (each === null) throw new Error(`${shown(file)}: can't read the re-export "${part}"`); + names.set(each[3] ?? each[2], { file: target, name: each[2], typeOnly: match[1] !== undefined || each[1] !== undefined }); + } + } + return names; +} + +/** + * The modules an import of `file` brings in, each with whether it brings in + * types alone: the module it names or, when that is a barrel, the modules + * defining the names it imports (every module the barrel re-exports from, + * for a whole-module import). Returns { modules }, { refused } (the entry + * points of a workspace package whose exports map lacks the subpath), or + * undefined for an outside package. + */ +export function importedModules(file, { specifier, typeOnly, names }) { + const pkg = packageNamed(specifier); + const target = importTarget(file, specifier); + if (pkg !== undefined && target === undefined) return { refused: entryPoints(pkg) }; + if (target === undefined) return undefined; + const modules = new Map(); + const add = (each, typesAlone) => modules.set(each, (modules.get(each) ?? true) && typesAlone); + const follow = (module, wanted, typesAlone) => { + const barrel = tsSourceOf(module) === undefined ? undefined : barrelExports(tsSourceOf(module)); + if (barrel === undefined) return add(module, typesAlone); + const picked = wanted === null ? [...barrel.keys()].map((name) => ({ name, typeOnly: false })) : wanted; + for (const { name, typeOnly: typeName } of picked) { + const definer = barrel.get(name); + if (definer === undefined) add(tsSourceOf(module), typesAlone || typeName); + else follow(definer.file, [{ name: definer.name, typeOnly: false }], typesAlone || typeName || definer.typeOnly); + } + }; + follow(target, names ?? null, typeOnly); + return { modules: [...modules].map(([each, typesAlone]) => ({ file: each, typeOnly: typesAlone })) }; +} + +/** The refusal of a deep import into `pkg`, naming its entry points. */ +const deepImportRule = (pkg, entries) => `deep import into ${pkg} (its entry points: ${entries.join(', ')})`; + +/** The imports of a source file that break a rule. */ +function sourceProblems(file) { + const rel = relOf(file); + const home = homeOf(file); + const from = packageOf(file); const violations = []; - for (const file of sourceFiles()) { - const rel = relOf(file); - const home = homeOf(file); - if (home === undefined) { - unhomed.push(shown(file)); + for (const imported of importsOf(file)) { + const { specifier, line } = imported; + const where = `${shown(file)}:${line}`; + const pkg = packageNamed(specifier); + if (specifier.startsWith('.') && from !== undefined && packageOf(resolve(dirname(file), specifier)) !== from) { + violations.push({ home, rule: `${home} package → outside it (a package imports another only by name)`, where, specifier }); + continue; + } + const resolved = specifier.startsWith('.') || pkg !== undefined ? importedModules(file, imported) : undefined; + if (resolved?.refused !== undefined) { + violations.push({ home, rule: deepImportRule(pkg.name, resolved.refused), where, specifier }); continue; } - for (const { specifier, line } of importsOf(file)) { - const where = `${shown(file)}:${line}`; - const pkg = WORKSPACE_PACKAGES.find((p) => specifier === p.name || specifier.startsWith(p.name + '/')); - const from = packageOf(file); - if (specifier.startsWith('.') && from !== undefined && packageOf(resolve(dirname(file), specifier)) !== from) { - violations.push({ home, rule: `${home} package → outside it (a package imports another only by name)`, where, specifier }); - continue; - } - if (specifier.startsWith('.') || pkg !== undefined) { - const target = pkg !== undefined ? `${pkg.prefix ?? ''}${specifier === pkg.name ? 'index' : specifier.slice(pkg.name.length + 1)}.ts` : relOf(resolve(dirname(file), specifier)); - const rule = importRule(rel, target); - if (rule !== undefined) violations.push({ home, rule, where, specifier }); - } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine') { - violations.push({ home, rule: `${home} → Midnight SDK (only an engine imports it)`, where, specifier }); - } else if (home !== 'grant' && ACCOUNT_CHAIN.test(specifier)) { - violations.push({ home, rule: `${home} → account chain`, where, specifier }); - } + if (resolved !== undefined) { + // A barrel only lists its own package's modules for the packages above; it calls nothing. + if (barrelExports(file) !== undefined) continue; + const rules = new Set(resolved.modules.map((module) => importRule(rel, relOf(module.file))).filter((rule) => rule !== undefined)); + for (const rule of rules) violations.push({ home, rule, where, specifier }); + } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine') { + violations.push({ home, rule: `${home} → Midnight SDK (only an engine imports it)`, where, specifier }); + } else if (home !== 'grant' && ACCOUNT_CHAIN.test(specifier)) { + violations.push({ home, rule: `${home} → account chain`, where, specifier }); + } + } + return violations; +} + +/** The folder of the package a file is in: a workspace package's, or the repository's root for mn's own (src/, scripts/). */ +const packageRootOf = (file) => WORKSPACE_PACKAGES.find((pkg) => file.startsWith(pkg.root + '/'))?.root ?? ROOT; + +/** + * The imports of a test file that break a rule: a test imports its own + * package relatively and every other workspace package by an entry point. + */ +export function testProblems(file) { + const own = packageRootOf(file); + const violations = []; + for (const { specifier, line } of importsOf(file)) { + const where = `${shown(file)}:${line}`; + const pkg = packageNamed(specifier); + const target = specifier.startsWith('.') ? resolve(dirname(file), specifier) : undefined; + if (target !== undefined && !target.startsWith(TEST_SUPPORT + '/') && packageRootOf(target) !== own) { + violations.push({ home: 'test', rule: 'test → another package by path (a test imports another package by its entry points)', where, specifier }); + } else if (pkg !== undefined && pkg.root === own) { + violations.push({ home: 'test', rule: 'test → its own package by name (a test imports its own package relatively)', where, specifier }); + } else if (pkg !== undefined && importTarget(file, specifier) === undefined) { + violations.push({ home: 'test', rule: deepImportRule(pkg.name, entryPoints(pkg)), where, specifier }); + } + } + return violations; +} + +/** + * The imports of a test-support file that break a rule: it imports a + * workspace package by an entry point, and of mn's own code only the shell's + * list of engines (TEST_SUPPORT_MAY_IMPORT). + */ +export function testSupportProblems(file) { + const violations = []; + for (const { specifier, line } of importsOf(file)) { + const where = `${shown(file)}:${line}`; + const pkg = packageNamed(specifier); + const target = specifier.startsWith('.') ? resolve(dirname(file), specifier) : undefined; + if (target !== undefined && !target.startsWith(TEST_SUPPORT + '/') && !TEST_SUPPORT_MAY_IMPORT.includes(target)) { + violations.push({ home: 'test-support', rule: "test-support → code by path (it imports a package by its entry points, and of mn's code only lib/installed-engines.ts)", where, specifier }); + } else if (pkg !== undefined && importTarget(file, specifier) === undefined) { + violations.push({ home: 'test-support', rule: deepImportRule(pkg.name, entryPoints(pkg)), where, specifier }); + } + } + return violations; +} + +/** The imports of a script that break a rule: a script imports a workspace package by an entry point. */ +function scriptProblems(file) { + const violations = []; + for (const { specifier, line } of importsOf(file)) { + const where = `${shown(file)}:${line}`; + const pkg = packageNamed(specifier); + if (specifier.startsWith('.') && packageRootOf(resolve(dirname(file), specifier)) !== ROOT) { + violations.push({ home: 'script', rule: 'script → a package by path (a script imports a package by its entry points)', where, specifier }); + } else if (pkg !== undefined && importTarget(file, specifier) === undefined) { + violations.push({ home: 'script', rule: deepImportRule(pkg.name, entryPoints(pkg)), where, specifier }); } } + return violations; +} + +/** Files with no package, and imports that break a rule: in the source, the tests and the scripts. */ +export function findLayeringProblems() { + const unhomed = []; + const violations = []; + for (const file of sourceFiles()) { + if (homeOf(file) === undefined) unhomed.push(shown(file)); + else violations.push(...sourceProblems(file)); + } + for (const file of testFiles()) violations.push(...testProblems(file)); + for (const file of testSupportFiles()) violations.push(...testSupportProblems(file)); + for (const file of scriptFiles()) violations.push(...scriptProblems(file)); return { unhomed, violations }; } diff --git a/scripts/code-reach.mjs b/scripts/code-reach.mjs index e092abcd..e705b8ca 100644 --- a/scripts/code-reach.mjs +++ b/scripts/code-reach.mjs @@ -9,6 +9,10 @@ // DYNAMIC_MODULES); a module constructing a class whose code is not a literal // and that the first table lacks fails the scan. // +// An import of a barrel (an entry point made only of `export { … } from` +// lists) reaches the modules defining the names it imports, not every module +// the barrel lists: the others load, but nothing of theirs runs. +// // Reaches that don't show as imports are added: // - the engine: a module that asks the host for one (`engines.load(`, // `.for(`, `.any(`) reaches the host's engines and loads every shipped @@ -29,10 +33,10 @@ // modules), the tables, and declaredCodeProblems, which the suite runs // (src/__tests__/declared-codes.test.ts). -import { existsSync, readFileSync, statSync } from 'node:fs'; +import { readFileSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { importTarget, importsOf, sourceFiles } from './check-layering.mjs'; +import { importTarget, importedModules, importsOf, sourceFiles, tsSourceOf } from './check-layering.mjs'; import { codeOnly } from './check-process-safety.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); @@ -232,19 +236,24 @@ export function moduleCodes(file) { /** The source file an import names, with its .ts or index.ts filled in; undefined for an outside package or a file that isn't there. */ function sourceOf(file, specifier) { const target = importTarget(file, specifier); - if (target === undefined) return undefined; - for (const candidate of [target, `${target}.ts`, join(target, 'index.ts')]) { - if (existsSync(candidate) && statSync(candidate).isFile() && candidate.endsWith('.ts')) return candidate; - } - return undefined; + return target === undefined ? undefined : tsSourceOf(target); } -/** The modules a module reaches directly: its imports that run, and the engine its calls reach. */ +/** + * The modules a module reaches directly: the modules its imports that run + * bring in (through a barrel, the modules defining the names it imports), + * and the engine its calls reach. + */ function nextModules(file) { const cut = new Set(CUT_IMPORTS.filter(([from]) => fromRoot(from) === file).map(([, to]) => fromRoot(to))); // A definition is data: its load() and its tools' checks run only when the shell or the MCP server calls them. const isDefinition = file.endsWith('.definition.ts'); - const next = importsOf(file).filter((each) => !each.typeOnly && !(isDefinition && each.dynamic)).map((each) => sourceOf(file, each.specifier)).filter((target) => target !== undefined && !cut.has(target)); + const next = importsOf(file) + .filter((each) => !each.typeOnly && !(isDefinition && each.dynamic)) + .flatMap((each) => importedModules(file, each)?.modules ?? []) + .filter((module) => !module.typeOnly) + .map((module) => tsSourceOf(module.file)) + .filter((target) => target !== undefined && !cut.has(target)); const code = codeOnly(readFileSync(file, 'utf8')); for (const { site, reaches } of ENGINE_SITES) if (site.test(code)) next.push(...reaches.map(fromRoot)); return next; diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 31a228d6..752443d3 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -236,7 +236,7 @@ try { } } writeFileSync(join(outside, 'load.mjs'), ` - import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; + import { createHost } from '@kuiralabs/midnight-cli-core'; const host = createHost({ paths: { stateRoot: ${JSON.stringify(join(outside, 'state'))}, home: ${JSON.stringify(outside)} }, engineLoader: async (set, host) => set === 'beta' ? (await import('@kuiralabs/midnight-engine-beta')).createBetaEngine(host) : (await import('@kuiralabs/midnight-engine-rc')).createRcEngine(host), @@ -247,6 +247,34 @@ try { const loaded = run(process.execPath, ['load.mjs', network], outside).trim(); check(`a program outside mn loads the ${set} engine for ${network}`, loaded === set, loaded); } + + // The installed packages are imported by their entry points alone: each + // named entry point loads, the published manifests name no source file, + // and a module that is not an entry point is refused. + writeFileSync(join(outside, 'entry.mjs'), ` + try { await import(process.argv[2]); console.log('loaded'); } catch (error) { console.log(error.code ?? error.message); } + `); + for (const { name } of workspaces) { + const manifest = readFileSync(join(outside, 'node_modules', name, 'package.json'), 'utf-8'); + check(`a program outside mn: ${name}'s manifest names no source file`, !manifest.includes('midnight-cli-source')); + for (const entry of Object.keys(JSON.parse(manifest).exports).filter((key) => !key.includes('*'))) { + const specifier = entry === '.' ? name : `${name}${entry.slice(1)}`; + const loaded = run(process.execPath, ['entry.mjs', specifier], outside).trim(); + check(`a program outside mn imports ${specifier}`, loaded === 'loaded', loaded); + } + } + // A module of each package that is not an entry point, named as the open + // `./*` used to export it (core's lib/errors as `/lib/errors`). + for (const [name, deepPath] of [ + ['@kuiralabs/midnight-cli-core', 'lib/errors'], + ['@kuiralabs/midnight-chain', 'lib/chain-id'], + ['@kuiralabs/midnight-engine-rc', 'derive-address'], + ['@kuiralabs/midnight-engine-beta', 'derive-address'], + ]) { + check(`a program outside mn finds ${name}'s ${deepPath} built`, existsSync(join(outside, 'node_modules', name, 'dist', `${deepPath}.js`))); + const deep = run(process.execPath, ['entry.mjs', `${name}/${deepPath}`], outside).trim(); + check(`a program outside mn is refused ${name}/${deepPath}`, deep === 'ERR_PACKAGE_PATH_NOT_EXPORTED', deep); + } } catch (error) { check('the fresh install and its checks ran', false, String(error.stderr || error.message).trim().split('\n').slice(-3).join(' | ')); } finally { diff --git a/scripts/measure-preprod-dust.ts b/scripts/measure-preprod-dust.ts deleted file mode 100644 index cea56d12..00000000 --- a/scripts/measure-preprod-dust.ts +++ /dev/null @@ -1,95 +0,0 @@ -// Measure the WalletDataRepository's caching wins on preprod dust reads. -// -// Three scenarios, all running against a real preprod indexer with a wallet -// that is already registered for dust generation (the cache layer is -// orthogonal to whether the wallet has dust): -// -// 1. Cold — disk cache cleared, in-memory empty. First-ever read. -// Pre-repo this never completed (180s timeout, 0 events -// saved). Post-repo+checkpoint, this completes. -// 2. Disk-warm — separate process, disk cache populated from #1. -// Tests the disk-resume path (delta sync from last -// applied event id). -// 3. Memo-warm — same process, repo singleton in memory. -// Tests the in-memory memo path (tip-aware; no network -// if chain tip unchanged). -// -// Wall-clock millis printed for each. Runs with no flags against `alice` on -// preprod by default; override with WALLET / NETWORK env. -// -// Usage: npx tsx scripts/measure-preprod-dust.ts - -import { Buffer } from 'node:buffer'; -import { existsSync, unlinkSync, readdirSync } from 'node:fs'; -import { join } from 'node:path'; -import { homedir } from 'node:os'; -import { execSync } from 'node:child_process'; - -import { WalletDataRepository, defaultRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; -import { getNetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { unlockWallet, resolveWalletPath } from '../src/lib/wallet-config.ts'; - -const WALLET = (process.env.WALLET ?? 'alice') as string; -const NETWORK = (process.env.NETWORK ?? 'preprod') as NetworkName; - -function wipeDustCacheFor(network: string): void { - const dir = join(homedir(), '.midnight', 'cache', network); - if (!existsSync(dir)) return; - for (const entry of readdirSync(dir)) { - if (entry.startsWith('dust-') && entry.endsWith('.json')) { - unlinkSync(join(dir, entry)); - } - } -} - -async function main() { - const network = getNetworkConfig(NETWORK); - const wallet = await unlockWallet(resolveWalletPath(WALLET)); - const seed = Buffer.from(wallet.seed, 'hex'); - - console.log(`Wallet: ${WALLET}`); - console.log(`Network: ${NETWORK}\n`); - - // Scenario 1: cold (no disk, no memo) — fresh repo, wiped disk cache. - wipeDustCacheFor(NETWORK); - const coldRepo = new WalletDataRepository(); - const t1 = Date.now(); - const v1 = await coldRepo.dust(seed, network); - const cold = Date.now() - t1; - console.log(`1. Cold (no disk, no memo) ${cold.toString().padStart(7)}ms fromCache=${v1.fromCache} events=${v1.eventsApplied}`); - - // Scenario 2: disk-warm (new process). Spawn a sub-process so the in-memory - // memo doesn't leak. Disk cache from #1 still present. - const disk = Number(execSync( - `npx tsx -e " - import('./src/engine/rc/wallet-data-repository.ts').then(async (repo) => { - const { Buffer } = await import('node:buffer'); - const { getNetworkConfig } = await import('./src/lib/network.ts'); - const { unlockWallet, resolveWalletPath } = await import('./src/lib/wallet-config.ts'); - const cfg = getNetworkConfig('${NETWORK}'); - const wc = await unlockWallet(resolveWalletPath('${WALLET}')); - const seed = Buffer.from(wc.seed, 'hex'); - const t = Date.now(); - await repo.defaultRepository().dust(seed, cfg); - console.log(Date.now() - t); - process.exit(0); - }); - "`, - { encoding: 'utf-8', cwd: import.meta.dirname + '/..' }, - ).trim()); - console.log(`2. Disk-warm (new process) ${disk.toString().padStart(7)}ms`); - - // Scenario 3: memo-warm (same process). Use defaultRepository singleton — - // first call primes the memo (we already did one in scenario 1 against - // `coldRepo`, but that was a different instance). Prime then measure. - const memoRepo = defaultRepository(); - await memoRepo.dust(seed, network); // prime - const t3 = Date.now(); - const v3 = await memoRepo.dust(seed, network); - const memo = Date.now() - t3; - console.log(`3. Memo-warm (same process) ${memo.toString().padStart(7)}ms fromCache=${v3.fromCache} events=${v3.eventsApplied}`); - - console.log(`\nSpeedup: cold→disk ${(cold / disk).toFixed(1)}× ; cold→memo ${(cold / Math.max(memo, 1)).toFixed(0)}×`); -} - -main().then(() => process.exit(0)).catch((err) => { console.error(err); process.exit(1); }); diff --git a/scripts/pack-release.mjs b/scripts/pack-release.mjs index a1bc6ed8..ae983dd7 100644 --- a/scripts/pack-release.mjs +++ b/scripts/pack-release.mjs @@ -1,5 +1,6 @@ // mn as a release publishes it, packed into a folder: the workspace packages -// mn depends on (each engine with its shrinkwrap), and mn with the shrinkwrap +// mn depends on (each engine with its shrinkwrap, each with the manifest it is +// published with: scripts/publish-manifest.mjs), and mn with the shrinkwrap // the release job writes, its workspace packages' tarballs and integrity as a // local registry on `port` serves them (scripts/local-registry.mjs). Until those packages are on npm, a // consumer's npm finds them nowhere else, and npm honours mn's shrinkwrap only @@ -17,6 +18,7 @@ import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { startLocalRegistryProcess } from './local-registry.mjs'; import { makeShrinkwrap, registryDist } from './make-shrinkwrap.mjs'; +import { packPublished } from './publish-manifest.mjs'; const repo = fileURLToPath(new URL('..', import.meta.url)); const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); @@ -40,7 +42,7 @@ export async function packRelease(dir, port = 0) { const engine = name.startsWith('@kuiralabs/midnight-engine-'); if (engine) makeShrinkwrap({ dir: folder }); try { - run('npm', ['pack', '--pack-destination', dir], join(repo, folder)); + packPublished(join(repo, folder), dir); } finally { if (engine) rmSync(join(repo, folder, 'npm-shrinkwrap.json'), { force: true }); } diff --git a/scripts/publish-manifest.d.mts b/scripts/publish-manifest.d.mts new file mode 100644 index 00000000..6af9ce4f --- /dev/null +++ b/scripts/publish-manifest.d.mts @@ -0,0 +1,7 @@ +// Types for what scripts/publish-manifest.mjs exports when imported. +/** The development-only export condition: an entry point's TypeScript source. */ +export const SOURCE_CONDITION: string; +/** The manifest a package is published with: its own, the source condition taken out of `exports`. */ +export function publishedManifest(manifest: T): T; +/** Packs the package in `dir` into `destination` with its published manifest, its own package.json put back; returns the tarball's path. */ +export function packPublished(dir: string, destination: string): string; diff --git a/scripts/publish-manifest.mjs b/scripts/publish-manifest.mjs new file mode 100644 index 00000000..120e8cc4 --- /dev/null +++ b/scripts/publish-manifest.mjs @@ -0,0 +1,57 @@ +#!/usr/bin/env node +// A workspace package as it is published: its package.json without the +// `midnight-cli-source` condition, which points each entry point at its +// TypeScript source for this repository's own runs (tsx, vitest, tsc) and +// means nothing to a consumer. Packing writes that manifest in place of the +// package's own, runs `npm pack`, and puts the original back, so the tarball +// (and the registry's metadata, read from it) names only the built files. +// The release job and scripts/pack-release.mjs publish what this packs. +// +// node scripts/publish-manifest.mjs +// prints the tarball's path + +import { execFileSync } from 'node:child_process'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** The development-only export condition: an entry point's TypeScript source. */ +export const SOURCE_CONDITION = 'midnight-cli-source'; + +/** An exports map (or one entry's conditions) without the source condition, at any depth. */ +function withoutSourceCondition(exports) { + if (typeof exports !== 'object' || exports === null || Array.isArray(exports)) return exports; + return Object.fromEntries(Object.entries(exports).filter(([key]) => key !== SOURCE_CONDITION).map(([key, value]) => [key, withoutSourceCondition(value)])); +} + +/** The manifest a package is published with: its own, the source condition taken out of `exports`. */ +export function publishedManifest(manifest) { + return manifest.exports === undefined ? manifest : { ...manifest, exports: withoutSourceCondition(manifest.exports) }; +} + +/** + * Packs the package in `dir` into `destination` with its published manifest, + * putting its own package.json back afterwards, byte for byte, whatever + * happens; returns the tarball's path. + */ +export function packPublished(dir, destination) { + mkdirSync(destination, { recursive: true }); + const path = join(dir, 'package.json'); + const original = readFileSync(path, 'utf-8'); + writeFileSync(path, JSON.stringify(publishedManifest(JSON.parse(original)), null, 2) + '\n'); + try { + const [packed] = JSON.parse(execFileSync('npm', ['pack', '--json', '--pack-destination', destination], { cwd: dir, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] })); + return join(destination, packed.filename); + } finally { + writeFileSync(path, original); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const [dir, destination] = process.argv.slice(2); + if (!dir || !destination) { + console.error('usage: node scripts/publish-manifest.mjs '); + process.exit(2); + } + console.log(packPublished(resolve(dir), resolve(destination))); +} diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index 5df5a629..99b7ccf4 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -13,16 +13,14 @@ import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { type FeeWallet, accountProviders, freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_ID } from '@kuiralabs/midnight-account-chain/contract'; -import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { WrongPassphraseError, getNetworkConfig, createHost } from '@kuiralabs/midnight-cli-core'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { exportAccount, importAccount } from '../lib/grant/account-backup.ts'; import { createPendingDevice, openAccountKey, ownDeviceCode, sealedDeviceList } from '../lib/grant/sealed-account.ts'; import { parseDeviceCode } from '../lib/grant/device-code.ts'; import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStatePassword } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. diff --git a/src/__tests__/address-command.test.ts b/src/__tests__/address-command.test.ts index e74e1a26..db6308ad 100644 --- a/src/__tests__/address-command.test.ts +++ b/src/__tests__/address-command.test.ts @@ -3,8 +3,8 @@ import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import addressCommand from '../commands/address.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index 42dd58f7..e73306bd 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -8,15 +8,8 @@ import { describe, expect, it } from 'vitest'; import { join } from 'node:path'; import { installedCommands } from '../lib/installed-commands.ts'; -import { - CommandDefinitionError, - createPackageRegistry, - type CommandDefinition, - type CommandPackage, - type CommandRegistry, -} from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { GuidanceError, assembleGuidance, manualCodeRow, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; -import { chainCodes } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { CommandDefinitionError, createPackageRegistry, type CommandDefinition, type CommandPackage, type CommandRegistry, GuidanceError, assembleGuidance, manualCodeRow, sectionsWithAdded, type GuidancePiece, type GuidanceText } from '@kuiralabs/midnight-cli-core'; +import { chainCodes } from '@kuiralabs/midnight-chain/commands'; import { AGENT_MANUAL_SECTIONS, TOOL_GROUPS, agentManual } from '../lib/agent-manual.ts'; import { SKILL_CORE_SECTIONS, SKILL_FULL_SECTIONS, skillCore, skillFull } from '../lib/mcp/skills.ts'; import { listedTools } from '../lib/mcp/registry-tools.ts'; diff --git a/src/__tests__/airdrop-command.test.ts b/src/__tests__/airdrop-command.test.ts index bef1ad63..980456d6 100644 --- a/src/__tests__/airdrop-command.test.ts +++ b/src/__tests__/airdrop-command.test.ts @@ -1,10 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import airdropCommand from '../commands/airdrop.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -32,7 +31,7 @@ describe('airdrop command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -45,7 +44,7 @@ describe('airdrop command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -58,7 +57,7 @@ describe('airdrop command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -71,7 +70,7 @@ describe('airdrop command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -95,7 +94,7 @@ describe('airdrop command — network restriction', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -108,7 +107,7 @@ describe('airdrop command — network restriction', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -121,7 +120,7 @@ describe('airdrop command — network restriction', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -204,7 +203,7 @@ describe('airdrop command — shielded flag', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -217,7 +216,7 @@ describe('airdrop command — shielded flag', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index f0bfc8d8..2cd95b95 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -1,11 +1,10 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; -import { testHost } from './helpers/test-host.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; +import { testHost } from '../../test-support/test-host.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -21,11 +20,11 @@ const TEST_DIR = path.join(os.tmpdir(), `midnight-balance-cmd-test-${process.pid // Derive real valid addresses for testing against the local undeployed indexer const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); -const GENESIS_UNDEPLOYED_ADDRESS = deriveUnshieldedAddress(genesisSeedBuffer, 'undeployed'); +const GENESIS_UNDEPLOYED_ADDRESS = rcKeys.unshieldedAddress(genesisSeedBuffer, 'undeployed'); // A different seed with no balance — used to test "No balance found" path const EMPTY_SEED = '0000000000000000000000000000000000000000000000000000000000000099'; -const EMPTY_ADDRESS = deriveUnshieldedAddress(Buffer.from(EMPTY_SEED, 'hex'), 'undeployed'); +const EMPTY_ADDRESS = rcKeys.unshieldedAddress(Buffer.from(EMPTY_SEED, 'hex'), 'undeployed'); let io: CapturedOutput; @@ -56,7 +55,7 @@ afterEach(() => { }); beforeAll(async () => { - const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core'); const { indexer } = resolveNetwork({ args: parseArgs(['balance', '--network', 'undeployed']), configDir: testHost().paths().stateRoot }, testHost().settings()).config; const answered = await fetch(indexer, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: '{ block { height } }' }), signal: AbortSignal.timeout(5_000) }) .then((r) => r.ok, () => false); @@ -68,7 +67,7 @@ describe('balance command — reads address from wallet file', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: GENESIS_SEED, - addresses: deriveAllAddresses(genesisSeedBuffer), + addresses: rcKeys.unshieldedAddresses(genesisSeedBuffer), createdAt: '2026-01-01T00:00:00.000Z', }; saveWalletConfig(config, walletFile); @@ -88,7 +87,7 @@ describe('balance command — reads address from wallet file', () => { // Every dev chain's genesis wallet holds two shielded test tokens beside NIGHT. const tokens = ['00'.repeat(31) + '01', '00'.repeat(31) + '02']; const walletFile = path.join(TEST_DIR, 'wallet.json'); - saveWalletConfig({ seed: GENESIS_SEED, addresses: deriveAllAddresses(genesisSeedBuffer), createdAt: '2026-01-01T00:00:00.000Z' }, walletFile); + saveWalletConfig({ seed: GENESIS_SEED, addresses: rcKeys.unshieldedAddresses(genesisSeedBuffer), createdAt: '2026-01-01T00:00:00.000Z' }, walletFile); await cliCall(balanceCommand, parseArgs(['balance', '--wallet', walletFile, '--network', 'undeployed'])); for (const token of tokens) { diff --git a/src/__tests__/balance-command.test.ts b/src/__tests__/balance-command.test.ts index 6a6a2a27..00b6efee 100644 --- a/src/__tests__/balance-command.test.ts +++ b/src/__tests__/balance-command.test.ts @@ -1,10 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import balanceCommand from '../commands/balance.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -17,11 +16,11 @@ const TEST_DIR = path.join(os.tmpdir(), `midnight-balance-cmd-test-${process.pid // Derive real valid addresses for testing against the local undeployed indexer const genesisSeedBuffer = Buffer.from(GENESIS_SEED, 'hex'); -const GENESIS_UNDEPLOYED_ADDRESS = deriveUnshieldedAddress(genesisSeedBuffer, 'undeployed'); +const GENESIS_UNDEPLOYED_ADDRESS = rcKeys.unshieldedAddress(genesisSeedBuffer, 'undeployed'); // A different seed with no balance — used to test "No balance found" path const EMPTY_SEED = '0000000000000000000000000000000000000000000000000000000000000099'; -const EMPTY_ADDRESS = deriveUnshieldedAddress(Buffer.from(EMPTY_SEED, 'hex'), 'undeployed'); +const EMPTY_ADDRESS = rcKeys.unshieldedAddress(Buffer.from(EMPTY_SEED, 'hex'), 'undeployed'); let io: CapturedOutput; diff --git a/src/__tests__/cache-local-stacks.test.ts b/src/__tests__/cache-local-stacks.test.ts new file mode 100644 index 00000000..ce4d9b39 --- /dev/null +++ b/src/__tests__/cache-local-stacks.test.ts @@ -0,0 +1,15 @@ +// mn cache clear names its network without resolving endpoints, so several +// local stacks running (core's local stack detection refuses to pick one) +// never stop it. + +import { describe, expect, it } from 'vitest'; + +describe('mn cache clear with several local stacks', () => { + it('needs only the network name, so it never runs detection', async () => { + const src = (await import('node:fs')).readFileSync(new URL('../commands/cache.ts', import.meta.url), 'utf-8'); + // Full resolution would detect local stacks and refuse when several run, + // yet cache takes no endpoint flags to settle it. + expect(src).toContain('resolveNetworkName('); + expect(src).not.toMatch(/\bresolveNetwork\(/); + }); +}); diff --git a/src/__tests__/chain-reset-clearing.test.ts b/src/__tests__/chain-reset-clearing.test.ts index 8256f8ea..5f29ab5f 100644 --- a/src/__tests__/chain-reset-clearing.test.ts +++ b/src/__tests__/chain-reset-clearing.test.ts @@ -7,9 +7,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { clearChainCaches } from '../lib/chain-caches.ts'; -import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { getCachePath, getDustCachePath, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/engine'; import { PRIVATE_STATE_DATABASE, clearDappPrivateState } from '../lib/contract/private-state.ts'; let dir: string; diff --git a/src/__tests__/classify-reads-no-message.test.ts b/src/__tests__/classify-reads-no-message.test.ts index 6a775381..2e97540a 100644 --- a/src/__tests__/classify-reads-no-message.test.ts +++ b/src/__tests__/classify-reads-no-message.test.ts @@ -8,8 +8,7 @@ import { readFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import ts from 'typescript'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { DustRequiredError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { classifyError, DustRequiredError } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; /** `error` with a message getter that throws, as an object from a broken bridge can have. */ diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 95ea5927..81c0d970 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -14,30 +14,31 @@ import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { Buffer } from 'node:buffer'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, type Prompter, type CommandHandler } from '@kuiralabs/midnight-cli-core'; +import { getCachePath } from '@kuiralabs/midnight-cli-core/engine'; import { installedCommands } from '../lib/installed-commands.ts'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; import { establishPassphrase, isPassphraseSet } from '../lib/passphrase.ts'; -import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { loadWalletConfig, protectAllWallets } from '../lib/wallet-config.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import type { WalletProtector } from '../lib/wallet-protector.ts'; -import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import balanceCommand from '../commands/balance.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import statusCommand from '@kuiralabs/midnight-chain/commands/status'; +import { statusDefinition } from '@kuiralabs/midnight-chain/commands'; import generateCommand from '../commands/generate.ts'; import walletCommand from '../commands/wallet.ts'; import cacheCommand from '../commands/cache.ts'; import testCommand from '../commands/test.ts'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; + +// The status handler, as the shell loads it. +const { default: statusCommand } = await statusDefinition.load(); const PASSPHRASE = 'correct horse battery staple'; @@ -123,7 +124,7 @@ describe('balance passes the signal into its reads', () => { const endpoints = (): string[] => ['--indexer-ws', indexer.url, '--node', `ws://127.0.0.1:${refusing.port}`, '--proof-server', `http://127.0.0.1:${refusing.port}`]; it('an address\'s balance: the subscription closes at once and the call answers CANCELLED with no result', async () => { - const address = deriveUnshieldedAddress(Buffer.from('aa'.repeat(32), 'hex'), 'undeployed'); + const address = rcKeys.unshieldedAddress(Buffer.from('aa'.repeat(32), 'hex'), 'undeployed'); const call = new AbortController(); void indexer.sentAtLeast(1).then(() => call.abort()); @@ -259,7 +260,7 @@ describe('commands that write check the call before each whole write', () => { const seed = seedByte.repeat(32); return saveWalletConfig({ seed, - addresses: { undeployed: deriveUnshieldedAddress(Buffer.from(seed, 'hex'), 'undeployed') } as never, + addresses: { undeployed: rcKeys.unshieldedAddress(Buffer.from(seed, 'hex'), 'undeployed') } as never, createdAt: '2026-10-31T00:00:00.000Z', }, path.join(stateRootIn(home), 'wallets', `${name}.json`)); }; diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 015abe12..0ced72ac 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -9,11 +9,8 @@ import { readFileSync } from 'node:fs'; import { basename } from 'node:path'; import { sourceFiles } from '../../scripts/check-layering.mjs'; import { join } from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { findUnknownFlags as findUnknownFlagsIn, findMisplacedFlags as findMisplacedFlagsIn, assertKnownFlags as assertKnownFlagsIn } from '@kuiralabs/midnight-cli-core/lib/command-flags'; +import { parseArgs, UsageError, findUnknownFlags as findUnknownFlagsIn, findMisplacedFlags as findMisplacedFlagsIn, assertKnownFlags as assertKnownFlagsIn, type ParsedArgs } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; -import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; // The refusal reads the installed commands' registry, as the CLI's does. const findUnknownFlags = (args: ParsedArgs) => findUnknownFlagsIn(args, installedCommands); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 6f3d7198..ce608a7c 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -8,31 +8,12 @@ import { describe, expect, it } from 'vitest'; import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; -import { WORKSPACE_PACKAGES, sourceFiles } from '../../scripts/check-layering.mjs'; +import { sourceFiles } from '../../scripts/check-layering.mjs'; import { installedCommands } from '../lib/installed-commands.ts'; -import { - CommandDefinitionError, - confirmationText, - createCommandRegistry, - commandHelpSpecs, - flagsSectionLines, - introBriefs, - toolArgv, - needsConfirmation, - NETWORK_PARAM, - type CommandDefinition, - type ToolDefinition, -} from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; +import { confirmationText, createCommandRegistry, commandHelpSpecs, introBriefs, toolArgv, needsConfirmation, NETWORK_PARAM, type CommandDefinition, getValidNetworkNames, FULL_FLAG, parseArgs, type ParsedArgs, CancelledError, isUsageError, classifyError, EXIT_CANCELLED, type CallContext, type CommandOutcome, type Payer, createSdkWarningRouter } from '@kuiralabs/midnight-cli-core'; import { CONFIRM_TOOL, listedTools } from '../lib/mcp/registry-tools.ts'; import { commandNeedsWalletSdk, dispatchCommand, type ShellProvisions } from '../lib/command-dispatch.ts'; -import { testHost } from './helpers/test-host.ts'; -import { FULL_FLAG, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { CancelledError, isUsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError, EXIT_CANCELLED } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import type { CallContext, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { createSdkWarningRouter, sdkWarningCallsOn } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { testHost } from '../../test-support/test-host.ts'; import type { WalletProtector } from '../lib/wallet-protector.ts'; const SRC = join(import.meta.dirname, '..'); @@ -64,10 +45,9 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => it('loads each handler from its own command\'s module', async () => { for (const c of registry.commands.filter((c) => c.shell.unavailable === undefined)) { - // A command's module sits in commands/, under src/ or a workspace package, which is imported by name. + // A command's module sits in commands/, under src/ or a workspace package's source. const file = sourceFiles().find((f) => f.endsWith(`/commands/${c.name}.ts`))!; - const pkg = WORKSPACE_PACKAGES.find((p) => file.startsWith(p.dir + '/')); - const fromModule = await import(pkg === undefined ? file : `${pkg.name}/commands/${c.name}`); + const fromModule = await import(file); expect((await c.load()).default, c.name).toBe(fromModule.default); } }, 120_000); @@ -403,88 +383,3 @@ describe('the MCP tools, generated from the registry', () => { }); }); -describe('createCommandRegistry', () => { - const base: CommandDefinition = { - name: 'x', - order: 1, - flags: [{ name: 'a', takesValue: false, help: ['--a A'] }], - help: { description: 'X', usage: 'midnight x', flags: ['note', { flag: 'a' }] }, - needsWalletSdk: false, - shell: {}, - errors: { codes: [] }, - load: async () => ({ default: async () => {} }), - }; - - it('renders the Flags section from its lines and the flags\' own help', () => { - expect(flagsSectionLines(base)).toStrictEqual(['note', '--a A']); - }); - - it('refuses a command defined twice', () => { - expect(() => createCommandRegistry([base, base], [])).toThrow(CommandDefinitionError); - }); - - it('refuses help that shows a flag with no help lines, or a flag\'s help that help never shows', () => { - expect(() => createCommandRegistry([{ ...base, help: { ...base.help!, flags: [{ flag: 'b' }] } }], [])).toThrow(/--b/); - expect(() => createCommandRegistry([{ ...base, help: { ...base.help!, flags: [] } }], [])).toThrow(/--a has help lines/); - }); - - it('refuses a flag tied to a subcommand the command lacks', () => { - expect(() => createCommandRegistry([{ ...base, flags: [{ name: 'a', takesValue: false, subcommands: ['nope'] }], help: undefined }], [])).toThrow(/"nope"/); - }); - - const tool: ToolDefinition = { name: 't', description: 'T', params: [], argv: { flags: [] }, order: 1 }; - const withTools = (flags: CommandDefinition['flags'], ...tools: ToolDefinition[]): CommandDefinition => - ({ ...base, subcommands: ['s', 'r'], flags, help: undefined, mcp: { tools } }); - - it('refuses two tools with one name or one place', () => { - expect(() => createCommandRegistry([{ ...base, mcp: { tools: [tool, tool] } }], [])).toThrow(/MCP tool "t"/); - expect(() => createCommandRegistry([{ ...base, mcp: { tools: [tool, { ...tool, name: 'u' }] } }], [])).toThrow(/place "1"/); - }); - - it('generates a tool\'s schema: its params in order, then the flags it passes on that agents may pass and apply to its subcommand', () => { - const registry = createCommandRegistry([withTools([ - { name: 'z', takesValue: true, agent: { type: 'string', description: 'Z' } }, - { name: 'only-r', takesValue: true, subcommands: ['r'], agent: { type: 'string' } }, - { name: 'loud', takesValue: false, agent: { notForAgents: 'a terminal\'s' } }, - { name: 'a', takesValue: true, subcommands: ['s'], agent: { type: 'string', enum: ['x'] } }, - ], { - ...tool, - params: [{ name: 'id', schema: { type: 'string' } }, { flag: 'a', schema: { type: 'string', description: 'as shown before' } }], - required: ['id'], - argv: { subcommand: 's', positionals: ['id'], flags: 'rest' }, - })], [{ name: 'json', takesValue: false, agent: { notForAgents: 'set by the server' } }]); - expect(JSON.stringify(registry.tools[0]!.inputSchema)).toBe(JSON.stringify({ - type: 'object', - properties: { id: { type: 'string' }, a: { type: 'string', description: 'as shown before' }, z: { type: 'string', description: 'Z' } }, - required: ['id'], - })); - }); - - it('refuses a tool that places a flag its command lacks, one hidden from agents, or one not of its subcommand', () => { - const flags = [ - { name: 'hidden', takesValue: false, agent: { notForAgents: 'why' } }, - { name: 'only-r', takesValue: true, subcommands: ['r'], agent: { type: 'string' as const } }, - ]; - const placing = (flag: string) => withTools(flags, { ...tool, params: [{ flag }], argv: { subcommand: 's', flags: [flag] } }); - expect(() => createCommandRegistry([placing('nope')], [])).toThrow(/--nope, which x doesn't accept/); - expect(() => createCommandRegistry([placing('hidden')], [])).toThrow(/--hidden, which says no schema/); - expect(() => createCommandRegistry([placing('only-r')], [])).toThrow(/--only-r, which doesn't apply/); - }); - - it('refuses a tool passing the rest on when a flag of its subcommand says neither how agents see it nor why not', () => { - const rest = { ...tool, argv: { subcommand: 's', flags: 'rest' as const } }; - expect(() => createCommandRegistry([withTools([{ name: 'quiet', takesValue: false }], rest)], [])).toThrow(/--quiet on, which says neither/); - // A flag of another subcommand needs nothing. - expect(() => createCommandRegistry([withTools([{ name: 'quiet', takesValue: false, subcommands: ['r'] }], rest)], [])).not.toThrow(); - // Nor does a global flag, which the tool passes on too. - expect(() => createCommandRegistry([withTools([], rest)], [{ name: 'json', takesValue: false }])).toThrow(/--json on, which says neither/); - }); - - it('refuses an own parameter named like a flag, a mapping to a parameter it lacks, and a required one its schema lacks', () => { - const flags = [{ name: 'a', takesValue: true, agent: { type: 'string' as const } }]; - expect(() => createCommandRegistry([withTools(flags, { ...tool, params: [{ name: 'a', schema: { type: 'string' } }] })], [])).toThrow(/"a" is also a flag/); - expect(() => createCommandRegistry([withTools(flags, { ...tool, argv: { positionals: ['id'], flags: [] } })], [])).toThrow(/"id" fills/); - expect(() => createCommandRegistry([withTools(flags, { ...tool, argv: { flags: ['a'] } })], [])).toThrow(/passes "a"/); - expect(() => createCommandRegistry([withTools(flags, { ...tool, required: ['b'] })], [])).toThrow(/requires "b"/); - }); -}); diff --git a/src/__tests__/config-command.test.ts b/src/__tests__/config-command.test.ts index a88843da..d81e10f0 100644 --- a/src/__tests__/config-command.test.ts +++ b/src/__tests__/config-command.test.ts @@ -2,13 +2,15 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; +import { parseArgs, loadCliConfig } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +// The config handler, as the shell loads it. +const { default: configCommand } = await configDefinition.load(); + let io: CapturedOutput; // A home of the test's own: the config the commands write is never the user's. diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 5ca80e70..8fdb7122 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -9,10 +9,8 @@ import * as path from 'node:path'; import { contractDeployRequest } from '../lib/contract/request.ts'; import { deployContract } from '../lib/contract/deploy.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; -import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { createSdkWarningRouter, CancelledError, createHost, type Host } from '@kuiralabs/midnight-cli-core'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; const ENDPOINTS = { network: 'undeployed' as const, node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', proofServer: 'http://localhost:26300' }; diff --git a/src/__tests__/contract-lib.test.ts b/src/__tests__/contract-lib.test.ts index ad09a0b4..dac09eb7 100644 --- a/src/__tests__/contract-lib.test.ts +++ b/src/__tests__/contract-lib.test.ts @@ -10,15 +10,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { InsufficientBalanceError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { createHost, type Host, type Payer, type PayingTarget, InsufficientBalanceError } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { contractCallRequest, contractDeployRequest } from '../lib/contract/request.ts'; import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { readContractState } from '../lib/contract/state.ts'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../test-support/local-indexer.ts'; const ADDRESS = 'cb5230e1ac98e07520d3b330016743a05fec38dd8fe894ae5b9ac3f71cac5190'; const ENDPOINTS = { network: 'undeployed' as const, node: 'ws://127.0.0.1:29944', indexerWS: 'ws://127.0.0.1:28088/api/v4/graphql/ws', proofServer: 'http://127.0.0.1:26300' }; diff --git a/src/__tests__/contract-request.test.ts b/src/__tests__/contract-request.test.ts index 6501e35b..65fafcf2 100644 --- a/src/__tests__/contract-request.test.ts +++ b/src/__tests__/contract-request.test.ts @@ -6,8 +6,7 @@ import { mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { contractCallRequest, contractDeployRequest, resolveContractCallRequest, resolveContractDeployRequest, resolveScanDir } from '../lib/contract/request.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { parseArgs, UsageError } from '@kuiralabs/midnight-cli-core'; const UINT = { 'type-name': 'Uint', maxval: 255 }; const ADDRESS = 'cb5230e1ac98e07520d3b330016743a05fec38dd8fe894ae5b9ac3f71cac5190'; diff --git a/src/__tests__/contract-runner-endpoints.test.ts b/src/__tests__/contract-runner-endpoints.test.ts index 7c9014b7..b56a8d96 100644 --- a/src/__tests__/contract-runner-endpoints.test.ts +++ b/src/__tests__/contract-runner-endpoints.test.ts @@ -4,17 +4,16 @@ // them in its text. import { describe, expect, it } from 'vitest'; -import { BlockfrostProjectIdRequiredError, blockfrostEndpoints } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { BlockfrostProjectIdRequiredError, blockfrostEndpoints, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/engine'; import { SCRIPT_PARTS, indexerEnvironment } from '../lib/contract/runner.ts'; -import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; -import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { rcEngine } from '../../test-support/rc-engine.ts'; // The rc engine's scripts, with the parts the runner gives every engine. -const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); -const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); -const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); +const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcEngine.contracts.scripts.deploy(opts, SCRIPT_PARTS); +const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcEngine.contracts.scripts.call(opts, SCRIPT_PARTS); +const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcEngine.contracts.scripts.state(opts, SCRIPT_PARTS); -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; const ID = 'nightpreprodAbCdEfGhIjKlMnOpQrStUv0123'; const preprod = (projectId: string | undefined): NetworkConfig => ({ diff --git a/src/__tests__/contract-runner.test.ts b/src/__tests__/contract-runner.test.ts index c95c7f77..f94a1d62 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/src/__tests__/contract-runner.test.ts @@ -1,56 +1,24 @@ -// The contract runner emits a Node script; these tests evaluate its provider -// fragments against the installed midnight-js 5 / ledger-v9 packages. Only the -// mn serve RPC (`rpcCall`) is stubbed. - -import { describe, it, expect, beforeAll, afterEach } from 'vitest'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; +// The contract runner emits a Node script for the engine's set: these tests +// check the scripts the rc engine generates with the runner's parts (each +// starts with the prelude, imports only what its packages export, and parses), +// and that a cancelled run starts none. The generated provider fragments are +// the rc engine's own (packages/engine-rc/src/__tests__/contract-scripts.test.ts). + +import { describe, it, expect } from 'vitest'; +import { CancelledError, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/engine'; import { spawnSync } from 'node:child_process'; import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import * as ledger from '@midnightntwrk/ledger-v9'; -import { - createWalletProvider, - createMidnightProvider, - assertSeamsSupportEra, - Transaction, - type WalletProvider, - type MidnightProvider, - type UnboundTransaction, -} from '@midnight-ntwrk/midnight-js-types'; -import { toHex, fromHex } from '@midnight-ntwrk/midnight-js-utils'; -import { CURRENT_LEDGER_VERSION } from '@midnight-ntwrk/midnight-js-protocol/version'; -import { NodeZkConfigProvider } from '@midnight-ntwrk/midnight-js-node-zk-config-provider'; -import { httpClientProofProvider } from '@midnight-ntwrk/midnight-js-http-client-proof-provider'; -import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider'; -import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider'; -import { - SCRIPT_PARTS, - SCRIPT_PRELUDE, - indexerEnvironment, - runCall, - runDeploy, - runState, -} from '../lib/contract/runner.ts'; -import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; -import { PROVIDER_IMPORTS, walletProviderCode } from '@kuiralabs/midnight-engine-rc/contract-scripts'; -import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { SCRIPT_PARTS, SCRIPT_PRELUDE, runCall, runDeploy, runState } from '../lib/contract/runner.ts'; +import { rcEngine } from '../../test-support/rc-engine.ts'; +import { testHost } from '../../test-support/test-host.ts'; // The rc engine's scripts, with the parts the runner gives every engine. -const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); -const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); -const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); -const providerSetupCode = (networkConfig: Parameters[0], key: string): string => rcScripts.providerSetupCode(networkConfig, key, SCRIPT_PARTS); - -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { testHost } from './helpers/test-host.ts'; - -const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new ( - ...params: string[] -) => (...args: unknown[]) => Promise; - -const COIN_PK = 'aa'.repeat(32); -const ENC_PK = 'bb'.repeat(32); +const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcEngine.contracts.scripts.deploy(opts, SCRIPT_PARTS); +const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcEngine.contracts.scripts.call(opts, SCRIPT_PARTS); +const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcEngine.contracts.scripts.state(opts, SCRIPT_PARTS); const NETWORK: NetworkConfig = { indexer: 'http://127.0.0.1:1/api/v4/graphql', @@ -60,151 +28,6 @@ const NETWORK: NetworkConfig = { networkId: 'Undeployed', }; -type RpcRecord = { method: string; params: Record }; - -/** Stub of the mn serve JSON-RPC boundary: records calls, answers from `replies`. */ -function makeRpcStub(replies: Record) { - const calls: RpcRecord[] = []; - const rpcCall = async (method: string, params: Record = {}) => { - calls.push({ method, params }); - if (!(method in replies)) throw new Error(`unexpected RPC ${method}`); - return replies[method]; - }; - return { calls, rpcCall }; -} - -/** Run the generated wallet/midnight provider fragment with the bindings PROVIDER_IMPORTS gives it. */ -async function evalWalletProviders(rpcCall: unknown) { - const fn = new AsyncFunction( - 'rpcCall', 'createWalletProvider', 'createMidnightProvider', 'Transaction', 'toHex', 'fromHex', - `${walletProviderCode()}\nreturn { walletProvider, midnightProvider };`, - ); - return await fn(rpcCall, createWalletProvider, createMidnightProvider, Transaction, toHex, fromHex) as { - walletProvider: WalletProvider; - midnightProvider: MidnightProvider; - }; -} - -// Real ledger-v9 txs built offline: an empty intent needs no circuit proofs, -// so prove() never reaches the proving provider. -let unboundTx: UnboundTransaction; -let finalizedTx: ledger.FinalizedTransaction; - -beforeAll(async () => { - const neverProves = async () => { throw new Error('proving provider must not be called'); }; - const unproven = ledger.Transaction.fromParts( - 'undeployed', undefined, undefined, ledger.Intent.new(new Date(Date.UTC(2030, 0, 1))), - ); - unboundTx = await unproven.prove( - { check: neverProves, prove: neverProves, lookupKey: neverProves }, - ledger.CostModel.initialCostModel(), - ); - finalizedTx = ledger.Transaction.fromParts( - 'undeployed', undefined, undefined, ledger.Intent.new(new Date(Date.UTC(2030, 0, 1))), - ).mockProve(); -}); - -describe('generated walletProvider', () => { - it('declares the current ledger era so midnight-js 5 does not refuse it', async () => { - const { rpcCall } = makeRpcStub({ - getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, - }); - const { walletProvider, midnightProvider } = await evalWalletProviders(rpcCall); - - expect(walletProvider.supportedEras).toContain(CURRENT_LEDGER_VERSION); - expect(midnightProvider.supportedEras).toContain(CURRENT_LEDGER_VERSION); - }); - - it('returns the keys mn serve reports', async () => { - const { rpcCall } = makeRpcStub({ - getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, - }); - const { walletProvider } = await evalWalletProviders(rpcCall); - - expect(walletProvider.getCoinPublicKey()).toBe(COIN_PK); - expect(walletProvider.getEncryptionPublicKey()).toBe(ENC_PK); - }); - - it('balances a v9-tagged tx via balanceUnsealedTransaction and returns the sealed tx v9-tagged', async () => { - const sealedHex = toHex(finalizedTx.serialize()); - const { calls, rpcCall } = makeRpcStub({ - getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, - balanceUnsealedTransaction: { tx: sealedHex }, - }); - const { walletProvider } = await evalWalletProviders(rpcCall); - - const balanced = await walletProvider.balanceTx({ version: 'v9', tx: unboundTx }); - - const balanceCall = calls.find((c) => c.method === 'balanceUnsealedTransaction'); - expect(balanceCall?.params).toEqual({ tx: toHex(unboundTx.serialize()) }); - expect(balanced.version).toBe('v9'); - if (balanced.version !== 'v9') throw new Error('unreachable'); - expect(balanced.tx).toBeInstanceOf(Transaction); - expect(toHex(balanced.tx.serialize())).toBe(sealedHex); - }); - - it('surfaces an RPC rejection from mn serve', async () => { - const { rpcCall } = makeRpcStub({ - getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, - }); - const { walletProvider } = await evalWalletProviders(rpcCall); - - await expect(walletProvider.balanceTx({ version: 'v9', tx: unboundTx })) - .rejects.toThrow('unexpected RPC balanceUnsealedTransaction'); - }); -}); - -describe('generated midnightProvider', () => { - it('submits the unwrapped tx hex via submitTransaction and returns its first identifier', async () => { - const { calls, rpcCall } = makeRpcStub({ - getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, - submitTransaction: { txHash: 'ignored-by-provider' }, - }); - const { midnightProvider } = await evalWalletProviders(rpcCall); - - const txId = await midnightProvider.submitTx({ version: 'v9', tx: finalizedTx }); - - const submitCall = calls.find((c) => c.method === 'submitTransaction'); - expect(submitCall?.params).toEqual({ tx: toHex(finalizedTx.serialize()) }); - expect(txId).toBe(finalizedTx.identifiers()[0]); - }); -}); - -describe('generated providers object', () => { - let dir: string | undefined; - afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = undefined; }); - - it('passes the era check deployContract/findDeployedContract run first', async () => { - dir = mkdtempSync(join(tmpdir(), 'mn-runner-')); - const { rpcCall } = makeRpcStub({ - getShieldedAddresses: { shieldedCoinPublicKey: COIN_PK, shieldedEncryptionPublicKey: ENC_PK }, - }); - const { walletProvider, midnightProvider } = await evalWalletProviders(rpcCall); - const fn = new AsyncFunction( - 'MANAGED_DIR', 'walletProvider', 'midnightProvider', - 'NodeZkConfigProvider', 'httpClientProofProvider', 'indexerPublicDataProvider', 'levelPrivateStateProvider', - `${providerSetupCode(NETWORK, 'counterPrivateState')}\nreturn providers;`, - ); - // The generated code reads the indexer's URLs from its environment, as the script's process is given them. - const environment = indexerEnvironment(NETWORK); - Object.assign(process.env, environment); - try { - const providers = await fn( - dir, walletProvider, midnightProvider, - NodeZkConfigProvider, httpClientProofProvider, indexerPublicDataProvider, levelPrivateStateProvider, - ); - try { - expect(() => assertSeamsSupportEra(CURRENT_LEDGER_VERSION, providers)).not.toThrow(); - expect(providers.midnightProvider).toBe(midnightProvider); - } finally { - await providers.publicDataProvider.dispose(); - } - } finally { - for (const name of Object.keys(environment)) delete process.env[name]; - } - }); -}); - describe('generated scripts', () => { const scripts = { deploy: generateDeployScript({ @@ -227,11 +50,6 @@ describe('generated scripts', () => { } }); - it('includes the provider imports in deploy and call scripts', () => { - expect(scripts.deploy).toContain(PROVIDER_IMPORTS); - expect(scripts.call).toContain(PROVIDER_IMPORTS); - }); - for (const [name, script] of Object.entries(scripts)) { it(`${name} script: every named import exists in the installed package`, async () => { const imports = [...script.matchAll(/^import \{([^}]+)\} from '([^']+)';$/gm)]; diff --git a/src/__tests__/contract-runtime-check.test.ts b/src/__tests__/contract-runtime-check.test.ts index 50dcf194..fa4e5a30 100644 --- a/src/__tests__/contract-runtime-check.test.ts +++ b/src/__tests__/contract-runtime-check.test.ts @@ -5,11 +5,9 @@ import { afterAll, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { UsageError, classifyError, createHost } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { runDeploy } from '../lib/contract/runner.ts'; diff --git a/src/__tests__/contract-script-errors.test.ts b/src/__tests__/contract-script-errors.test.ts index 2498560e..ddf53411 100644 --- a/src/__tests__/contract-script-errors.test.ts +++ b/src/__tests__/contract-script-errors.test.ts @@ -10,14 +10,14 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; -import { closedPort } from './helpers/closed-port.ts'; +import { closedPort } from '../../test-support/closed-port.ts'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { ContractScriptError, SCRIPT_PRELUDE, executeScript, rpcClientCode, scriptFailureMessage, scriptFailureOf } from '../lib/contract/runner.ts'; import { createApiError } from '../lib/ws-rpc.ts'; import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { withEngineCode } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { classifyError } from '@kuiralabs/midnight-cli-core'; +import { withEngineCode } from '@kuiralabs/midnight-cli-core/engine'; import { installedCommands } from '../lib/installed-commands.ts'; function runScript(body: string): { stderr: string; status: number | null } { diff --git a/src/__tests__/contract-script-packages.test.ts b/src/__tests__/contract-script-packages.test.ts index 4b1fefd7..d53f186c 100644 --- a/src/__tests__/contract-script-packages.test.ts +++ b/src/__tests__/contract-script-packages.test.ts @@ -1,15 +1,13 @@ // The contract runner finds each package its scripts need by name, wherever // it is installed, and links it into a dApp laid out unlike ours; the list of -// packages matches what the scripts import; scripts run under Node whatever -// runtime hosts mn; and the sidecar's platform package is found from a folder -// it is installed under. Temporary folders only; nothing reaches a chain. +// packages matches what the scripts import; and scripts run under Node whatever +// runtime hosts mn. Temporary folders only; nothing reaches a chain. import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { pathToFileURL } from 'node:url'; import { NoNodeRuntimeError, SCRIPT_PARTS, @@ -20,26 +18,22 @@ import { scriptRuntime, undoOverlay, } from '../lib/contract/runner.ts'; -import * as rcScripts from '@kuiralabs/midnight-engine-rc/contract-scripts'; -import { SCRIPT_PACKAGES, packageFolder } from '@kuiralabs/midnight-engine-rc/contract-scripts'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { createHost } from '@kuiralabs/midnight-cli-core'; +import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/engine'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); // The rc engine's scripts, with the parts the runner gives every engine. -const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcScripts.generateDeployScript(opts, SCRIPT_PARTS); -const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcScripts.generateCallScript(opts, SCRIPT_PARTS); -const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcScripts.generateStateScript(opts, SCRIPT_PARTS); +const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcEngine.contracts.scripts.deploy(opts, SCRIPT_PARTS); +const generateCallScript = (opts: CallScript & { dappDir?: string }): string => rcEngine.contracts.scripts.call(opts, SCRIPT_PARTS); +const generateStateScript = (opts: StateScript & { dappDir?: string }): string => rcEngine.contracts.scripts.state(opts, SCRIPT_PARTS); // The overlay of the rc engine's packages. const RC_PACKAGES = { ...rcEngine.contracts.scripts, set: 'rc' }; const overlayScriptPackages = (userNodeModules: string) => overlayScriptPackagesFor(userNodeModules, RC_PACKAGES); const acquireOverlay = (dir: string): void => acquireOverlayFor(dir, RC_PACKAGES); -import { platformPackageBinary } from '@kuiralabs/midnight-engine-rc/dust-sync-native'; - const NETWORK = { indexer: 'http://localhost:28088/api/v4/graphql', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', node: 'ws://localhost:29944', proofServer: 'http://localhost:26300', networkId: 'Undeployed' }; let dir: string; @@ -61,23 +55,23 @@ describe('the packages the scripts need', () => { // The user's compiled contract imports it. '@midnight-ntwrk/compact-runtime', ]); - expect([...imported].sort()).toEqual([...SCRIPT_PACKAGES].sort()); + expect([...imported].sort()).toEqual([...rcEngine.contracts.scripts.packages].sort()); }); it('are each found by name, as an installed package folder', () => { - for (const name of SCRIPT_PACKAGES) { - const folder = packageFolder(name); + for (const name of rcEngine.contracts.scripts.packages) { + const folder = rcEngine.contracts.scripts.packageFolder(name); expect(folder, name).not.toBeNull(); expect(JSON.parse(fs.readFileSync(path.join(folder!, 'package.json'), 'utf8')).name).toBe(name); } - expect(packageFolder('@midnight-ntwrk/no-such-package')).toBeNull(); + expect(rcEngine.contracts.scripts.packageFolder('@midnight-ntwrk/no-such-package')).toBeNull(); }); }); describe('a dApp laid out unlike ours', () => { const importEach = (dapp: string, extra: string[] = []) => { const script = path.join(dapp, 'probe.mjs'); - const names = [...SCRIPT_PACKAGES, ...extra]; + const names = [...rcEngine.contracts.scripts.packages, ...extra]; fs.writeFileSync(script, `for (const p of ${JSON.stringify(names)}) await import(p);\nconsole.log('imported', ${names.length});`); const run = spawnSync(scriptRuntime(), [script], { cwd: dapp, encoding: 'utf8', timeout: 120_000 }); fs.rmSync(script); @@ -92,7 +86,7 @@ describe('a dApp laid out unlike ours', () => { expect(fs.lstatSync(path.join(dir, 'node_modules')).isSymbolicLink()).toBe(true); const run = importEach(dir, [WITNESS_ONLY]); expect(run.status, run.stderr).toBe(0); - expect(run.stdout.trim()).toBe(`imported ${SCRIPT_PACKAGES.length + 1}`); + expect(run.stdout.trim()).toBe(`imported ${rcEngine.contracts.scripts.packages.length + 1}`); undoOverlay(made); expect(fs.readdirSync(dir)).toEqual([]); @@ -221,17 +215,3 @@ describe('the runtime a script runs under', () => { expect(() => scriptRuntime({ execPath: '/opt/bun/bin/bun', isNode: false }, path.join(dir, 'empty'))).toThrow(NoNodeRuntimeError); }); }); - -describe("the sidecar's platform package", () => { - it('is found from a folder it is installed under, and is null where it is not', () => { - const exe = process.platform === 'win32' ? 'dust-sync.exe' : 'dust-sync'; - const pkg = path.join(dir, 'node_modules', '@nel349', `dust-sync-${process.platform}-${process.arch}`); - fs.mkdirSync(pkg, { recursive: true }); - fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({ name: `@nel349/dust-sync-${process.platform}-${process.arch}`, version: '0.0.0' })); - fs.writeFileSync(path.join(pkg, exe), ''); - const from = pathToFileURL(path.join(dir, 'app', 'index.js')).href; - - expect(platformPackageBinary(from)).toBe(path.join(pkg, exe)); - expect(platformPackageBinary(pathToFileURL(path.join(os.tmpdir(), 'nowhere', 'index.js')).href)).toBeNull(); - }); -}); diff --git a/src/__tests__/contract-validate.test.ts b/src/__tests__/contract-validate.test.ts index 22ca9377..9ea0b3d0 100644 --- a/src/__tests__/contract-validate.test.ts +++ b/src/__tests__/contract-validate.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { validateCallRequest, validateContractAddress } from '../lib/contract/validate.ts'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; import type { ContractInfo } from '../lib/contract/inspect.ts'; const UINT = { 'type-name': 'Uint', maxval: 255 } as never; diff --git a/src/__tests__/declared-codes.test.ts b/src/__tests__/declared-codes.test.ts index 24980cd8..45e73f59 100644 --- a/src/__tests__/declared-codes.test.ts +++ b/src/__tests__/declared-codes.test.ts @@ -17,21 +17,21 @@ import { commandEntries, declaredCodeProblems, } from '../../scripts/code-reach.mjs'; -import { importTarget, importsOf } from '../../scripts/check-layering.mjs'; -import { declaredCodes, type CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { EVERY_COMMAND, READS_OFFERS } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { CancelledError, CommandFailedError, DustRequiredError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { refusalCodeOf, toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; +import { importTarget, importedModules, importsOf } from '../../scripts/check-layering.mjs'; +import { declaredCodes, type CommandDefinition, CancelledError, CommandFailedError, DustRequiredError, TransactionRefusedError, withTransportCode } from '@kuiralabs/midnight-cli-core'; +import { EVERY_COMMAND, READS_OFFERS } from '@kuiralabs/midnight-cli-core/commands'; +import { refusalCodeOf, toEngineError } from '@kuiralabs/midnight-cli-core/engine'; import { ContractScriptError, SCRIPT_ERROR_MARKER, scriptFailureOf } from '../lib/contract/runner.ts'; import { PrepStepFailedError } from '../lib/test/prep-runner.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { WalletNotFoundError } from '../lib/wallet-config.ts'; import { expectDeclared, expectDeclaredToolResult } from './helpers/expect-declared.ts'; import { fixtureDefinition } from './fixtures/code-reach/fixture.definition.ts'; +import { barrelFixtureDefinition } from './fixtures/code-reach/barrel.definition.ts'; const ROOT = join(import.meta.dirname, '..', '..'); const FIXTURE = join(import.meta.dirname, 'fixtures', 'code-reach', 'fixture.definition.ts'); +const BARREL_FIXTURE = join(import.meta.dirname, 'fixtures', 'code-reach', 'barrel.definition.ts'); /** The problems the check finds with `definition` declaring what it does, its entries read from its file. */ function problemsOf(definition: CommandDefinition, file: string): string[] { @@ -87,6 +87,24 @@ describe('a definition whose handler can throw a code it does not declare', () = }); }); +describe('a handler that imports a name through a barrel', () => { + it('reaches the module defining that name, and none of the others the barrel lists', () => { + expect(problemsOf(barrelFixtureDefinition, BARREL_FIXTURE)).toStrictEqual([ + 'code-reach-barrel-fixture: reaches NOT_AN_OFFER (src/__tests__/fixtures/code-reach/barrel-handler.ts → src/__tests__/fixtures/code-reach/refuses.ts), which it doesn\'t declare', + 'code-reach-barrel-fixture: reaches TERMS_MISMATCH (src/__tests__/fixtures/code-reach/barrel-handler.ts → src/__tests__/fixtures/code-reach/refuses.ts → packages/cli-core/src/lib/swap-offer.ts), which it doesn\'t declare', + ]); + }); + + it('reaches every module the barrel lists when it imports the whole barrel', () => { + const handler = join(import.meta.dirname, 'fixtures', 'code-reach', 'barrel-handler.ts'); + const whole = importsOf(handler).map((each) => ({ ...each, names: null })); + expect(whole.flatMap((each) => importedModules(handler, each)!.modules!.map((module) => module.file.slice(ROOT.length + 1)))).toStrictEqual([ + 'src/__tests__/fixtures/code-reach/refuses.ts', + 'src/__tests__/fixtures/code-reach/unpaid.ts', + ]); + }); +}); + describe("the scan's tables", () => { it('name only codes the installed packages define', () => { for (const site of [...Object.values(DYNAMIC_CLASSES), ...Object.values(DYNAMIC_MODULES)]) { diff --git a/src/__tests__/device-code.test.ts b/src/__tests__/device-code.test.ts index 38b802bf..a590feb5 100644 --- a/src/__tests__/device-code.test.ts +++ b/src/__tests__/device-code.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest'; import { freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; import { verifyReadKeyAttestation } from '@kuiralabs/midnight-account'; import { deviceCodeOf, deviceKeyOf, identityCodeOf, joinCodeOf, parseDeviceCode } from '../lib/grant/device-code.ts'; diff --git a/src/__tests__/dust-command.test.ts b/src/__tests__/dust-command.test.ts index 90c45f65..4975a79f 100644 --- a/src/__tests__/dust-command.test.ts +++ b/src/__tests__/dust-command.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import dustCommand from '../commands/dust.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -31,7 +31,7 @@ describe('dust command — subcommand validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -44,7 +44,7 @@ describe('dust command — subcommand validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -57,7 +57,7 @@ describe('dust command — subcommand validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); diff --git a/src/__tests__/engine-beta-boundary-errors.test.ts b/src/__tests__/engine-beta-boundary-errors.test.ts index 83b7798a..855f7a02 100644 --- a/src/__tests__/engine-beta-boundary-errors.test.ts +++ b/src/__tests__/engine-beta-boundary-errors.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; -import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; import { engineBoundarySuite } from './helpers/engine-boundary-suite.ts'; const ENGINE_DIR = new URL('../../packages/engine-beta', import.meta.url).pathname; diff --git a/src/__tests__/engine-beta-error-code-parity.test.ts b/src/__tests__/engine-beta-error-code-parity.test.ts deleted file mode 100644 index 4f44a0c4..00000000 --- a/src/__tests__/engine-beta-error-code-parity.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -// The beta engine's stale-cache error, as error-code-parity.test.ts checks the -// rc engine's: in a file of its own, since one process loads one SDK set. -// Approved (Y52): an escaped stale cache reports STALE_CACHE, where it was UNKNOWN. - -import { describe, expect, it } from 'vitest'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { StaleCacheError } from '@kuiralabs/midnight-engine-beta/facade'; -import { installedCommands } from '../lib/installed-commands.ts'; - -describe("the beta engine's stale cache", () => { - it('reports STALE_CACHE (exit 6) through the installed codes, where the message alone gave UNKNOWN', () => { - const err = new StaleCacheError('applied 120 of 80 events'); - expect(classifyError(err, installedCommands)).toStrictEqual({ exitCode: 6, errorCode: 'STALE_CACHE' }); - }); -}); diff --git a/src/__tests__/engine.test.ts b/src/__tests__/engine.test.ts index b7b40b81..e0a15e51 100644 --- a/src/__tests__/engine.test.ts +++ b/src/__tests__/engine.test.ts @@ -7,15 +7,14 @@ import { afterAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { OtherSdkSetError, sdkSetOf, type Engine, type SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { getValidNetworkNames, sdkSetOfNetwork, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import type { RepoDeps } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; +import { OtherSdkSetError, sdkSetOf, type Engine, type SdkSet, createHost, type Host, settingsFromEnvironment, getValidNetworkNames, sdkSetOfNetwork, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain'; +import { createRcEngine, type RcEngineOptions } from '@kuiralabs/midnight-engine-rc'; + +/** The seams an rc engine's wallet repository takes, as its options name them. */ +type RepoDeps = NonNullable; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import { startRefusingEndpoint } from './helpers/stand-in-indexer.ts'; +import { startRefusingEndpoint } from '../../test-support/stand-in-indexer.ts'; // A state root with no config: every network on the set the table names. const ROOT = mkdtempSync(join(tmpdir(), 'mn-engine-test-')); diff --git a/src/__tests__/entry-points.test.ts b/src/__tests__/entry-points.test.ts new file mode 100644 index 00000000..80f8a507 --- /dev/null +++ b/src/__tests__/entry-points.test.ts @@ -0,0 +1,31 @@ +// Each public package states its API through named entry points: its exports +// map has no pattern subpath (`./*`) a program could reach any module through, +// and its entry points are the agreed ones. A new entry point is a change to +// the API, agreed first and added here. + +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { PUBLIC_PACKAGES } from '../../scripts/api-report.mjs'; + +const PACKAGES = join(import.meta.dirname, '..', '..', 'packages'); + +/** The agreed entry points of each public package, by folder under packages/. */ +const ENTRY_POINTS: Record = { + 'cli-core': ['.', './engine', './ui', './commands'], + chain: ['.', './commands'], + 'engine-rc': ['.'], + 'engine-beta': ['.'], +}; + +describe('the public entry points', () => { + it('are agreed for every public package', () => { + expect(Object.keys(ENTRY_POINTS).sort()).toStrictEqual([...PUBLIC_PACKAGES].sort()); + }); + + it.each(Object.entries(ENTRY_POINTS))('%s: its exports map lists the agreed entry points and no pattern', (dir, agreed) => { + const { exports } = JSON.parse(readFileSync(join(PACKAGES, dir, 'package.json'), 'utf8')) as { exports: Record }; + expect(Object.keys(exports).filter((key) => key.includes('*'))).toStrictEqual([]); + expect(Object.keys(exports)).toStrictEqual(agreed); + }); +}); diff --git a/src/__tests__/error-code-docs.test.ts b/src/__tests__/error-code-docs.test.ts index d684b817..7eb59f63 100644 --- a/src/__tests__/error-code-docs.test.ts +++ b/src/__tests__/error-code-docs.test.ts @@ -8,8 +8,7 @@ import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { codeGuidancePieces, GuidanceError, manualCodeRow, skillCodeRow, wrapWords } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; -import type { CodeDefinition } from '@kuiralabs/midnight-cli-core/lib/error-codes'; +import { codeGuidancePieces, GuidanceError, manualCodeRow, skillCodeRow, wrapWords, type CodeDefinition } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { agentManual } from '../lib/agent-manual.ts'; import { skillFull } from '../lib/mcp/skills.ts'; diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index 52db6311..351c3d04 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -16,66 +16,24 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, ProofTimeoutError, SyncTimeoutError, TransactionRefusedError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { createApiError, OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { withEngineCode } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { sessionOver } from '@kuiralabs/midnight-cli-core/lib/wallet-session'; +import { classifyError, CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, SyncTimeoutError, TransactionRefusedError, UsageError, createApiError, OPERATOR_REJECTED_MESSAGE, withTransportCode, parseArgs, requireFlag, dustShortError, ProgramTimedOutError, NATIVE_TOKEN_TYPE, type NetworkConfig, type CommandHandler, createHost, payerFor, openSecret, sealSecret, checkTerms, assertOfferUnexpired, OfferCoinsInUseError, AmbiguousLocalStacksError, BlockfrostLimitError, BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, OtherSdkSetError, createSdkWarningRouter } from '@kuiralabs/midnight-cli-core'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; +import { ProofTimeoutError, withEngineCode, NotAnOfferError, MixedSdkLayoutError, DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/engine'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { ProvingError } from '@midnightntwrk/wallet-sdk/capabilities/proving'; import { InsufficientFundsError as NoCoinsCoverIt } from '@midnightntwrk/wallet-sdk/capabilities'; import { WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; -import { DustAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; -import { createDAppConnector } from '@kuiralabs/midnight-engine-rc/dapp-connector'; -import { deriveShieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { FORK_SCHEDULE } from '@kuiralabs/midnight-engine-rc/fork-schedule'; -import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from './helpers/connector-stub.ts'; -import { agentPaysMerchant, unsealedBytes } from './helpers/ledger-tx.ts'; import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; -import { closedPort } from './helpers/closed-port.ts'; +import { closedPort } from '../../test-support/closed-port.ts'; import { SCRIPT_PRELUDE, executeScript, rpcClientCode } from '../lib/contract/runner.ts'; -import { withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; import { WebSocket } from 'ws'; -import { parseArgs, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { dustShortError } from '@kuiralabs/midnight-cli-core/lib/dust-wait'; -import { ProgramTimedOutError } from '@kuiralabs/midnight-cli-core/lib/exec-program'; -import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; -import { checkTerms, NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; -import { assertOfferUnexpired } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; -import { OfferCoinsInUseError } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import { AmbiguousLocalStacksError } from '@kuiralabs/midnight-cli-core/lib/network'; -import { - BlockfrostLimitError, - BlockfrostProjectIdRejectedError, - BlockfrostProjectIdRequiredError, - EndpointShutDownError, -} from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import { MixedSdkLayoutError } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; -import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/lib/dust-registration-plan'; -import { LocalStackUnreachableError, UnsupportedLedgerError } from '@kuiralabs/midnight-chain/lib/ledger-guard'; -import { ChainClockBehindError } from '@kuiralabs/midnight-chain/lib/chain-clock'; -import { waitForFirstBlock } from '@kuiralabs/midnight-chain/lib/node-ready'; -import { waitForAddressFunded } from '@kuiralabs/midnight-chain/lib/indexer-ready'; -import { waitForProofServerReady } from '@kuiralabs/midnight-chain/lib/proof-server-ready'; -import { callNodeRpc } from '@kuiralabs/midnight-chain/lib/node-rpc'; -import { subscribeGraphqlWs } from '@kuiralabs/midnight-chain/lib/graphql-ws-subscription'; -import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; -import { StaleCacheError } from '@kuiralabs/midnight-engine-rc/facade'; +import { LocalStackUnreachableError, UnsupportedLedgerError, ChainClockBehindError, waitForFirstBlock, waitForAddressFunded, waitForProofServerReady, callNodeRpc, subscribeGraphqlWs, checkBalance, queryIndexer } from '@kuiralabs/midnight-chain'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; -import * as rx from 'rxjs'; import { readPassphrase } from '../lib/passphrase.ts'; import { assertWalletFileExists, assertWalletRemovable, setActiveWallet } from '../lib/wallet-config.ts'; import { walletSecretFrom } from '../lib/wallet-create.ts'; @@ -83,7 +41,6 @@ import { resolveTransferRequest } from '../lib/transfer-request.ts'; import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import { PrepStepFailedError, runPrepSteps } from '../lib/test/prep-runner.ts'; import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; -import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import walletCommand from '../commands/wallet.ts'; import generateCommand from '../commands/generate.ts'; @@ -108,8 +65,8 @@ beforeAll(() => { afterAll(() => { rmSync(root, { recursive: true, force: true }); }); const SEED = Buffer.from('00'.repeat(31) + '11', 'hex'); -const ADDRESSES = deriveAllAddresses(SEED); -const OTHER_ADDRESSES = deriveAllAddresses(Buffer.from('00'.repeat(31) + '22', 'hex')); +const ADDRESSES = rcKeys.unshieldedAddresses(SEED); +const OTHER_ADDRESSES = rcKeys.unshieldedAddresses(Buffer.from('00'.repeat(31) + '22', 'hex')); /** A host on the test's state root, never ~/.midnight, with the engines mn ships. */ const hostOnRoot = () => createHost({ paths: { stateRoot: root, home: root }, engineLoader: loadInstalledEngine }); @@ -147,19 +104,6 @@ const nodeRefusal = (reason: string) => () => sdkRejection(new SubmissionError({ const throughRcEngine = (failure: () => Promise) => () => createRcEngine(createHost({ paths: { stateRoot: root, home: root } }), { repository: { fetchUnshielded: failure, fetchTip: async () => 'tip-1' }, }).wallet.unshieldedBalance(ADDRESSES.undeployed, STAND_IN, { forceFresh: true }); -/** A program's wallet session over the rc engine's connector, its facade stubbed at the SDK boundary, submitting what the node refuses with `reason`. */ -const { createBundleStub, mockState } = connectorStub({ createDAppConnector, deriveShieldedAddress, DustAddress, UnshieldedAddress, ledger9ProtocolVersion: FORK_SCHEDULE.v9 }); -const throughSession = (reason: string) => async () => { - const bundle = createBundleStub({ stateFn: () => rx.of(mockState({})), submitTransaction: nodeRefusal(reason) }); - (bundle.facade as unknown as { revert: () => Promise }).revert = async () => {}; - const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); - const session = sessionOver('undeployed', { connector, stop: async () => { connector.dispose(); } }, () => []); - try { - await session.submit(await session.balanceTransaction(Buffer.from(await unsealedBytes(agentPaysMerchant())).toString('hex'))); - } finally { - await session.close(); - } -}; /** The connector's answer to a submission the node refused with `reason`: its own words over the SDK's error, marked with mn's code. */ const connectorRefusal = async (reason: string) => { const thrown = await nodeRefusal(reason)().catch((e: Error) => e); @@ -228,7 +172,7 @@ const ROWS: Row[] = [ ['airdrop with no amount', run(airdropCommand, 'airdrop'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], ["balance of an address on another network than --network", run(balanceCommand, 'balance', OTHER_ADDRESSES.undeployed, '--network', 'preprod'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], ["the shielded balance of someone else's address", run(balanceCommand, 'balance', OTHER_ADDRESSES.preview, '--shielded', '--network', 'preview'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], - ['a shielded transfer where shielded is off', () => resolveTransferRequest(parseArgs(['transfer', deriveAllShieldedAddresses(SEED).preprod, '1', '--wallet', 'alice', '--shielded', '--network', 'preprod']), root, hostOnRoot()), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + ['a shielded transfer where shielded is off', () => resolveTransferRequest(parseArgs(['transfer', rcKeys.shieldedAddresses(SEED).preprod, '1', '--wallet', 'alice', '--shielded', '--network', 'preprod']), root, hostOnRoot()), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], // No such wallet: exit 3, by its message. ['no wallet of that name', () => setActiveWallet(root, 'nobody'), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], @@ -287,14 +231,12 @@ const ROWS: Row[] = [ ["a saved state the indexer's events don't fit, through the engine", throughRcEngine(() => Promise.reject(new Error('Failed applying dust events: commitment inserted non-linearly'))), as('STALE_CACHE', 6), as('STALE_CACHE', 6)], ['a wallet sync past its deadline, in the engine', () => { throw new SyncTimeoutError('Wallet sync timed out'); }, as('SYNC_TIMEOUT', 4), as('SYNC_TIMEOUT', 4)], ['a ZK proof that timed out, in the engine (approved Y54: was UNKNOWN)', () => { throw new ProofTimeoutError(); }, as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], - // A program's wallet session: the connector in this process, reporting as the engine does. - ["the node refusing a spent coin, through a program's wallet session", throughSession('1010: Invalid Transaction: Custom error: 115'), as('STALE_UTXO', 6), as('STALE_UTXO', 6)], + // A program's wallet session (the connector in this process) and an escaped stale cache are the engines' own errors: their rows are in each engine's tests (wallet-session.test.ts, stale-cache.test.ts). // A contract run: the connector at mn serve, the wire, and the script's process. ['a contract run the node refused at mn serve (approved Y54: was UNKNOWN)', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 199'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('UNKNOWN', 1), as('TX_REJECTED', 6)], ['a contract run refused a spent coin at mn serve', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 115'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('STALE_UTXO', 6), as('STALE_UTXO', 6)], ['a contract run whose proof timed out at mn serve (approved Y54: was UNKNOWN)', () => scriptFailureAtServe(() => new ProofTimeoutError()).then((err) => { throw err; }), as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], ['a contract run the operator refused at mn serve', () => scriptFailureAtServe(() => createApiError('Rejected', OPERATOR_REJECTED_MESSAGE, 'TX_REJECTED')).then((err) => { throw err; }), as('TX_REJECTED', 6), as('TX_REJECTED', 6)], - ['a stale cache that escapes (approved: was UNKNOWN)', () => { throw new StaleCacheError('applied 120 of 80 events'); }, as('UNKNOWN', 1), as('STALE_CACHE', 6)], // Cancelled: exit 7. ['a cancelled call', () => { throw new CancelledError(); }, as('CANCELLED', 7), as('CANCELLED', 7)], diff --git a/src/__tests__/error-code-registry.test.ts b/src/__tests__/error-code-registry.test.ts index 7efead88..2f5937ac 100644 --- a/src/__tests__/error-code-registry.test.ts +++ b/src/__tests__/error-code-registry.test.ts @@ -3,20 +3,9 @@ // is defined twice. import { describe, expect, it } from 'vitest'; -import { CodeDefinitionError, defineCodeSet, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { - CommandDefinitionError, - commandErrorCodes, - commandExitCodes, - createCommandRegistry, - createPackageRegistry, - declaredCodes, - type CommandDefinition, - type CommandPackage, -} from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { classifyError, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { coreCodes, ENGINE_SYNC, EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { chainCodes, READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { CodeDefinitionError, defineCodeSet, defineCodes, CommandDefinitionError, commandErrorCodes, commandExitCodes, createCommandRegistry, createPackageRegistry, declaredCodes, type CommandDefinition, type CommandPackage, classifyError, ERROR_CODES } from '@kuiralabs/midnight-cli-core'; +import { coreCodes, ENGINE_SYNC, EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCodes, READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { installedCommands } from '../lib/installed-commands.ts'; /** A package with no commands and no guidance: only codes. */ diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 4a60c5ac..27d6f471 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -1,13 +1,9 @@ import { describe, it, expect } from 'vitest'; -import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR, EXIT_INVALID_ARGS, WrongPassphraseError, OtherSdkSetError, UsageError } from '@kuiralabs/midnight-cli-core'; +import { MixedSdkLayoutError, toEngineError } from '@kuiralabs/midnight-cli-core/engine'; import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; import { NoAccountError } from '../lib/grant/prepare.ts'; -import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { NoPassphraseError } from '../lib/passphrase.ts'; -import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { MixedSdkLayoutError } from '@kuiralabs/midnight-cli-core/lib/sdk-layout'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; import { installedCommands } from '../lib/installed-commands.ts'; describe('humanizeNetworkError', () => { @@ -57,10 +53,10 @@ describe('classifyError usage errors (positional-address balance)', () => { describe('classifyError: typed setup errors keep their own code', () => { // Agents read errorCode from --json / MCP; these must not collapse to UNKNOWN. it.each([ - ['UNSUPPORTED_LEDGER', async () => new (await import('@kuiralabs/midnight-chain/lib/ledger-guard')).UnsupportedLedgerError('preview', 1000300n)], - ['LOCAL_STACK_UNREACHABLE', async () => new (await import('@kuiralabs/midnight-chain/lib/ledger-guard')).LocalStackUnreachableError('indexer', 'http://localhost:8088/api/v4/graphql')], + ['UNSUPPORTED_LEDGER', async () => new (await import('@kuiralabs/midnight-chain')).UnsupportedLedgerError('preview', 1000300n)], + ['LOCAL_STACK_UNREACHABLE', async () => new (await import('@kuiralabs/midnight-chain')).LocalStackUnreachableError('indexer', 'http://localhost:8088/api/v4/graphql')], ['LOCALNET_UNAVAILABLE', async () => new (await import('../lib/localnet.ts')).LocalnetUnavailableError()], - ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('@kuiralabs/midnight-cli-core/lib/network')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], + ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('@kuiralabs/midnight-cli-core')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], ])('%s', async (code, make) => { const result = classifyError(await make(), installedCommands); expect(result.errorCode).toBe(code); diff --git a/src/__tests__/fixtures/code-reach/barrel-handler.ts b/src/__tests__/fixtures/code-reach/barrel-handler.ts new file mode 100644 index 00000000..e5c32b89 --- /dev/null +++ b/src/__tests__/fixtures/code-reach/barrel-handler.ts @@ -0,0 +1,7 @@ +// The barrel fixture command's handler: it refuses every call, through the barrel's refuse. + +import { refuse } from './barrel.ts'; + +export default async function barrelFixtureCommand(): Promise { + refuse('the fixture takes no offer'); +} diff --git a/src/__tests__/fixtures/code-reach/barrel.definition.ts b/src/__tests__/fixtures/code-reach/barrel.definition.ts new file mode 100644 index 00000000..ba43a265 --- /dev/null +++ b/src/__tests__/fixtures/code-reach/barrel.definition.ts @@ -0,0 +1,14 @@ +// A command for the code reach check whose handler imports one name from a +// barrel: it reaches that name's module and no other the barrel lists. + +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; + +export const barrelFixtureDefinition: CommandDefinition = { + name: 'code-reach-barrel-fixture', + order: 9_999, + flags: [], + needsWalletSdk: false, + shell: {}, + errors: { codes: [] }, + load: () => import('./barrel-handler.ts'), +}; diff --git a/src/__tests__/fixtures/code-reach/barrel.ts b/src/__tests__/fixtures/code-reach/barrel.ts new file mode 100644 index 00000000..0f6ea751 --- /dev/null +++ b/src/__tests__/fixtures/code-reach/barrel.ts @@ -0,0 +1,5 @@ +// A barrel for the code reach check: a handler that imports refuse through it +// reaches refuses.ts, and not unpaid.ts, whose code it never calls. + +export { refuse } from './refuses.ts'; +export { refuseUnpaid } from './unpaid.ts'; diff --git a/src/__tests__/fixtures/code-reach/fixture.definition.ts b/src/__tests__/fixtures/code-reach/fixture.definition.ts index 7f66356f..7be3f442 100644 --- a/src/__tests__/fixtures/code-reach/fixture.definition.ts +++ b/src/__tests__/fixtures/code-reach/fixture.definition.ts @@ -1,7 +1,7 @@ // A command for the code reach check: its handler imports a module that throws // NotAnOfferError (NOT_AN_OFFER), and it declares no code. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; export const fixtureDefinition: CommandDefinition = { name: 'code-reach-fixture', diff --git a/src/__tests__/fixtures/code-reach/refuses.ts b/src/__tests__/fixtures/code-reach/refuses.ts index 94ec5018..5edf2ce5 100644 --- a/src/__tests__/fixtures/code-reach/refuses.ts +++ b/src/__tests__/fixtures/code-reach/refuses.ts @@ -1,6 +1,6 @@ // What the fixture command's handler imports: it throws a coded error. -import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/engine'; export function refuse(reason: string): never { throw new NotAnOfferError(reason); diff --git a/src/__tests__/fixtures/code-reach/unpaid.ts b/src/__tests__/fixtures/code-reach/unpaid.ts new file mode 100644 index 00000000..2a8c4986 --- /dev/null +++ b/src/__tests__/fixtures/code-reach/unpaid.ts @@ -0,0 +1,7 @@ +// Listed by the fixture barrel beside refuses.ts: it throws NoPayerError (NO_PAYER). + +import { NoPayerError } from '@kuiralabs/midnight-cli-core'; + +export function refuseUnpaid(command: string): never { + throw new NoPayerError(command); +} diff --git a/src/__tests__/fixtures/layering/by-entry-point.ts b/src/__tests__/fixtures/layering/by-entry-point.ts new file mode 100644 index 00000000..0d9a72df --- /dev/null +++ b/src/__tests__/fixtures/layering/by-entry-point.ts @@ -0,0 +1,6 @@ +// A test file for the layering check that imports core by its entry points: it passes. + +import { UsageError } from '@kuiralabs/midnight-cli-core'; +import { toHex } from '@kuiralabs/midnight-cli-core/engine'; + +export const passed = [UsageError, toHex]; diff --git a/src/__tests__/fixtures/layering/by-path.ts b/src/__tests__/fixtures/layering/by-path.ts new file mode 100644 index 00000000..83223797 --- /dev/null +++ b/src/__tests__/fixtures/layering/by-path.ts @@ -0,0 +1,6 @@ +// A test file for the layering check that reaches into core's source by path +// instead of by an entry point: the check refuses it. + +import { UsageError } from '../../../../packages/cli-core/src/lib/errors.ts'; + +export const refused = UsageError; diff --git a/src/__tests__/fixtures/layering/deep-import.ts b/src/__tests__/fixtures/layering/deep-import.ts new file mode 100644 index 00000000..4a3a5de7 --- /dev/null +++ b/src/__tests__/fixtures/layering/deep-import.ts @@ -0,0 +1,7 @@ +// A test file for the layering check that imports a module of core that is +// not one of its entry points: the check refuses it, naming the entry points. + +// @ts-expect-error core's exports map has no ./lib/errors, so TypeScript finds no module either +import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; + +export const refused = UsageError; diff --git a/src/__tests__/fixtures/record-swap-offer.ts b/src/__tests__/fixtures/record-swap-offer.ts index aff30dfa..d89cd36a 100644 --- a/src/__tests__/fixtures/record-swap-offer.ts +++ b/src/__tests__/fixtures/record-swap-offer.ts @@ -13,9 +13,7 @@ import { mkdtempSync, writeFileSync } from 'node:fs'; import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { settingsFromEnvironment, createHost, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from '../../lib/installed-engines.ts'; const GIVE = '00'.repeat(31) + '01'; diff --git a/src/__tests__/generate-command.test.ts b/src/__tests__/generate-command.test.ts index 413f1b6f..bf94771c 100644 --- a/src/__tests__/generate-command.test.ts +++ b/src/__tests__/generate-command.test.ts @@ -3,14 +3,14 @@ import { mnemonicToSeedSync } from '@scure/bip39'; import generateCommand from '../commands/generate.ts'; import { unlockWallet } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped. const host = testHost(); diff --git a/src/__tests__/genesis-address-command.test.ts b/src/__tests__/genesis-address-command.test.ts index 6b4945c4..f8dc5b95 100644 --- a/src/__tests__/genesis-address-command.test.ts +++ b/src/__tests__/genesis-address-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import genesisAddressCommand from '../commands/genesis-address.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; let io: CapturedOutput; diff --git a/src/__tests__/grant-account.test.ts b/src/__tests__/grant-account.test.ts index f7e59209..06e5cca4 100644 --- a/src/__tests__/grant-account.test.ts +++ b/src/__tests__/grant-account.test.ts @@ -8,13 +8,11 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { WrongPassphraseError, getNetworkConfig, createHost } from '@kuiralabs/midnight-cli-core'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; import { openGrantAccount } from '../lib/grant/account.ts'; import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. diff --git a/src/__tests__/grant-deploy-cost.test.ts b/src/__tests__/grant-deploy-cost.test.ts index cd4b0eeb..40166caa 100644 --- a/src/__tests__/grant-deploy-cost.test.ts +++ b/src/__tests__/grant-deploy-cost.test.ts @@ -1,9 +1,8 @@ // What an owner is told when an account deploy stops for want of Dust. import { describe, expect, it } from 'vitest'; -import { ERROR_CODES, EXIT_INSUFFICIENT_BALANCE, classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { ERROR_CODES, EXIT_INSUFFICIENT_BALANCE, classifyError, DustRequiredError } from '@kuiralabs/midnight-cli-core'; import { MEASURED_ACCOUNT_DEPLOY, deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; -import { DustRequiredError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { installedCommands } from '../lib/installed-commands.ts'; describe('deployShortOfDustNote', () => { diff --git a/src/__tests__/grant-owner-commands.test.ts b/src/__tests__/grant-owner-commands.test.ts index 7f9007e1..18eae747 100644 --- a/src/__tests__/grant-owner-commands.test.ts +++ b/src/__tests__/grant-owner-commands.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { freshGrantee, grantRequestFor, grantRequestLink } from '@kuiralabs/midnight-account-chain/agent'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; import { DEFAULT_GRANT_LIMITS, grantRequestOf, issuePreview } from '../lib/grant/owner-commands.ts'; const ACCOUNT = '5e'.repeat(32); diff --git a/src/__tests__/grant-prepare.test.ts b/src/__tests__/grant-prepare.test.ts index 9db88df3..1efc4cfc 100644 --- a/src/__tests__/grant-prepare.test.ts +++ b/src/__tests__/grant-prepare.test.ts @@ -6,12 +6,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { parseArgs, UsageError, createHost } from '@kuiralabs/midnight-cli-core'; import { UnreachableByAccountError } from '../lib/grant/account.ts'; import { NoAccountError, prepareGrant } from '../lib/grant/prepare.ts'; import { createAccountKey, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/grant-request.test.ts b/src/__tests__/grant-request.test.ts index 0c5e2c7d..1bbf2d36 100644 --- a/src/__tests__/grant-request.test.ts +++ b/src/__tests__/grant-request.test.ts @@ -1,8 +1,7 @@ // What `mn grant` is asked to do, checked from its arguments alone. import { describe, expect, it } from 'vitest'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { parseArgs, UsageError } from '@kuiralabs/midnight-cli-core'; import { describeGrantTerms, paysAFee, resolveGrantRequest } from '../lib/grant/request.ts'; const request = (...argv: string[]) => resolveGrantRequest(parseArgs(['grant', ...argv])); diff --git a/src/__tests__/heap-guard.test.ts b/src/__tests__/heap-guard.test.ts index 6b57f116..11711acf 100644 --- a/src/__tests__/heap-guard.test.ts +++ b/src/__tests__/heap-guard.test.ts @@ -1,10 +1,6 @@ import { describe, it, expect } from 'vitest'; import { computeHeapTargetMb } from '../lib/heap-guard.ts'; -import { - SYNC_HEAP_TARGET_MB, - SYNC_HEAP_RAM_FRACTION, - SYNC_HEAP_MIN_GAIN_MB, -} from '@kuiralabs/midnight-cli-core/lib/constants'; +import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB } from '@kuiralabs/midnight-cli-core'; describe('computeHeapTargetMb', () => { // The OOM repro: a 128 GB box with Node's default ~4.3 GB old-space cap. diff --git a/src/__tests__/help-agent.test.ts b/src/__tests__/help-agent.test.ts index deba5361..21da871d 100644 --- a/src/__tests__/help-agent.test.ts +++ b/src/__tests__/help-agent.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import helpCommand from '../commands/help.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; let io: CapturedOutput; @@ -32,7 +32,7 @@ describe('help --agent', () => { }); it('lists every error code mn can return', async () => { - const { ERROR_CODES } = await import('@kuiralabs/midnight-cli-core/lib/exit-codes'); + const { ERROR_CODES } = await import('@kuiralabs/midnight-cli-core'); await cliCall(helpCommand, parseArgs(['help', '--agent'])); const table = io.stdout().split('ERROR CODES')[1]!.split('MCP SERVER')[0]!; const missing = Object.values(ERROR_CODES).filter((code) => !new RegExp(`^ ${code}\\s+\\d`, 'm').test(table)); diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index 35fef913..908f3888 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -1,9 +1,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import helpCommand, { helpSpecs } from '../commands/help.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, declaredCodes } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; -import { declaredCodes } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; let io: CapturedOutput; diff --git a/src/__tests__/helpers/cli-call.ts b/src/__tests__/helpers/cli-call.ts index 52f0e36f..16cac5df 100644 --- a/src/__tests__/helpers/cli-call.ts +++ b/src/__tests__/helpers/cli-call.ts @@ -2,12 +2,9 @@ // shell builds one, its result written at once to stdout as one JSON line. // Tests that read a command's output from the process's streams call it so. -import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { createCallContext, runHandler, type CommandHandler, type CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { type ParsedArgs, createCallContext, runHandler, type CommandHandler, type CommandOutcome, type Payer, type Host } from '@kuiralabs/midnight-cli-core'; import { processOutput } from '../../lib/command-dispatch.ts'; -import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { testHost } from './test-host.ts'; +import { testHost } from '../../../test-support/test-host.ts'; export interface CliCallOptions { /** The call's cancellation; none: it is never cancelled. */ diff --git a/src/__tests__/helpers/engine-boundary-suite.ts b/src/__tests__/helpers/engine-boundary-suite.ts index e946e295..3a7a288a 100644 --- a/src/__tests__/helpers/engine-boundary-suite.ts +++ b/src/__tests__/helpers/engine-boundary-suite.ts @@ -14,11 +14,8 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; // The wallet SDK's copy of Effect (both engines' SDKs share it). import { Effect } from 'effect'; -import type { Engine, EngineHost } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { DustRequiredError, InsufficientBalanceError, ProofFailureError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type Engine, type NetworkConfig, createHost, classifyError, DustRequiredError, InsufficientBalanceError, ProofFailureError, TransactionRefusedError } from '@kuiralabs/midnight-cli-core'; +import type { EngineHost } from '@kuiralabs/midnight-cli-core/engine'; import { installedCommands } from '../../lib/installed-commands.ts'; /** What the suite takes from an engine: how to make it with its repository's seams, and the SDK's error classes from its own copy. */ diff --git a/src/__tests__/helpers/engine-transfer-suite.ts b/src/__tests__/helpers/engine-transfer-suite.ts index b3e1cf5e..13083879 100644 --- a/src/__tests__/helpers/engine-transfer-suite.ts +++ b/src/__tests__/helpers/engine-transfer-suite.ts @@ -11,11 +11,9 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import type { Engine, EngineHost, TransferParams } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { type Engine, type NetworkConfig, createHost, withCallSdkWarnings } from '@kuiralabs/midnight-cli-core'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; +import type { EngineHost, TransferParams } from '@kuiralabs/midnight-cli-core/engine'; /** What the suite takes from an engine: how to make it with its repository's protocol-version read. */ export interface TransferEngine { diff --git a/src/__tests__/helpers/expect-declared.ts b/src/__tests__/helpers/expect-declared.ts index 539f37fb..5e428ca6 100644 --- a/src/__tests__/helpers/expect-declared.ts +++ b/src/__tests__/helpers/expect-declared.ts @@ -5,10 +5,8 @@ // the code; this checks them against what the commands the tests run do. import { expect } from 'vitest'; -import { declaredCodes } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { asReported } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { declaredCodes, asReported, classifyError } from '@kuiralabs/midnight-cli-core'; +import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands'; import { installedCommands } from '../../lib/installed-commands.ts'; /** diff --git a/src/__tests__/helpers/own-call.ts b/src/__tests__/helpers/own-call.ts index 228fd6d0..8ea35392 100644 --- a/src/__tests__/helpers/own-call.ts +++ b/src/__tests__/helpers/own-call.ts @@ -2,7 +2,7 @@ // outside any host: no host's filters report to it. import type { CommandRun } from '../../lib/run-command.ts'; -import { testHost } from './test-host.ts'; +import { testHost } from '../../../test-support/test-host.ts'; export function ownCall(run: Omit & { host?: CommandRun['host'] } = {}): CommandRun { return { ...run, host: run.host ?? testHost() }; diff --git a/src/__tests__/helpers/plain-wallet.ts b/src/__tests__/helpers/plain-wallet.ts index 0be74222..a7d4aed0 100644 --- a/src/__tests__/helpers/plain-wallet.ts +++ b/src/__tests__/helpers/plain-wallet.ts @@ -5,8 +5,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { DIR_MODE, FILE_MODE, type NetworkName } from '@kuiralabs/midnight-cli-core'; export interface PlainWalletConfig { seed: string; diff --git a/src/__tests__/helpers/serve-script-failure.ts b/src/__tests__/helpers/serve-script-failure.ts index d9529bab..d0ea4414 100644 --- a/src/__tests__/helpers/serve-script-failure.ts +++ b/src/__tests__/helpers/serve-script-failure.ts @@ -11,7 +11,7 @@ import { pathToFileURL } from 'node:url'; import type { AddressInfo } from 'node:net'; import { SCRIPT_PRELUDE, executeScript, rpcClientCode } from '../../lib/contract/runner.ts'; import { createRpcServer } from '../../lib/ws-rpc.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { createHost } from '@kuiralabs/midnight-cli-core'; /** What the runner rejects with when a script's call to mn serve fails with what `failure` throws. */ export async function scriptFailureAtServe(failure: () => unknown): Promise { diff --git a/src/__tests__/helpers/state-root-in.ts b/src/__tests__/helpers/state-root-in.ts index 9e57e498..f27a54d1 100644 --- a/src/__tests__/helpers/state-root-in.ts +++ b/src/__tests__/helpers/state-root-in.ts @@ -1,6 +1,6 @@ // The state root the CLI would keep under a test's home: its .midnight folder. import { join } from 'node:path'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core'; export const stateRootIn = (home: string): string => join(home, MIDNIGHT_DIR); diff --git a/src/__tests__/host-engines.test.ts b/src/__tests__/host-engines.test.ts index f80e027c..0ed33bed 100644 --- a/src/__tests__/host-engines.test.ts +++ b/src/__tests__/host-engines.test.ts @@ -7,14 +7,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { BalanceSummary } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { createHost, type Host, type SdkSet, type NetworkConfig, type PayingTarget } from '@kuiralabs/midnight-cli-core'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; +import type { BalanceSummary } from '@kuiralabs/midnight-chain'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import { listWallets } from '../lib/wallet-config.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; @@ -28,7 +25,7 @@ const NETWORK: NetworkConfig = { networkId: 'Undeployed', }; const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; -const ADDRESSES = deriveAllAddresses(Buffer.from(SEED, 'hex')); +const ADDRESSES = rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')); const empty = (): BalanceSummary => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }); let root: string; diff --git a/src/__tests__/host-paths.test.ts b/src/__tests__/host-paths.test.ts index 585cfce1..6ad80ec0 100644 --- a/src/__tests__/host-paths.test.ts +++ b/src/__tests__/host-paths.test.ts @@ -7,14 +7,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { openOffersFile, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import { cacheRootDir, getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; +import { createHost, type Host, parseArgs, MIDNIGHT_DIR, loadCliConfig, sdkSetOf, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; +import { cacheRootDir, getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { captureCommand } from '../lib/run-command.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; @@ -23,6 +18,9 @@ import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { clearChainCaches } from '../lib/chain-caches.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; +// The config handler, as the shell loads it. +const { default: configCommand } = await configDefinition.load(); + const PASSPHRASE = 'correct horse battery staple'; const MAKER = 'mn_addr_undeployed1maker'; const OFFER: OpenOffer = { @@ -105,7 +103,7 @@ describe('two hosts with different state roots', () => { expect(readOpenOffers(rootA, 'undeployed', MAKER)).toEqual([OFFER]); expect(readOpenOffers(rootB, 'undeployed', MAKER)).toEqual([]); - expect(openOffersFile(rootA, 'undeployed', MAKER)).toBe(path.join(rootA, 'swap-offers', 'undeployed', `${MAKER}.json`)); + expect(fs.existsSync(path.join(rootA, 'swap-offers', 'undeployed', `${MAKER}.json`))).toBe(true); expect(fs.existsSync(path.join(rootB, 'swap-offers'))).toBe(false); }); diff --git a/src/__tests__/host-slots.test.ts b/src/__tests__/host-slots.test.ts index 2c8988e8..09f5452a 100644 --- a/src/__tests__/host-slots.test.ts +++ b/src/__tests__/host-slots.test.ts @@ -9,14 +9,13 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { WebSocket } from 'ws'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { createHost, type Host, type Prompter } from '@kuiralabs/midnight-cli-core'; +import { promptApproval } from '@kuiralabs/midnight-cli-core/engine'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import { promptApproval } from '@kuiralabs/midnight-cli-core/lib/approval'; import { NoPassphraseError, PASSPHRASE_ENV, establishPassphrase, unlockPassphrase } from '../lib/passphrase.ts'; import { unlockWallet } from '../lib/wallet-config.ts'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; @@ -94,7 +93,7 @@ describe('the plain-text wallet warning', () => { it("is said once per host, through that host's notices", async () => { const root = stateRootIn(home); const wallet = saveWalletConfig( - { seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-11-03T00:00:00.000Z' }, + { seed: SEED, addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-11-03T00:00:00.000Z' }, path.join(root, 'wallets', 'plain.json'), ); const saidA: string[] = []; diff --git a/src/__tests__/info-command.test.ts b/src/__tests__/info-command.test.ts index ca9d88c6..8078cef8 100644 --- a/src/__tests__/info-command.test.ts +++ b/src/__tests__/info-command.test.ts @@ -1,9 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import infoCommand from '../commands/info.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -12,7 +12,7 @@ import { cliCall } from './helpers/cli-call.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-info-cmd-test-${process.pid}`); const TEST_SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; -const TEST_ADDRESSES = deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')); +const TEST_ADDRESSES = rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')); const TEST_CONFIG: WalletConfig = { seed: TEST_SEED, diff --git a/src/__tests__/inspect-cost-command.test.ts b/src/__tests__/inspect-cost-command.test.ts index 1388ef7c..f492cf44 100644 --- a/src/__tests__/inspect-cost-command.test.ts +++ b/src/__tests__/inspect-cost-command.test.ts @@ -5,10 +5,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; -import { LEDGER9_PARAMETERS_HEX } from './fixtures/ledger9-parameters.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../test-support/local-indexer.ts'; +import { LEDGER9_PARAMETERS_HEX } from '../../test-support/fixtures/ledger9-parameters.ts'; import { cliCall } from './helpers/cli-call.ts'; let io: CapturedOutput; diff --git a/src/__tests__/json-fields.test.ts b/src/__tests__/json-fields.test.ts index 121a3bef..f5456e3d 100644 --- a/src/__tests__/json-fields.test.ts +++ b/src/__tests__/json-fields.test.ts @@ -7,10 +7,9 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, type CommandHandler } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { captureCommand } from '../lib/run-command.ts'; -import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { ownCall } from './helpers/own-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index bbdab2ef..7bd58d24 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -1,10 +1,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; -import { classifyError, EXIT_NETWORK_ERROR, EXIT_INSUFFICIENT_BALANCE, EXIT_TX_REJECTED, EXIT_GENERAL_ERROR, ERROR_CODES } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { toEngineError } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; +import { parseArgs, classifyError, EXIT_NETWORK_ERROR, EXIT_INSUFFICIENT_BALANCE, EXIT_TX_REJECTED, EXIT_GENERAL_ERROR, ERROR_CODES, writeJsonResult, writeJsonError, loadCliConfig } from '@kuiralabs/midnight-cli-core'; +import { toEngineError } from '@kuiralabs/midnight-cli-core/engine'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { installedCommands } from '../lib/installed-commands.ts'; -import { writeJsonResult, writeJsonError } from '@kuiralabs/midnight-cli-core/lib/json-output'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -15,22 +13,24 @@ import infoCommand from '../commands/info.ts'; import addressCommand from '../commands/address.ts'; import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; +import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import helpCommand from '../commands/help.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { localIndexerFlags } from './helpers/local-indexer.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { localIndexerFlags } from '../../test-support/local-indexer.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; +// The config handler, as the shell loads it. +const { default: configCommand } = await configDefinition.load(); + const TEST_DIR = path.join(os.tmpdir(), `midnight-json-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; const TEST_CONFIG_SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; const TEST_CONFIG: WalletConfig = { seed: TEST_CONFIG_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_CONFIG_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_CONFIG_SEED, 'hex')), createdAt: '2026-01-15T10:30:00.000Z', }; diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index e42494d7..5be72529 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -1,8 +1,15 @@ // The package layering, checked on every run of the suite: every file of src/ // has a package, and no import crosses the layering the planned split needs. +// A workspace package is imported by its entry points alone, in code, tests +// and scripts. +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { findLayeringProblems, importRule } from '../../scripts/check-layering.mjs'; +import { findLayeringProblems, importRule, importedModules, testProblems } from '../../scripts/check-layering.mjs'; + +const ROOT = join(import.meta.dirname, '..', '..'); +const FIXTURES = join(import.meta.dirname, 'fixtures', 'layering'); +const fromRoot = (file: string) => file.slice(ROOT.length + 1); describe('the layering', () => { it('holds across src/', () => { @@ -69,3 +76,32 @@ describe('the layering', () => { expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); }); }); + +describe('a workspace package imported by its entry points', () => { + it('refuses a deep import across packages, naming the entry points', () => { + expect(testProblems(join(FIXTURES, 'deep-import.ts')).map((v) => `${v.rule}: ${v.where} ${v.specifier}`)).toStrictEqual([ + 'deep import into @kuiralabs/midnight-cli-core (its entry points: ., ./engine, ./ui, ./commands): src/__tests__/fixtures/layering/deep-import.ts:5 @kuiralabs/midnight-cli-core/lib/errors', + ]); + }); + + it("refuses a test reaching into another package's source by path", () => { + expect(testProblems(join(FIXTURES, 'by-path.ts')).map((v) => `${v.rule}: ${v.where}`)).toStrictEqual([ + 'test → another package by path (a test imports another package by its entry points): src/__tests__/fixtures/layering/by-path.ts:4', + ]); + }); + + it('passes an import of an entry point', () => { + expect(testProblems(join(FIXTURES, 'by-entry-point.ts'))).toStrictEqual([]); + }); + + it('judges an import of a barrel by the modules defining the names it imports', () => { + const file = join(ROOT, 'src', 'lib', 'facade.ts'); + const modules = (names: { name: string; typeOnly: boolean }[] | null) => + importedModules(file, { specifier: '@kuiralabs/midnight-cli-core/engine', typeOnly: false, names })!.modules!.map((each) => fromRoot(each.file)); + expect(modules([{ name: 'toEngineError', typeOnly: false }])).toStrictEqual(['packages/cli-core/src/lib/sdk-errors.ts']); + expect(modules([{ name: 'toHex', typeOnly: false }, { name: 'EngineHost', typeOnly: true }])).toStrictEqual(['packages/cli-core/src/lib/tx-serde.ts', 'packages/cli-core/src/lib/engine.ts']); + // So a package that may not read the SDK's errors is refused them through the barrel too. + expect(importRule('lib/facade.ts', 'lib/sdk-errors.ts')).toBe("wallet → the SDK's errors (only an engine reads them)"); + expect(modules(null)).toContain('packages/cli-core/src/lib/wallet-cache.ts'); + }); +}); diff --git a/src/__tests__/localnet-cancellation.test.ts b/src/__tests__/localnet-cancellation.test.ts index 6ffbb24c..51e6c724 100644 --- a/src/__tests__/localnet-cancellation.test.ts +++ b/src/__tests__/localnet-cancellation.test.ts @@ -13,11 +13,9 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { runLocalnet } from '../commands/localnet.ts'; import { startLocalnet, type DockerCall } from '../lib/localnet.ts'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { ExecRun, ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; +import { CancelledError, type ExecRun, type ExecRunner, parseArgs } from '@kuiralabs/midnight-cli-core'; import { captureCommand } from '../lib/run-command.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { ownCall } from './helpers/own-call.ts'; /** One run the stand-in was given. */ diff --git a/src/__tests__/localnet-command.test.ts b/src/__tests__/localnet-command.test.ts index 4b26f2e7..47599bfb 100644 --- a/src/__tests__/localnet-command.test.ts +++ b/src/__tests__/localnet-command.test.ts @@ -3,8 +3,8 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; import localnetCommand from '../commands/localnet.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { parseArgs, commandHelpSpecs, introBriefs } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { existsSync, statSync } from 'fs'; import { COMPOSE_YAML, @@ -15,7 +15,6 @@ import { parseServiceStatus, } from '../lib/localnet.ts'; import helpCommand from '../commands/help.ts'; -import { commandHelpSpecs, introBriefs } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { installedCommands } from '../lib/installed-commands.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/manual-command.test.ts b/src/__tests__/manual-command.test.ts index 7633faf6..61acd679 100644 --- a/src/__tests__/manual-command.test.ts +++ b/src/__tests__/manual-command.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { buildManual } from '../commands/manual.ts'; -import { getConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; +import { getConfigValue } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; function stripAnsi(s: string): string { diff --git a/src/__tests__/mcp-registry-tools.test.ts b/src/__tests__/mcp-registry-tools.test.ts index 442d253e..df59cf22 100644 --- a/src/__tests__/mcp-registry-tools.test.ts +++ b/src/__tests__/mcp-registry-tools.test.ts @@ -4,11 +4,9 @@ // installed tools' descriptions. import { describe, expect, it } from 'vitest'; -import { createCommandRegistry, type CommandDefinition, type ToolDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { createCommandRegistry, type CommandDefinition, type ToolDefinition, type CallContext, MINIMAL_FLAG, type ParsedArgs } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { CONFIRM_TOOL, confirmationFor, findTool, listedTools, runTool } from '../lib/mcp/registry-tools.ts'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { MINIMAL_FLAG, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; import { ownCall } from './helpers/own-call.ts'; const received: ParsedArgs[] = []; diff --git a/src/__tests__/mcp-server-advice.test.ts b/src/__tests__/mcp-server-advice.test.ts index 8a427791..2d4b1ece 100644 --- a/src/__tests__/mcp-server-advice.test.ts +++ b/src/__tests__/mcp-server-advice.test.ts @@ -4,7 +4,7 @@ import { afterAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core'; import { withServerAdvice } from '../lib/mcp/server-advice.ts'; // A state root with no config: every network on the set the table names. diff --git a/src/__tests__/mcp-server-concurrent-calls.test.ts b/src/__tests__/mcp-server-concurrent-calls.test.ts index 85d412f7..3033965c 100644 --- a/src/__tests__/mcp-server-concurrent-calls.test.ts +++ b/src/__tests__/mcp-server-concurrent-calls.test.ts @@ -21,15 +21,15 @@ import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.js'; -import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { toNight } from '@kuiralabs/midnight-cli-core/ui/format'; -import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { toNight } from '@kuiralabs/midnight-cli-core/ui'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; import { expectDeclaredToolResult } from './helpers/expect-declared.ts'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); const TSX = path.join(REPO, 'node_modules', '.bin', 'tsx'); -const addressOf = (byte: string): string => deriveUnshieldedAddress(Buffer.from(byte.repeat(32), 'hex'), 'undeployed'); +const addressOf = (byte: string): string => rcKeys.unshieldedAddress(Buffer.from(byte.repeat(32), 'hex'), 'undeployed'); const ADDRESS_A = addressOf('aa'); const ADDRESS_B = addressOf('bb'); const ADDRESS_C = addressOf('cc'); diff --git a/src/__tests__/mcp-server-progress.test.ts b/src/__tests__/mcp-server-progress.test.ts index f2cbec88..0eae3ec1 100644 --- a/src/__tests__/mcp-server-progress.test.ts +++ b/src/__tests__/mcp-server-progress.test.ts @@ -14,7 +14,7 @@ import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import type { JSONRPCMessage, Progress } from '@modelcontextprotocol/sdk/types.js'; -import { startRefusingEndpoint } from './helpers/stand-in-indexer.ts'; +import { startRefusingEndpoint } from '../../test-support/stand-in-indexer.ts'; import { expectDeclaredToolResult } from './helpers/expect-declared.ts'; const REPO = fileURLToPath(new URL('../..', import.meta.url)); diff --git a/src/__tests__/mcp-server.test.ts b/src/__tests__/mcp-server.test.ts index 4cbc7fee..1bcf6e8a 100644 --- a/src/__tests__/mcp-server.test.ts +++ b/src/__tests__/mcp-server.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { commandHelpSpecs } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { commandHelpSpecs } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { listedTools } from '../lib/mcp/registry-tools.ts'; diff --git a/src/__tests__/multi-wallet.test.ts b/src/__tests__/multi-wallet.test.ts index 35879103..982c9726 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/src/__tests__/multi-wallet.test.ts @@ -12,22 +12,8 @@ import { } from '../lib/wallet-config.ts'; import { migrateOldWallet } from '../lib/wallet-paths.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { - loadCliConfig, - saveCliConfig, - type CliConfig, -} from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { - MIDNIGHT_DIR, - WALLETS_DIR_NAME, - DEFAULT_WALLET_NAME, - DEFAULT_WALLET_FILENAME, - DIR_MODE, - FILE_MODE, - isValidWalletName, -} from '@kuiralabs/midnight-cli-core/lib/constants'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { loadCliConfig, saveCliConfig, type CliConfig, MIDNIGHT_DIR, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, DEFAULT_WALLET_FILENAME, DIR_MODE, FILE_MODE, isValidWalletName, createHost } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The engines the wallet functions derive a wallet's missing addresses with: a host's of the engines the CLI ships. @@ -44,13 +30,13 @@ const SEED_2 = '1111111111111111111111111111111111111111111111111111111111111111 const VALID_WALLET: WalletConfig = { seed: SEED_1, - addresses: deriveAllAddresses(Buffer.from(SEED_1, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED_1, 'hex')), createdAt: '2025-01-01T00:00:00.000Z', }; const VALID_WALLET_2: WalletConfig = { seed: SEED_2, - addresses: deriveAllAddresses(Buffer.from(SEED_2, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED_2, 'hex')), createdAt: '2025-02-01T00:00:00.000Z', }; diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index 01810923..7c065e31 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -11,17 +11,16 @@ import { createServer, type Server } from 'node:http'; import { createServer as createTcpServer, type AddressInfo, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, type CommandHandler } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { establishPassphrase } from '../lib/passphrase.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; -import type { CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); diff --git a/src/__tests__/node-version.test.ts b/src/__tests__/node-version.test.ts index c4185a9d..9f6c3208 100644 --- a/src/__tests__/node-version.test.ts +++ b/src/__tests__/node-version.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { MIN_NODE_MAJOR, UnsupportedNodeError, assertNodeSupported } from '../lib/node-version.ts'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { classifyError } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; describe('assertNodeSupported', () => { diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index d51ecd8b..19a07dea 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -7,10 +7,10 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { createHost } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { unlockWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; const ROOT = path.resolve(import.meta.dirname, '..', '..'); @@ -29,7 +29,7 @@ afterEach(() => { }); const plainWallet = (name: string): string => - saveWalletConfig({ seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-10-19T00:00:00.000Z' }, path.join(home, '.midnight', 'wallets', `${name}.json`)); + saveWalletConfig({ seed: SEED, addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-10-19T00:00:00.000Z' }, path.join(home, '.midnight', 'wallets', `${name}.json`)); describe('notices', () => { it("carry a library's warning to its host's notices when its caller gives no warn of its own, and nowhere when the host takes none", async () => { diff --git a/src/__tests__/passphrase.test.ts b/src/__tests__/passphrase.test.ts index 759fb919..b0b4ae5e 100644 --- a/src/__tests__/passphrase.test.ts +++ b/src/__tests__/passphrase.test.ts @@ -8,7 +8,8 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { PassThrough } from 'node:stream'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { WrongPassphraseError, FILE_MODE, createHost } from '@kuiralabs/midnight-cli-core'; +import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui'; import { NoPassphraseError, PASSPHRASE_ENV, @@ -19,10 +20,7 @@ import { readPassphrase, unlockPassphrase, } from '../lib/passphrase.ts'; -import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { createTerminalPrompter } from '@kuiralabs/midnight-cli-core/ui/terminal-prompter'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index c83efe4f..df4268e1 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -7,23 +7,16 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { NoPayerError, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { parseArgs, saveCliConfig, NoPayerError, resolvePayingTarget, networkTargetOf, type NetworkName, createSdkWarningRouter, CancelledError, createHost } from '@kuiralabs/midnight-cli-core'; +import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; import { NoAccountError } from '../lib/grant/prepare.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; import { probeServeNetwork } from '../lib/serve-manager.ts'; -import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import contractCommand from '../commands/contract.ts'; import grantCommand from '../commands/grant.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/prep-runner-cancellation.test.ts b/src/__tests__/prep-runner-cancellation.test.ts index e4680f91..b146301e 100644 --- a/src/__tests__/prep-runner-cancellation.test.ts +++ b/src/__tests__/prep-runner-cancellation.test.ts @@ -4,9 +4,7 @@ import { describe, expect, it } from 'vitest'; import { runPrepSteps } from '../lib/test/prep-runner.ts'; import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; -import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { CancelledError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { createSdkWarningRouter, CancelledError, createHost } from '@kuiralabs/midnight-cli-core'; // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/protect-account.test.ts b/src/__tests__/protect-account.test.ts index fdd845d4..407176e9 100644 --- a/src/__tests__/protect-account.test.ts +++ b/src/__tests__/protect-account.test.ts @@ -13,12 +13,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { type FeeWallet, accountProviders, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_ID } from '@kuiralabs/midnight-account-chain/contract'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { getNetworkConfig, createHost } from '@kuiralabs/midnight-cli-core'; import { LEGACY_STORE_PASSWORD, openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { AccountMigrationInterruptedError, protectAccount } from '../lib/grant/protect-account.ts'; import { isSealedAccount } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. diff --git a/src/__tests__/publish-manifest.test.ts b/src/__tests__/publish-manifest.test.ts new file mode 100644 index 00000000..713ab109 --- /dev/null +++ b/src/__tests__/publish-manifest.test.ts @@ -0,0 +1,48 @@ +// A workspace package is published without the development-only source +// condition: the tarball's package.json (which the registry's metadata is read +// from) names only built files. Packing happens on a copy of each manifest in +// a folder of its own, so the workspace's package.json files, which the other +// tests resolve through, are never rewritten while they run. + +import { execFileSync } from 'node:child_process'; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { PUBLIC_PACKAGES } from '../../scripts/api-report.mjs'; +import { SOURCE_CONDITION, packPublished, publishedManifest } from '../../scripts/publish-manifest.mjs'; + +const PACKAGES = join(import.meta.dirname, '..', '..', 'packages'); +const manifestOf = (dir: string) => readFileSync(join(PACKAGES, dir, 'package.json'), 'utf8'); + +describe('the published manifest', () => { + it.each([...PUBLIC_PACKAGES])('%s: names no source file, and is otherwise the package\'s own', (dir) => { + const manifest = JSON.parse(manifestOf(dir)) as { exports: Record> }; + expect(manifestOf(dir)).toContain(SOURCE_CONDITION); + const published = publishedManifest(manifest); + expect(JSON.stringify(published)).not.toContain(SOURCE_CONDITION); + expect(Object.keys(published.exports)).toStrictEqual(Object.keys(manifest.exports)); + for (const [subpath, conditions] of Object.entries(manifest.exports)) { + const { [SOURCE_CONDITION]: source, ...rest } = conditions; + expect(source, subpath).toMatch(/^\.\/src\//); + expect(published.exports[subpath], subpath).toStrictEqual(rest); + } + expect({ ...published, exports: undefined }).toStrictEqual({ ...manifest, exports: undefined }); + }); + + it.each([...PUBLIC_PACKAGES])('%s: packs a tarball whose package.json has no source condition, and puts the manifest back as it was', (dir) => { + const work = mkdtempSync(join(tmpdir(), 'mn-publish-manifest-')); + try { + const folder = join(work, 'package'); + mkdirSync(folder); + copyFileSync(join(PACKAGES, dir, 'package.json'), join(folder, 'package.json')); + const tarball = packPublished(folder, join(work, 'out')); + const packed = execFileSync('tar', ['-xzOf', tarball, 'package/package.json'], { encoding: 'utf8' }); + expect(packed).not.toContain(SOURCE_CONDITION); + expect(JSON.parse(packed).exports).toStrictEqual(publishedManifest(JSON.parse(manifestOf(dir))).exports); + expect(readFileSync(join(folder, 'package.json'), 'utf8')).toBe(manifestOf(dir)); + } finally { + rmSync(work, { recursive: true, force: true }); + } + }, 60_000); +}); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index 492ef0c4..2d355180 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -1,12 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { captureCommand } from '../lib/run-command.ts'; -import { SecondResultError, type CommandHandler } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { CancelledError, CommandFailedError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { SecondResultError, type CommandHandler, CancelledError, CommandFailedError, classifyError, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; import { installedCommands } from '../lib/installed-commands.ts'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import { parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -17,8 +14,8 @@ import addressCommand from '../commands/address.ts'; import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { localIndexerFlags } from './helpers/local-indexer.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { localIndexerFlags } from '../../test-support/local-indexer.ts'; import { ownCall } from './helpers/own-call.ts'; const TEST_DIR = path.join(os.tmpdir(), `midnight-run-cmd-test-${process.pid}`); @@ -27,7 +24,7 @@ const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000 const TEST_CONFIG_SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; const TEST_CONFIG: WalletConfig = { seed: TEST_CONFIG_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_CONFIG_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_CONFIG_SEED, 'hex')), createdAt: '2026-01-15T10:30:00.000Z', }; diff --git a/src/__tests__/sealed-account.test.ts b/src/__tests__/sealed-account.test.ts index 2d3f494a..9429f3bd 100644 --- a/src/__tests__/sealed-account.test.ts +++ b/src/__tests__/sealed-account.test.ts @@ -8,7 +8,7 @@ import { execFileSync } from 'node:child_process'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; +import { createHost, WrongPassphraseError } from '@kuiralabs/midnight-cli-core'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -16,7 +16,6 @@ import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; -import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { contractAddressOnRecord, createAccountKey, diff --git a/src/__tests__/sealed-wallet.test.ts b/src/__tests__/sealed-wallet.test.ts index e0e21c47..3765be49 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/src/__tests__/sealed-wallet.test.ts @@ -8,13 +8,11 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError } from '@kuiralabs/midnight-cli-core/lib/keystore'; +import { WrongPassphraseError, FILE_MODE, createHost } from '@kuiralabs/midnight-cli-core'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { loadWalletConfig, protectAllWallets, sealWalletInPlace, unlockWallet, writeSealedWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. @@ -24,8 +22,8 @@ const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; const MNEMONIC = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; const PASSPHRASE = 'correct horse battery staple'; const PUBLIC = { - addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), - shieldedAddresses: deriveAllShieldedAddresses(Buffer.from(SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')), + shieldedAddresses: rcKeys.shieldedAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-10-19T00:00:00.000Z', }; diff --git a/src/__tests__/seed-resolver.test.ts b/src/__tests__/seed-resolver.test.ts index 5c42c54b..76cac1bc 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/src/__tests__/seed-resolver.test.ts @@ -6,16 +6,14 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, createHost, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core'; import { parseSeedHex, resolveSeedSource, resolveSeed, seedOf, walletSourceOf } from '../lib/seed-resolver.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { mkdirSync } from 'node:fs'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = testHost(); diff --git a/src/__tests__/serve-command.test.ts b/src/__tests__/serve-command.test.ts index 641c8e1b..53ef0a98 100644 --- a/src/__tests__/serve-command.test.ts +++ b/src/__tests__/serve-command.test.ts @@ -2,9 +2,7 @@ import { describe, it, expect } from 'vitest'; import serveCommand from '../commands/serve.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { findUnknownFlags } from '@kuiralabs/midnight-cli-core/lib/command-flags'; +import { parseArgs, UsageError, findUnknownFlags } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { cliCall } from './helpers/cli-call.ts'; diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index 94d163a3..0d310ff9 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -6,12 +6,11 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; -import { createSdkWarningRouter } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { createSdkWarningRouter, createHost } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. @@ -141,7 +140,7 @@ describe('startServeOrReuse against a running serve', () => { fs.mkdirSync(path.join(home, '.midnight', 'wallets'), { recursive: true }); for (const [name, seed] of [['two', TWO], ['bob', BOB]] as const) { saveWalletConfig( - { seed: seed.toString('hex'), addresses: deriveAllAddresses(seed), createdAt: new Date(0).toISOString() }, + { seed: seed.toString('hex'), addresses: rcKeys.unshieldedAddresses(seed), createdAt: new Date(0).toISOString() }, path.join(home, '.midnight', 'wallets', `${name}.json`), ); } @@ -154,7 +153,7 @@ describe('startServeOrReuse against a running serve', () => { it('reuses a serve that pays from that wallet', async () => { const { startServeOrReuse } = await import('../lib/serve-manager.ts'); - const serve = await fakeServe(sameChain, deriveAllAddresses(TWO).undeployed); + const serve = await fakeServe(sameChain, rcKeys.unshieldedAddresses(TWO).undeployed); try { const handle = await startServeOrReuse({ root: stateRootIn(home), host, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' }); expect(handle.port).toBe(serve.port); @@ -167,11 +166,11 @@ describe('startServeOrReuse against a running serve', () => { // for bob had bob pay, with no word of it. it('refuses a serve that pays from another wallet, on the same chain', async () => { const { startServeOrReuse } = await import('../lib/serve-manager.ts'); - const bob = deriveAllAddresses(BOB).undeployed; + const bob = rcKeys.unshieldedAddresses(BOB).undeployed; const serve = await fakeServe(sameChain, bob); try { await expect(startServeOrReuse({ root: stateRootIn(home), host, port: serve.port, network: 'undeployed', sdkWarnings: createSdkWarningRouter().openCall().warnings, endpoints: requested, wallet: 'two' })) - .rejects.toThrow(`can't pay for this command: it serves the wallet at ${bob}, and this command pays from two (${deriveAllAddresses(TWO).undeployed})`); + .rejects.toThrow(`can't pay for this command: it serves the wallet at ${bob}, and this command pays from two (${rcKeys.unshieldedAddresses(TWO).undeployed})`); } finally { await serve.close(); } diff --git a/src/__tests__/settings.test.ts b/src/__tests__/settings.test.ts index e907b34b..39021051 100644 --- a/src/__tests__/settings.test.ts +++ b/src/__tests__/settings.test.ts @@ -6,11 +6,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { resolveBlockfrostProjectId } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { detectLocalStacks } from '@kuiralabs/midnight-cli-core/lib/network'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { settingsFromEnvironment, createHost, resolveBlockfrostProjectId, detectLocalStacks, parseArgs } from '@kuiralabs/midnight-cli-core'; import { readPassphrase, passphraseForNewSecret, NoPassphraseError } from '../lib/passphrase.ts'; import { resolveSeedSource } from '../lib/seed-resolver.ts'; diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 2f18be9c..5e358c50 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -8,25 +8,21 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { NoStateRootError } from '@kuiralabs/midnight-cli-core/lib/state-root'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { testHost } from './helpers/test-host.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import configCommand from '@kuiralabs/midnight-cli-core/commands/config'; +import { NoStateRootError, createHost, parseArgs, setConfigValue, MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core'; +import { bindCachesToIndexer, getCachePath, getDustCachePath, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/engine'; +import { testHost } from '../../test-support/test-host.ts'; +import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { cliCall } from './helpers/cli-call.ts'; -import { setConfigValue } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { bindCachesToIndexer } from '@kuiralabs/midnight-cli-core/lib/cache-indexer'; import { passphraseForNewSecret, PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; import { accountRecordsDir } from '../lib/grant/account-records.ts'; import { accountArtifactsDir } from '../lib/grant/account.ts'; -import { getCachePath } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { getDustCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { getShieldedCachePath } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; import { getComposePath } from '../lib/localnet.ts'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; import before from './fixtures/state-layout-before-1g.json'; +// The config handler, as the shell loads it. +const { default: configCommand } = await configDefinition.load(); + const PASSPHRASE = 'fixture-passphrase-1g'; let dir: string; diff --git a/src/__tests__/status.test.ts b/src/__tests__/status.test.ts index 6035995b..c488d084 100644 --- a/src/__tests__/status.test.ts +++ b/src/__tests__/status.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import { statusDefinition } from '@kuiralabs/midnight-chain/commands'; import { cliCall } from './helpers/cli-call.ts'; // ── Test helpers ── @@ -114,8 +115,8 @@ describe('status command', () => { /** Runs status as the CLI would; the exit code it gives, which the shell sets. */ async function runStatus(flags: Record = {}) { - // Dynamic import to get fresh module - const mod = await import('@kuiralabs/midnight-chain/commands/status'); + // The status handler, as the shell loads it. + const mod = await statusDefinition.load(); return cliCall(mod.default, { command: 'status', subcommand: undefined, diff --git a/src/__tests__/swap-command.test.ts b/src/__tests__/swap-command.test.ts index 68b01ed5..8d96db2f 100644 --- a/src/__tests__/swap-command.test.ts +++ b/src/__tests__/swap-command.test.ts @@ -7,13 +7,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { encodeOfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; -import type { ConnectOptions, Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; +import { parseArgs, encodeOfferEnvelope, type ConnectOptions, type Payer } from '@kuiralabs/midnight-cli-core'; import swapCommand from '../commands/swap.ts'; import { cliCall } from './helpers/cli-call.ts'; -import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../test-support/fixtures/swap-offer.ts'; +import { rcEngine } from '../../test-support/rc-engine.ts'; const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; const TERMS = ['--give', '10', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT]; @@ -24,7 +22,7 @@ afterEach(() => rmSync(dir, { recursive: true, force: true })); describe('swap take', () => { it('asks its payer for a session with the shielded side synced', async () => { - const read = readOffer(SWAP_OFFER_HEX); + const read = rcEngine.ledger.readOffer(SWAP_OFFER_HEX); const file = join(dir, 'offer.json'); writeFileSync(file, encodeOfferEnvelope({ network: 'undeployed', id: read.id, terms: read.terms, expiresAt: new Date(Date.now() + 3_600_000), tx: SWAP_OFFER_HEX })); const asked: (ConnectOptions | undefined)[] = []; diff --git a/src/__tests__/swap-lib.test.ts b/src/__tests__/swap-lib.test.ts index 88ad2bae..3da80d67 100644 --- a/src/__tests__/swap-lib.test.ts +++ b/src/__tests__/swap-lib.test.ts @@ -16,13 +16,8 @@ import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { WebSocketServer } from 'ws'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import type { ConnectOptions, Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { encodeOfferEnvelope } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; -import { readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createHost, type Host, saveCliConfig, type ConnectOptions, type Payer, type PayingTarget, encodeOfferEnvelope, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; +import { rcEngine, rcKeys } from '../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { makeSwapOffer } from '../lib/swap/make.ts'; import { inspectSwapOffer } from '../lib/swap/inspect.ts'; @@ -30,13 +25,13 @@ import { takeSwapOffer } from '../lib/swap/take.ts'; import { cancelSwapOffer } from '../lib/swap/cancel.ts'; import { listSwapOffers } from '../lib/swap/list.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../test-support/fixtures/swap-offer.ts'; const NOW = new Date('2026-11-02T12:00:00.000Z'); const SEED = 'c4'.repeat(32); -const ADDRESS = deriveAllAddresses(Buffer.from(SEED, 'hex')).undeployed; +const ADDRESS = rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')).undeployed; const TERMS = { give: { token: OFFER_GIVE, amount: 10n }, want: { token: OFFER_WANT, amount: 7n } }; -const OFFER = readOffer(SWAP_OFFER_HEX); +const OFFER = rcEngine.ledger.readOffer(SWAP_OFFER_HEX); const SPENT_IN = 'cd'.repeat(32); /** The stand-in indexer: the chain's tip over HTTP, and the spends of the coins it is told are spent over WebSocket, on one port. */ @@ -109,7 +104,7 @@ const offerText = (expiresAt = new Date(NOW.getTime() + 60_000), network = 'unde /** mn's wallet `alice` under the host's state root, the active one. */ function alice(): void { - saveWalletConfig({ seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: NOW.toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveWalletConfig({ seed: SEED, addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')), createdAt: NOW.toISOString() }, path.join(root, 'wallets', 'alice.json')); saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); } diff --git a/src/__tests__/swap-request.test.ts b/src/__tests__/swap-request.test.ts index 1963d95d..19313a06 100644 --- a/src/__tests__/swap-request.test.ts +++ b/src/__tests__/swap-request.test.ts @@ -6,14 +6,12 @@ import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { encodeOfferEnvelope, OfferExpiredError } from '@kuiralabs/midnight-cli-core/lib/offer-envelope'; -import { NotAnOfferError, TermsMismatchError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; -import { readOffer } from '@kuiralabs/midnight-engine-rc/offer-reader'; +import { parseArgs, UsageError, encodeOfferEnvelope, OfferExpiredError, TermsMismatchError } from '@kuiralabs/midnight-cli-core'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/engine'; import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../lib/swap/request.ts'; -import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; -import { testHost } from './helpers/test-host.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../test-support/fixtures/swap-offer.ts'; +import { testHost } from '../../test-support/test-host.ts'; +import { rcEngine } from '../../test-support/rc-engine.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = testHost(); @@ -57,7 +55,7 @@ describe('take', () => { afterEach(() => rmSync(dir, { recursive: true, force: true })); const offerFile = (overrides: { network?: string; expiresAt?: Date; tx?: string } = {}) => { - const read = readOffer(SWAP_OFFER_HEX); + const read = rcEngine.ledger.readOffer(SWAP_OFFER_HEX); const file = join(dir, 'offer.json'); writeFileSync(file, encodeOfferEnvelope({ network: (overrides.network ?? 'undeployed') as 'undeployed', id: read.id, terms: read.terms, diff --git a/src/__tests__/transfer-command.test.ts b/src/__tests__/transfer-command.test.ts index 7ed3baa3..1c2964c7 100644 --- a/src/__tests__/transfer-command.test.ts +++ b/src/__tests__/transfer-command.test.ts @@ -1,10 +1,9 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import transferCommand from '../commands/transfer.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { deriveUnshieldedAddress, deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; @@ -32,7 +31,7 @@ describe('transfer command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -45,12 +44,12 @@ describe('transfer command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); - const recipientAddr = deriveUnshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const recipientAddr = rcKeys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); const args = parseArgs(['transfer', recipientAddr, '--wallet', walletFile]); await expect(cliCall(transferCommand, args)).rejects.toThrow('Missing amount'); }); @@ -59,12 +58,12 @@ describe('transfer command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); - const recipientAddr = deriveUnshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const recipientAddr = rcKeys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); const args = parseArgs(['transfer', recipientAddr, 'notanumber', '--wallet', walletFile]); await expect(cliCall(transferCommand, args)).rejects.toThrow('Invalid amount'); }); @@ -73,18 +72,18 @@ describe('transfer command — argument validation', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); - const recipientAddr = deriveUnshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const recipientAddr = rcKeys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); const args = parseArgs(['transfer', recipientAddr, '0', '--wallet', walletFile]); await expect(cliCall(transferCommand, args)).rejects.toThrow('greater than 0'); }); it('throws when no wallet file exists', async () => { - const recipientAddr = deriveUnshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); + const recipientAddr = rcKeys.unshieldedAddress(Buffer.from(GENESIS_SEED, 'hex'), 'undeployed'); const args = parseArgs(['transfer', recipientAddr, '100', '--wallet', path.join(TEST_DIR, 'nonexistent.json')]); await expect(cliCall(transferCommand, args)).rejects.toThrow('Wallet file not found'); }); @@ -95,7 +94,7 @@ describe('transfer command — address validation errors', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -108,7 +107,7 @@ describe('transfer command — address validation errors', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -124,7 +123,7 @@ describe('transfer command — wallet name resolution', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -140,7 +139,7 @@ describe('transfer command — wallet name resolution', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -156,7 +155,7 @@ describe('transfer command — shielded flag', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -169,7 +168,7 @@ describe('transfer command — shielded flag', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); @@ -184,7 +183,7 @@ describe('transfer command — shielded flag', () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const config: WalletConfig = { seed: TEST_SEED, - addresses: deriveAllAddresses(Buffer.from(TEST_SEED, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(TEST_SEED, 'hex')), createdAt: new Date().toISOString(), }; saveWalletConfig(config, walletFile); diff --git a/src/__tests__/transfer-request.test.ts b/src/__tests__/transfer-request.test.ts index 7d9a0436..e27c264f 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/src/__tests__/transfer-request.test.ts @@ -7,14 +7,10 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { resolveTransferRequest } from '../lib/transfer-request.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs, MIDNIGHT_DIR, WALLETS_DIR_NAME, UsageError, classifyError, createHost } from '@kuiralabs/midnight-cli-core'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { MIDNIGHT_DIR, WALLETS_DIR_NAME } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { installedCommands } from '../lib/installed-commands.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. @@ -24,8 +20,8 @@ const HOME = path.join(os.tmpdir(), `midnight-transfer-request-test-${process.pi const WALLETS = path.join(HOME, MIDNIGHT_DIR, WALLETS_DIR_NAME); const SENDER_SEED = Buffer.from('00'.repeat(31) + '11', 'hex'); const RECIPIENT_SEED = Buffer.from('00'.repeat(31) + '22', 'hex'); -const RECIPIENT = deriveAllAddresses(RECIPIENT_SEED); -const RECIPIENT_SHIELDED = deriveAllShieldedAddresses(RECIPIENT_SEED); +const RECIPIENT = rcKeys.unshieldedAddresses(RECIPIENT_SEED); +const RECIPIENT_SHIELDED = rcKeys.shieldedAddresses(RECIPIENT_SEED); let origHome: string | undefined; @@ -33,8 +29,8 @@ function saveWallet(name: string, seed: Buffer, shielded = false): string { const file = path.join(WALLETS, `${name}.json`); saveWalletConfig({ seed: seed.toString('hex'), - addresses: deriveAllAddresses(seed), - ...(shielded ? { shieldedAddresses: deriveAllShieldedAddresses(seed) } : {}), + addresses: rcKeys.unshieldedAddresses(seed), + ...(shielded ? { shieldedAddresses: rcKeys.shieldedAddresses(seed) } : {}), createdAt: new Date(0).toISOString(), }, file); return file; diff --git a/src/__tests__/two-hosts.test.ts b/src/__tests__/two-hosts.test.ts index edd81172..b343d618 100644 --- a/src/__tests__/two-hosts.test.ts +++ b/src/__tests__/two-hosts.test.ts @@ -13,12 +13,7 @@ import * as path from 'node:path'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { WebSocketServer } from 'ws'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; -import type { CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { createHost, type Host, parseArgs, MIDNIGHT_DIR, settingsFromEnvironment, recordOpenOffer, type OpenOffer, type CallOutput } from '@kuiralabs/midnight-cli-core'; import { dispatchCommand } from '../lib/command-dispatch.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; diff --git a/src/__tests__/tx-status.test.ts b/src/__tests__/tx-status.test.ts index d4529ee1..3980ce87 100644 --- a/src/__tests__/tx-status.test.ts +++ b/src/__tests__/tx-status.test.ts @@ -1,190 +1,24 @@ -// What became of a transaction, from the indexer: the lookup, the wait, the -// receipt a submitting command reports, and `mn tx status`. The answers below -// have the shape stagenet's indexer gave on 2026-11-03 for the City's first -// swap (a 4.4 indexer; 4.3's transaction fields are the same). +// `mn tx status`, as the shell runs it, answered by a stand-in indexer with +// test-support/fixtures/tx-status.ts. The chain's lookup, wait and receipt +// are the chain's tests (packages/chain/src/__tests__/tx-status.test.ts). import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { CancelledError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { IndexerQueryError } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; -import { fetchTransactionStatus, parseTxReference, transactionStatus, waitForTransactionStatus } from '@kuiralabs/midnight-chain/lib/tx-status'; -import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import { receiptJson, receiptOf, transactionStatusJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; -import txCommand from '@kuiralabs/midnight-chain/commands/tx'; -import { startLocalIndexer, type LocalIndexer } from './helpers/local-indexer.ts'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { txDefinition } from '@kuiralabs/midnight-chain/commands'; +import { startLocalIndexer, type LocalIndexer } from '../../test-support/local-indexer.ts'; +import { BLOCK, HASH, IDENTIFIER, answer, regular } from '../../test-support/fixtures/tx-status.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; -const IDENTIFIER = '00408d0e7f195ae3a57b908f10513f2200386533960fcdc3fb152076dd84559086'; -const HASH = '1dc5749135a08df5fb95560e1ef1ff3fea6febdd8b263dbd2b371e2f9cb178f8'; -const BLOCK = { height: 1146592, hash: 'd3d3af4c0a35110377d12c1296274603fa75583b274191c8b7063bc913db2f75', timestamp: 1793696118000 }; - -const answer = (transactions: unknown[]) => JSON.stringify({ data: { transactions } }); -const regular = (status: string, segments: unknown = null) => ({ - __typename: 'RegularTransaction', - hash: HASH, - block: BLOCK, - identifiers: [IDENTIFIER], - fee: '845170285714286', - transactionResult: { status, segments }, -}); +// The tx handler, as the shell loads it. +const { default: txCommand } = await txDefinition.load(); let indexer: LocalIndexer | undefined; afterEach(async () => { await indexer?.close(); indexer = undefined; }); -describe('parseTxReference', () => { - it('reads 64 hex characters as a hash and 66 as an identifier, with or without 0x, in any case', () => { - expect(parseTxReference(HASH)).toEqual({ hash: HASH }); - expect(parseTxReference(IDENTIFIER)).toEqual({ identifier: IDENTIFIER }); - expect(parseTxReference(`0x${HASH.toUpperCase()}`)).toEqual({ hash: HASH }); - }); - - it.each(['', 'xyz', HASH.slice(1), `${IDENTIFIER}00`, `${HASH.slice(0, 63)}g`])('refuses %j as a usage error', (text) => { - expect(() => parseTxReference(text)).toThrow(UsageError); - }); -}); - -describe('fetchTransactionStatus', () => { - it('finds a transaction by its identifier: final, with its result, fee in specks and block', async () => { - indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); - const status = await fetchTransactionStatus(indexer.url, { identifier: IDENTIFIER }); - expect(status).toEqual({ - state: 'final', kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', feeSpecks: 845170285714286n, - block: { height: BLOCK.height, hash: BLOCK.hash, time: new Date('2026-11-03T08:55:18.000Z') }, - }); - expect(indexer.requests[0]!.variables).toEqual({ offset: { identifier: IDENTIFIER } }); - }); - - it('asks by hash when given a hash', async () => { - indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); - await fetchTransactionStatus(indexer.url, { hash: HASH }); - expect(indexer.requests[0]!.variables).toEqual({ offset: { hash: HASH } }); - }); - - it('lists the segments of a partial success, and only of one', async () => { - indexer = await startLocalIndexer(() => answer([regular('PARTIAL_SUCCESS', [{ id: 0, success: true }, { id: 1, success: false }])])); - const status = await fetchTransactionStatus(indexer.url, { hash: HASH }); - expect(status).toMatchObject({ result: 'PARTIAL_SUCCESS', segments: [{ id: 0, success: true }, { id: 1, success: false }] }); - }); - - it('reports a failed transaction as final, with the fee it paid', async () => { - indexer = await startLocalIndexer(() => answer([regular('FAILURE')])); - expect(await fetchTransactionStatus(indexer.url, { hash: HASH })).toMatchObject({ state: 'final', result: 'FAILURE', feeSpecks: 845170285714286n }); - }); - - it('reports a system transaction with its block, and no result or fee', async () => { - indexer = await startLocalIndexer(() => answer([{ __typename: 'SystemTransaction', hash: HASH, block: BLOCK }])); - const status = await fetchTransactionStatus(indexer.url, { hash: HASH }); - expect(status).toEqual({ state: 'final', kind: 'system', hash: HASH, identifiers: [], block: { height: BLOCK.height, hash: BLOCK.hash, time: new Date(BLOCK.timestamp) } }); - }); - - it('reports a transaction the indexer does not have as not found', async () => { - indexer = await startLocalIndexer(() => answer([])); - expect(await fetchTransactionStatus(indexer.url, { identifier: IDENTIFIER })).toEqual({ state: 'notFound' }); - }); - - it('throws IndexerQueryError when the indexer refuses the query', async () => { - indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'invalid transaction hash' }] })); - await expect(fetchTransactionStatus(indexer.url, { hash: HASH })).rejects.toThrow(IndexerQueryError); - }); -}); - -describe('waitForTransactionStatus', () => { - it('asks until the indexer lists the transaction', async () => { - let asked = 0; - indexer = await startLocalIndexer(() => (++asked < 3 ? answer([]) : answer([regular('SUCCESS')]))); - const status = await waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 5_000, undefined, 20); - expect(status.state).toBe('final'); - expect(asked).toBe(3); - }); - - it('gives not found once the timeout passes', async () => { - indexer = await startLocalIndexer(() => answer([])); - const started = Date.now(); - expect(await waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 150, undefined, 20)).toEqual({ state: 'notFound' }); - expect(Date.now() - started).toBeLessThan(2_000); - expect(indexer.requests.length).toBeGreaterThan(1); - }); - - it('stops with CancelledError when its call is cancelled', async () => { - indexer = await startLocalIndexer(() => answer([])); - const controller = new AbortController(); - setTimeout(() => controller.abort(), 50); - await expect(waitForTransactionStatus(indexer.url, { identifier: IDENTIFIER }, 10_000, controller.signal, 20)).rejects.toThrow(CancelledError); - }); -}); - -describe('transactionStatus', () => { - it('asks once, saying so, and gives what the indexer knows', async () => { - indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); - const said: ProgressEvent[] = []; - const status = await transactionStatus({ indexer: indexer.url, ref: { hash: HASH }, onProgress: (event) => said.push(event) }); - expect(status).toMatchObject({ state: 'final', result: 'SUCCESS', feeSpecks: 845170285714286n, block: { height: BLOCK.height } }); - expect(indexer.requests).toHaveLength(1); - expect(said).toEqual([{ kind: 'start', message: 'Asking the indexer...' }, { kind: 'done', message: 'Final' }]); - }); - - it('with wait, asks until the time passes, and says it was not found', async () => { - indexer = await startLocalIndexer(() => answer([])); - const said: ProgressEvent[] = []; - const status = await transactionStatus({ indexer: indexer.url, ref: { identifier: IDENTIFIER }, wait: true, timeoutMs: 100, onProgress: (event) => said.push(event) }); - expect(status).toEqual({ state: 'notFound' }); - expect(said).toEqual([{ kind: 'start', message: 'Waiting for the indexer to list it...' }, { kind: 'done', message: 'Not found' }]); - }); - - it('never asks when its call is cancelled already', async () => { - indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); - const said: ProgressEvent[] = []; - await expect(transactionStatus({ indexer: indexer.url, ref: { hash: HASH }, signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toThrow(CancelledError); - expect(indexer.requests).toEqual([]); - expect(said).toEqual([]); - }); - - it('throws IndexerQueryError when the indexer refuses', async () => { - indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'invalid transaction hash' }] })); - await expect(transactionStatus({ indexer: indexer.url, ref: { hash: HASH } })).rejects.toBeInstanceOf(IndexerQueryError); - }); -}); - -describe('receiptOf', () => { - it('gives the transaction once listed, and its JSON with the fee in DUST exactly', async () => { - indexer = await startLocalIndexer(() => answer([regular('SUCCESS')])); - const receipt = await receiptOf(indexer.url, IDENTIFIER); - expect(receiptJson(receipt)).toEqual({ - receipt: { - kind: 'regular', hash: HASH, identifiers: [IDENTIFIER], result: 'SUCCESS', fee: '0.845170285714286', feeSpecks: '845170285714286', - blockHeight: BLOCK.height, blockHash: BLOCK.hash, blockTime: '2026-11-03T08:55:18.000Z', - }, - }); - }); - - it('says the indexer has not listed it yet, never throwing', async () => { - indexer = await startLocalIndexer(() => answer([])); - expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER, undefined, 100))).toEqual({ receipt: null, receiptMissing: 'the indexer has not listed it after 0 s' }); - }); - - it('says the indexer did not answer, never throwing', async () => { - indexer = await startLocalIndexer(() => JSON.stringify({ errors: [{ message: 'overloaded' }] })); - expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER))).toEqual({ receipt: null, receiptMissing: 'the indexer did not answer: overloaded' }); - }); - - it('says it was cancelled, never throwing: the transaction is submitted already', async () => { - indexer = await startLocalIndexer(() => answer([])); - const controller = new AbortController(); - setTimeout(() => controller.abort(), 50); - expect(receiptJson(await receiptOf(indexer.url, IDENTIFIER, controller.signal))).toEqual({ receipt: null, receiptMissing: 'cancelled while waiting for the indexer' }); - }); -}); - -describe('transactionStatusJson', () => { - it('gives not found as its state alone', () => { - expect(transactionStatusJson({ state: 'notFound' })).toEqual({ state: 'notFound' }); - }); -}); - describe('mn tx status', () => { let io: CapturedOutput; let home: string; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index d74e1ccb..42b6f517 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -9,23 +9,21 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Buffer } from 'node:buffer'; import { captureCommand } from '../lib/run-command.ts'; -import { callDiagnostics } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { WalletDataRepository } from '@kuiralabs/midnight-engine-rc/wallet-data-repository'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; +import { callDiagnostics, parseArgs, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import balanceCommand from '../commands/balance.ts'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { ownCall } from './helpers/own-call.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; // One host for every call, as the MCP server has: its notices are where verbose lines go. const host = testHost({ notice: (line) => notices.push(line) }); // Nothing listens here: each call fails at its first connection, after its first diagnostic. const UNREACHABLE = ['--indexer-ws', 'ws://127.0.0.1:1/api/v4/graphql/ws', '--node', 'ws://127.0.0.1:1', '--proof-server', 'http://127.0.0.1:1']; -const VERBOSE_ADDRESS = deriveUnshieldedAddress(Buffer.from('aa'.repeat(32), 'hex'), 'undeployed'); -const QUIET_ADDRESS = deriveUnshieldedAddress(Buffer.from('bb'.repeat(32), 'hex'), 'undeployed'); +const VERBOSE_ADDRESS = rcKeys.unshieldedAddress(Buffer.from('aa'.repeat(32), 'hex'), 'undeployed'); +const QUIET_ADDRESS = rcKeys.unshieldedAddress(Buffer.from('bb'.repeat(32), 'hex'), 'undeployed'); let notices: string[]; let io: CapturedOutput; @@ -72,17 +70,17 @@ describe('verbose, per call', () => { it("a library writes its diagnostics to the log of the call that reached it, and only a verbose call's shows them", async () => { const network: NetworkConfig = { indexer: 'http://test/indexer', indexerWS: 'ws://test/indexer/ws', node: 'ws://test/node', proofServer: 'http://test/proof', networkId: 'Undeployed' }; - // The chain's tip can't be read, which the repository notes as a diagnostic. - const repo = new WalletDataRepository(testHost(), { + // The chain's tip can't be read, which the engine's wallet repository notes as a diagnostic. + const { wallet } = createRcEngine(testHost(), { repository: { fetchProtocolVersion: async () => 2001000n, fetchTip: async () => { throw new Error('node unreachable'); }, fetchUnshielded: async () => ({ balances: new Map(), utxoCount: 0, txCount: 0, highestTxId: 0, registeredUtxos: 0, unregisteredUtxos: 0 }), - }); + } }); const verboseLines: string[] = []; const quietLines: string[] = []; await Promise.all([ - repo.unshielded('addr-verbose', network, { log: callDiagnostics(true, (line) => verboseLines.push(line)).line }), - repo.unshielded('addr-quiet', network, { log: callDiagnostics(false, (line) => quietLines.push(line)).line }), + wallet.unshieldedBalance('addr-verbose', network, { log: callDiagnostics(true, (line) => verboseLines.push(line)).line }), + wallet.unshieldedBalance('addr-quiet', network, { log: callDiagnostics(false, (line) => quietLines.push(line)).line }), ]); expect(verboseLines).toHaveLength(1); expect(verboseLines[0]).toContain('repo: tip unavailable; skipping memo for'); diff --git a/src/__tests__/wallet-airdrop-lib.test.ts b/src/__tests__/wallet-airdrop-lib.test.ts index 71868085..e5438a6c 100644 --- a/src/__tests__/wallet-airdrop-lib.test.ts +++ b/src/__tests__/wallet-airdrop-lib.test.ts @@ -10,22 +10,18 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createHost, type Host, settingsFromEnvironment, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { airdropNight, type AirdropAddressed, type AirdropNightOptions } from '../lib/wallet/airdrop.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from './helpers/stand-in-indexer.ts'; +import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from '../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED = Buffer.from('a7'.repeat(32), 'hex'); -const ADDRESS = deriveAllAddresses(SEED); -const SHIELDED = deriveAllShieldedAddresses(SEED); +const ADDRESS = rcKeys.unshieldedAddresses(SEED); +const SHIELDED = rcKeys.shieldedAddresses(SEED); // Above what a JS number carries exactly (2^53 micro-NIGHT): 9007199254.740993 NIGHT. const LARGE = 9_007_199_254_740_993n; diff --git a/src/__tests__/wallet-balance-lib.test.ts b/src/__tests__/wallet-balance-lib.test.ts index 4996f859..674c1be3 100644 --- a/src/__tests__/wallet-balance-lib.test.ts +++ b/src/__tests__/wallet-balance-lib.test.ts @@ -8,20 +8,15 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import { deriveAllAddresses, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createHost, type Host, settingsFromEnvironment, NATIVE_TOKEN_TYPE, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { establishPassphrase, PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { writeSealedWallet, type WalletPublic } from '../lib/wallet-config.ts'; import { readAddressBalance, readWalletBalance, type UnshieldedRead } from '../lib/wallet/balance.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED_A = 'a1'.repeat(32); @@ -61,7 +56,7 @@ const endpoints = () => ({ indexerWS: indexer.url, node: `ws://127.0.0.1:${refus describe('readAddressBalance', () => { it('reads an address on the network its prefix names: balances in the smallest unit as bigint, with each step said', async () => { - const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + const address = rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); const said: ProgressEvent[] = []; const result = await readAddressBalance(programHost('a'), address, { ...endpoints(), forceFresh: true, onProgress: (event) => said.push(event) }); @@ -73,19 +68,19 @@ describe('readAddressBalance', () => { }); it('refuses a network other than the one the address is for, as a usage error, before reading', async () => { - const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + const address = rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); await expect(readAddressBalance(programHost('a'), address, { ...endpoints(), network: 'preprod' })).rejects.toMatchObject({ code: 'INVALID_ARGS', message: expect.stringContaining('Address belongs to undeployed but --network is preprod') }); expect(indexer.subscriptions).toEqual([]); }); it('fails with NETWORK_ERROR when the indexer refuses the connection', async () => { - const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + const address = rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); await expect(readAddressBalance(programHost('a'), address, { ...endpoints(), indexerWS: `ws://127.0.0.1:${refusing.port}/api/v4/graphql/ws`, forceFresh: true })).rejects.toMatchObject({ code: 'NETWORK_ERROR' }); }); it('cancelled already: CancelledError, and nothing asked of the indexer or said', async () => { const said: ProgressEvent[] = []; - const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + const address = rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); await expect(readAddressBalance(programHost('a'), address, { ...endpoints(), signal: AbortSignal.abort(), onProgress: (event) => said.push(event) })).rejects.toMatchObject({ code: 'CANCELLED' }); expect(indexer.subscriptions).toEqual([]); expect(said).toEqual([]); @@ -98,7 +93,7 @@ describe('readWalletBalance', () => { it('reads a seed the program holds: unshielded NIGHT as bigint, shielded not read where the network has no faucet', async () => { const said: Said[] = []; const seed = Buffer.from(SEED_A, 'hex'); - const address = deriveUnshieldedAddress(seed, 'preview'); + const address = rcKeys.unshieldedAddress(seed, 'preview'); const result = await readWalletBalance(programHost('a'), { seed }, { ...endpoints(), network: 'preview', forceFresh: true, onProgress: (event) => said.push(event) }); expect(result).toEqual({ network: 'preview', address, unshielded: { night: 3_500_000n, utxoCount: 2 }, shielded: null }); @@ -114,7 +109,7 @@ describe('readWalletBalance', () => { const host = programHost('a'); const root = host.paths().stateRoot; establishPassphrase(root, PASSPHRASE); - const addresses = deriveAllAddresses(Buffer.from(SEED_B, 'hex')); + const addresses = rcKeys.unshieldedAddresses(Buffer.from(SEED_B, 'hex')); const shieldedAddresses = { preview: 'mn_shield-addr_preview1saved' } as WalletPublic['addresses']; writeSealedWallet(path.join(root, 'wallets', 'alice.json'), { addresses, shieldedAddresses, createdAt: new Date().toISOString() }, { seed: SEED_B }, PASSPHRASE); const said: Said[] = []; @@ -132,7 +127,7 @@ describe('readWalletBalance', () => { const hostB = programHost('b'); for (const [host, seed, network] of [[hostA, SEED_A, 'preview'], [hostB, SEED_B, 'preprod']] as const) { const root = host.paths().stateRoot; - saveWalletConfig({ seed, addresses: deriveAllAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveWalletConfig({ seed, addresses: rcKeys.unshieldedAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); saveCliConfig({ network, wallet: 'alice' }, root); } @@ -141,8 +136,8 @@ describe('readWalletBalance', () => { readWalletBalance(hostB, {}, { ...endpoints(), forceFresh: true }), ]); - expect(a).toMatchObject({ network: 'preview', address: deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'preview'), unshielded: { night: 3_500_000n } }); - expect(b).toMatchObject({ network: 'preprod', address: deriveUnshieldedAddress(Buffer.from(SEED_B, 'hex'), 'preprod'), unshielded: { night: 3_500_000n } }); + expect(a).toMatchObject({ network: 'preview', address: rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'preview'), unshielded: { night: 3_500_000n } }); + expect(b).toMatchObject({ network: 'preprod', address: rcKeys.unshieldedAddress(Buffer.from(SEED_B, 'hex'), 'preprod'), unshielded: { night: 3_500_000n } }); }); it('refuses a wallet that is not there with WALLET_NOT_FOUND, and a seed of the wrong size with INVALID_ARGS, before reading', async () => { diff --git a/src/__tests__/wallet-config.test.ts b/src/__tests__/wallet-config.test.ts index 729dc0b4..7077f882 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/src/__tests__/wallet-config.test.ts @@ -5,10 +5,9 @@ import * as os from 'os'; import { loadWalletConfig, matchWalletAddress, unlockWallet, walletAddress, writeSealedWallet, type WalletInfo } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { deriveAllAddresses, deriveAllShieldedAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { DIR_MODE, FILE_MODE, createHost } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. @@ -17,7 +16,7 @@ const host = createHost({ engineLoader: loadInstalledEngine }); const TEST_DIR = path.join(os.tmpdir(), `midnight-wallet-test-${process.pid}`); const VALID_SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; -const VALID_ADDRESSES = deriveAllAddresses(Buffer.from(VALID_SEED, 'hex')); +const VALID_ADDRESSES = rcKeys.unshieldedAddresses(Buffer.from(VALID_SEED, 'hex')); const VALID_CONFIG: WalletConfig = { seed: VALID_SEED, @@ -62,7 +61,7 @@ describe('writeSealedWallet', () => { const filePath = path.join(TEST_DIR, 'wallet.json'); writeSealedWallet(filePath, PUBLIC, { seed: VALID_SEED, mnemonic: 'abandon abandon abandon' }, PASSPHRASE); const otherSeed = '1111111111111111111111111111111111111111111111111111111111111111'; - const otherAddresses = deriveAllAddresses(Buffer.from(otherSeed, 'hex')); + const otherAddresses = rcKeys.unshieldedAddresses(Buffer.from(otherSeed, 'hex')); writeSealedWallet(filePath, { addresses: otherAddresses, createdAt: '2026-02-26T00:00:00.000Z' }, { seed: otherSeed }, PASSPHRASE, { overwrite: true }); const loaded = await unlockWallet(filePath, UNLOCK); expect(loaded.seed).toBe(otherSeed); @@ -167,8 +166,8 @@ describe('round-trip', () => { it('a plain-text wallet unlocks to all it holds, mnemonic included', async () => { const filePath = path.join(TEST_DIR, 'roundtrip.json'); const seed = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; - const addresses = deriveAllAddresses(Buffer.from(seed, 'hex')); - const shieldedAddresses = deriveAllShieldedAddresses(Buffer.from(seed, 'hex')); + const addresses = rcKeys.unshieldedAddresses(Buffer.from(seed, 'hex')); + const shieldedAddresses = rcKeys.shieldedAddresses(Buffer.from(seed, 'hex')); const original: WalletConfig = { seed, mnemonic: 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about', @@ -182,14 +181,14 @@ describe('round-trip', () => { it('a sealed wallet unlocks to all it was written with', async () => { const filePath = path.join(TEST_DIR, 'roundtrip.json'); - const shieldedAddresses = deriveAllShieldedAddresses(Buffer.from(VALID_SEED, 'hex')); + const shieldedAddresses = rcKeys.shieldedAddresses(Buffer.from(VALID_SEED, 'hex')); writeSealedWallet(filePath, { addresses: VALID_ADDRESSES, shieldedAddresses, createdAt: VALID_CONFIG.createdAt }, { seed: VALID_SEED }, PASSPHRASE); expect(await unlockWallet(filePath, UNLOCK)).toEqual({ ...VALID_CONFIG, shieldedAddresses, isSealed: true }); }); }); describe('matchWalletAddress', () => { - const shieldedAddresses = deriveAllShieldedAddresses(Buffer.from(VALID_SEED, 'hex')); + const shieldedAddresses = rcKeys.shieldedAddresses(Buffer.from(VALID_SEED, 'hex')); const SEED_2 = '1111111111111111111111111111111111111111111111111111111111111111'; const alice: WalletInfo = { @@ -201,7 +200,7 @@ describe('matchWalletAddress', () => { }; const bob: WalletInfo = { name: 'bob', - addresses: deriveAllAddresses(Buffer.from(SEED_2, 'hex')), + addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED_2, 'hex')), isActive: false, file: '/wallets/bob.json', }; @@ -219,7 +218,7 @@ describe('matchWalletAddress', () => { }); it('returns undefined for an address no wallet owns', () => { - const stranger = deriveAllAddresses(Buffer.from( + const stranger = rcKeys.unshieldedAddresses(Buffer.from( '0000000000000000000000000000000000000000000000000000000000000099', 'hex', )).undeployed; expect(matchWalletAddress([alice, bob], stranger)).toBeUndefined(); @@ -233,7 +232,7 @@ describe('matchWalletAddress', () => { describe('a wallet written before stagenet', () => { // The addresses an earlier mn wrote: every network but stagenet. const { stagenet: stagenetAddress, ...earlierAddresses } = VALID_ADDRESSES; - const { stagenet: stagenetShielded, ...earlierShielded } = deriveAllShieldedAddresses(Buffer.from(VALID_SEED, 'hex')); + const { stagenet: stagenetShielded, ...earlierShielded } = rcKeys.shieldedAddresses(Buffer.from(VALID_SEED, 'hex')); it('gets its stagenet address derived and saved when a plain-text wallet is read', async () => { const filePath = path.join(TEST_DIR, 'plain.json'); diff --git a/src/__tests__/wallet-create.test.ts b/src/__tests__/wallet-create.test.ts index f0938c84..6b36f5f9 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/src/__tests__/wallet-create.test.ts @@ -10,10 +10,10 @@ import * as path from 'node:path'; import { mnemonicToSeedSync } from '@scure/bip39'; import { createWallet, walletFilePath, walletSecretFrom } from '../lib/wallet-create.ts'; import { getActiveWalletName, unlockWallet } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = testHost(); @@ -55,7 +55,7 @@ describe('createWallet', () => { it('derives its addresses from a given mnemonic', async () => { const created = await createWallet(stateRootIn(home), 'bob', walletSecretFrom({ mnemonic: MNEMONIC }), PASSPHRASE, await host.engines.any()); - expect(created.addresses).toEqual(deriveAllAddresses(Buffer.from(mnemonicToSeedSync(MNEMONIC)))); + expect(created.addresses).toEqual(rcKeys.unshieldedAddresses(Buffer.from(mnemonicToSeedSync(MNEMONIC)))); }); it('keeps a given seed and no mnemonic', async () => { diff --git a/src/__tests__/wallet-dust-lib.test.ts b/src/__tests__/wallet-dust-lib.test.ts index b6e48d72..9a6dbeef 100644 --- a/src/__tests__/wallet-dust-lib.test.ts +++ b/src/__tests__/wallet-dust-lib.test.ts @@ -10,18 +10,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import { deriveAllAddresses, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createHost, type Host, settingsFromEnvironment, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { exportDustSnapshot, readDustStatus, registerDust } from '../lib/wallet/dust.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from './helpers/stand-in-indexer.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED_A = 'c3'.repeat(32); @@ -59,7 +55,7 @@ function programHost(name: string): Host & { asked: () => number } { /** Writes `seed`'s wallet as `alice` under the host's state root, and makes it the active one. */ function aliceOf(host: Host, seed: string): void { const root = host.paths().stateRoot; - saveWalletConfig({ seed, addresses: deriveAllAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); + saveWalletConfig({ seed, addresses: rcKeys.unshieldedAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, path.join(root, 'wallets', 'alice.json')); saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); } @@ -73,7 +69,7 @@ describe('readDustStatus', () => { const host = programHost('a'); aliceOf(host, SEED_A); const said: Said[] = []; - const address = deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); + const address = rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'); const status = await readDustStatus(host, { wallet: 'alice' }, { ...endpoints(), onProgress: (event) => said.push(event) }); @@ -89,7 +85,7 @@ describe('readDustStatus', () => { const seed = Buffer.from(SEED_B, 'hex'); const status = await readDustStatus(programHost('a'), { seed }, endpoints()); expect(status).toMatchObject({ registered: false, unregisteredUtxos: 2 }); - expect(indexer.subscriptions.map((s) => s.address)).toEqual([deriveUnshieldedAddress(seed, 'undeployed')]); + expect(indexer.subscriptions.map((s) => s.address)).toEqual([rcKeys.unshieldedAddress(seed, 'undeployed')]); }); it('reads each host\'s own active wallet, two hosts in one process', async () => { @@ -99,8 +95,8 @@ describe('readDustStatus', () => { aliceOf(hostB, SEED_B); await Promise.all([readDustStatus(hostA, {}, endpoints()), readDustStatus(hostB, {}, endpoints())]); expect(indexer.subscriptions.map((s) => s.address).sort()).toEqual([ - deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'), - deriveUnshieldedAddress(Buffer.from(SEED_B, 'hex'), 'undeployed'), + rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed'), + rcKeys.unshieldedAddress(Buffer.from(SEED_B, 'hex'), 'undeployed'), ].sort()); }); diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index 91677959..db1d7ec2 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -10,17 +10,17 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import walletCommand from '../commands/wallet.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { parseArgs } from '@kuiralabs/midnight-cli-core'; import { PASSPHRASE_ENV, isPassphraseSet } from '../lib/passphrase.ts'; import { loadWalletConfig } from '../lib/wallet-config.ts'; -import { deriveAllAddresses } from '@kuiralabs/midnight-engine-rc/derive-address'; -import { captureOutput, type CapturedOutput } from './helpers/capture-output.ts'; +import { rcKeys } from '../../test-support/rc-engine.ts'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; import { accountProtector } from '../lib/grant/account-protector.ts'; import type { WalletProtector } from '../lib/wallet-protector.ts'; import { stateRootIn } from './helpers/state-root-in.ts'; import { cliCall } from './helpers/cli-call.ts'; -import { testHost } from './helpers/test-host.ts'; +import { testHost } from '../../test-support/test-host.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; @@ -29,7 +29,7 @@ let home: string; let io: CapturedOutput; const plainWallet = (name: string): string => - saveWalletConfig({ seed: SEED, addresses: deriveAllAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-10-19T00:00:00.000Z' }, path.join(home, '.midnight', 'wallets', `${name}.json`)); + saveWalletConfig({ seed: SEED, addresses: rcKeys.unshieldedAddresses(Buffer.from(SEED, 'hex')), createdAt: '2026-10-19T00:00:00.000Z' }, path.join(home, '.midnight', 'wallets', `${name}.json`)); /** `wallet protect --json`, given the protectors the CLI gives it unless told otherwise. */ const protect = async (protectors: WalletProtector[] = [accountProtector]): Promise> => { diff --git a/src/__tests__/wallet-transfer-lib.test.ts b/src/__tests__/wallet-transfer-lib.test.ts index bef081fe..43b2cd1f 100644 --- a/src/__tests__/wallet-transfer-lib.test.ts +++ b/src/__tests__/wallet-transfer-lib.test.ts @@ -10,24 +10,20 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { saveCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import { deriveAllAddresses, deriveAllShieldedAddresses, deriveUnshieldedAddress } from '@kuiralabs/midnight-engine-rc/derive-address'; +import { createHost, type Host, settingsFromEnvironment, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; +import { rcKeys } from '../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { transferNight, type TransferNightOptions } from '../lib/wallet/transfer.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from './helpers/stand-in-indexer.ts'; +import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from '../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED_A = 'e5'.repeat(32); const RECIPIENT_SEED = Buffer.from('f6'.repeat(32), 'hex'); -const RECIPIENT = deriveAllAddresses(RECIPIENT_SEED).undeployed; -const RECIPIENT_SHIELDED = deriveAllShieldedAddresses(RECIPIENT_SEED).undeployed; +const RECIPIENT = rcKeys.unshieldedAddresses(RECIPIENT_SEED).undeployed; +const RECIPIENT_SHIELDED = rcKeys.shieldedAddresses(RECIPIENT_SEED).undeployed; // Above what a JS number carries exactly (2^53 micro-NIGHT): 9007199254.740993 NIGHT. const LARGE = 9_007_199_254_740_993n; @@ -64,7 +60,7 @@ function programHost(name: string): Host & { asked: () => number } { function aliceOf(host: Host, seed: string): string { const root = host.paths().stateRoot; const file = path.join(root, 'wallets', 'alice.json'); - saveWalletConfig({ seed, addresses: deriveAllAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, file); + saveWalletConfig({ seed, addresses: rcKeys.unshieldedAddresses(Buffer.from(seed, 'hex')), createdAt: new Date().toISOString() }, file); saveCliConfig({ network: 'undeployed', wallet: 'alice' }, root); return file; } @@ -90,7 +86,7 @@ describe('transferNight', () => { await expect(transferNight(host, { wallet: 'alice' }, transfer({ onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); - expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address: deriveUnshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed') }); + expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address: rcKeys.unshieldedAddress(Buffer.from(SEED_A, 'hex'), 'undeployed') }); expect(said[1]).toEqual({ kind: 'start', message: 'Starting wallet...' }); expect(said.filter((event) => event.kind === 'done')).toEqual([]); expect(indexer.queries).toEqual(['{ block { protocolVersion } }']); @@ -100,7 +96,7 @@ describe('transferNight', () => { const seed = Buffer.from(SEED_A, 'hex'); const said: Said[] = []; await expect(transferNight(programHost('a'), { seed }, transfer({ recipient: RECIPIENT_SHIELDED, shielded: true, onProgress: (event) => said.push(event) }))).rejects.toMatchObject({ code: 'UNSUPPORTED_LEDGER' }); - expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address: deriveUnshieldedAddress(seed, 'undeployed') }); + expect(said[0]).toEqual({ kind: 'wallet-opened', network: 'undeployed', address: rcKeys.unshieldedAddress(seed, 'undeployed') }); expect(said[1]).toEqual({ kind: 'start', message: 'Syncing wallet...' }); }); @@ -117,7 +113,7 @@ describe('transferNight', () => { const host = programHost('a'); aliceOf(host, SEED_A); const said: Said[] = []; - const preprod = { ...transfer({ recipient: deriveAllShieldedAddresses(RECIPIENT_SEED).preprod, shielded: true }), network: 'preprod' as const, onProgress: (event: Said) => said.push(event) }; + const preprod = { ...transfer({ recipient: rcKeys.shieldedAddresses(RECIPIENT_SEED).preprod, shielded: true }), network: 'preprod' as const, onProgress: (event: Said) => said.push(event) }; const refused = transferNight(host, { wallet: 'alice' }, preprod); await expect(refused).rejects.toMatchObject({ code: 'INVALID_ARGS' }); await expect(refused).rejects.toThrow('Shielded is unavailable on preprod (no faucet). Use --force-shielded to sync anyway, or --network undeployed.'); diff --git a/src/__tests__/ws-rpc.test.ts b/src/__tests__/ws-rpc.test.ts index cb506854..c9d8a5b8 100644 --- a/src/__tests__/ws-rpc.test.ts +++ b/src/__tests__/ws-rpc.test.ts @@ -1,8 +1,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import { WebSocket } from 'ws'; import { createRpcServer, createApiError, type RpcServer } from '../lib/ws-rpc.ts'; -import { createHost } from '@kuiralabs/midnight-cli-core/lib/host'; -import { DustRequiredError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { createHost, DustRequiredError } from '@kuiralabs/midnight-cli-core'; // The host the servers run in: notices dropped. const host = createHost(); diff --git a/src/commands/address.definition.ts b/src/commands/address.definition.ts index 68847765..fb59298b 100644 --- a/src/commands/address.definition.ts +++ b/src/commands/address.definition.ts @@ -1,7 +1,7 @@ // The `address` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const addressDefinition: CommandDefinition = { diff --git a/src/commands/address.ts b/src/commands/address.ts index 4471e849..48929280 100644 --- a/src/commands/address.ts +++ b/src/commands/address.ts @@ -1,13 +1,9 @@ // address command — derive and display an unshielded address from a seed // Bare address to stdout (pipeable), formatted details to stderr -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { type ParsedArgs, getFlag, hasFlag, resolveNetworkName, type CallContext, UsageError } from '@kuiralabs/midnight-cli-core'; +import { keyValue, divider, formatAddress, dim } from '@kuiralabs/midnight-cli-core/ui'; import { resolveSeed } from '../lib/seed-resolver.ts'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function addressCommand(args: ParsedArgs, ctx: CallContext): Promise { // `address` is a seed-derivation tool with no active-wallet notion → requireExplicit. diff --git a/src/commands/airdrop.definition.ts b/src/commands/airdrop.definition.ts index b7f46455..664d844d 100644 --- a/src/commands/airdrop.definition.ts +++ b/src/commands/airdrop.definition.ts @@ -1,8 +1,8 @@ // The `airdrop` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const airdropDefinition: CommandDefinition = { diff --git a/src/commands/airdrop.ts b/src/commands/airdrop.ts index 73905f93..4af7c0da 100644 --- a/src/commands/airdrop.ts +++ b/src/commands/airdrop.ts @@ -9,16 +9,10 @@ // file required, useful for funding externally-generated addresses. // A shielded address implies --shielded; the flag is optional there. -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { nightAmountJson, nightAmountText, parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { UsageError, type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites, networkChoiceFromArgs, nightAmountJson, nightAmountText, parseAmount, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatAddress, successMessage, bold, dim, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; import { airdropNight, type AirdropAddressed, type AirdropRecipient, type NightAirdrop } from '../lib/wallet/airdrop.ts'; -import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain'; import { receiptText } from '../ui/receipt.ts'; export default async function airdropCommand(args: ParsedArgs, ctx: CallContext): Promise { diff --git a/src/commands/balance.definition.ts b/src/commands/balance.definition.ts index 9ab9512e..42000fca 100644 --- a/src/commands/balance.definition.ts +++ b/src/commands/balance.definition.ts @@ -1,8 +1,8 @@ // The `balance` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const balanceDefinition: CommandDefinition = { diff --git a/src/commands/balance.ts b/src/commands/balance.ts index 85837974..d124233a 100644 --- a/src/commands/balance.ts +++ b/src/commands/balance.ts @@ -1,18 +1,12 @@ // balance command — check unshielded + shielded balance via full wallet sync // For positional address: unshielded only (GraphQL, no facade) -import { type ParsedArgs, hasFlag, isMinimalMode } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { type ParsedArgs, hasFlag, isMinimalMode, networkChoiceFromArgs, networkTargetOf, shieldedDisabledReason, type CallContext, UsageError } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatNight, formatAddress, toNight, bold, dim, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; import { findWalletByAddress } from '../lib/wallet-config.ts'; import { walletSourceOf } from '../lib/seed-resolver.ts'; -import { networkChoiceFromArgs, networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { shieldedDisabledReason } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; -import { isNativeToken } from '@kuiralabs/midnight-chain/lib/balance-subscription'; +import { isNativeToken } from '@kuiralabs/midnight-chain'; import { addressNetwork, readAddressBalance, readWalletBalance } from '../lib/wallet/balance.ts'; -import { header, keyValue, divider, formatNight, formatAddress, toNight } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function balanceCommand(args: ParsedArgs, ctx: CallContext): Promise { // Positional address → unshielded only (lightweight, no facade) diff --git a/src/commands/cache.definition.ts b/src/commands/cache.definition.ts index 1f4acdba..284dc4e3 100644 --- a/src/commands/cache.definition.ts +++ b/src/commands/cache.definition.ts @@ -1,7 +1,7 @@ // The `cache` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const cacheDefinition: CommandDefinition = { diff --git a/src/commands/cache.ts b/src/commands/cache.ts index 601f5364..decb907b 100644 --- a/src/commands/cache.ts +++ b/src/commands/cache.ts @@ -1,14 +1,9 @@ // cache command — manage wallet state cache // cache clear [--network ] [--wallet ] -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { clearWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { type ParsedArgs, getFlag, hasFlag, UsageError, throwIfCancelled, clearWalletCache, clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache, resolveNetworkName, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { green } from '@kuiralabs/midnight-cli-core/ui'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { green } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { clearChainCaches } from '../lib/chain-caches.ts'; export default async function cacheCommand(args: ParsedArgs, ctx: CallContext): Promise { diff --git a/src/commands/connect.guidance.ts b/src/commands/connect.guidance.ts index 1f53f155..941797b4 100644 --- a/src/commands/connect.guidance.ts +++ b/src/commands/connect.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core'; export const connectGuidance: PackageGuidance = { pieces: [ diff --git a/src/commands/contract.codes.ts b/src/commands/contract.codes.ts index bedd69b4..759bf7a6 100644 --- a/src/commands/contract.codes.ts +++ b/src/commands/contract.codes.ts @@ -1,7 +1,6 @@ // The error codes the contract package owns. -import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { defineCodes, EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core'; export const contractCodes = defineCodes([ { code: 'NO_NODE_RUNTIME', exitCode: EXIT_GENERAL_ERROR, order: 200, summary: 'Contract scripts run under Node.js, and none was found on PATH.', recovery: 'Ask the user to install Node.js 22 or later, or to run mn under Node.' }, diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index 5b8cb573..8956fda2 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -1,9 +1,8 @@ // The `contract` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget, type HostEngines } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; /** The subcommands that reach a chain: inspect reads only the compiled contract (--path, --managed, --name). */ @@ -221,7 +220,7 @@ export const contractDefinition: CommandDefinition = { const { resolveContractDeployRequest } = await import('../lib/contract/request.ts'); const args = call.argv(); const { info } = resolveContractDeployRequest(args, process.cwd()); - const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); + const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'deploy', root, call.host).network, root, call.host.engines); @@ -256,7 +255,7 @@ export const contractDefinition: CommandDefinition = { const { resolveContractCallRequest } = await import('../lib/contract/request.ts'); const args = call.argv(); const { info } = resolveContractCallRequest(args, process.cwd()); - const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core/lib/payer'); + const { resolvePayingTarget } = await import('@kuiralabs/midnight-cli-core'); const { assertContractRunsOn } = await import('../lib/contract/runtime-check.ts'); const root = call.host.paths().stateRoot; await assertContractRunsOn(info, resolvePayingTarget(args, 'contract', 'call', root, call.host).network, root, call.host.engines); diff --git a/src/commands/contract.guidance.ts b/src/commands/contract.guidance.ts index f1d776c7..4e7c1f88 100644 --- a/src/commands/contract.guidance.ts +++ b/src/commands/contract.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core'; import { contractCodes } from './contract.codes.ts'; export const contractGuidance: PackageGuidance = { diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 0a639853..5cca5ab2 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -1,19 +1,12 @@ // Contract commands — inspect, deploy, call, and query state for compiled Midnight contracts. -import { type ParsedArgs, getFlag, hasFlag, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { header, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim, teal, yellow, green } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; - -import { type Payer, payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; +import { type ParsedArgs, getFlag, hasFlag, requireFlag, UsageError, type CallContext, type CallOutput, networkChoiceFromArgs, type Payer, payerFor, type RawStateValue } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, bold, dim, teal, yellow, green, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; + import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { readContractState } from '../lib/contract/state.ts'; import { showPaidStep } from '../lib/wallet/paid-call.ts'; -import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; import { resolveContractCallRequest, resolveContractDeployRequest, resolveDappDir, resolveScanDir } from '../lib/contract/request.ts'; import { findContractInfo, diff --git a/src/commands/dev.codes.ts b/src/commands/dev.codes.ts index fe8954ce..7fc4c884 100644 --- a/src/commands/dev.codes.ts +++ b/src/commands/dev.codes.ts @@ -1,7 +1,6 @@ // The error codes the dev package owns. -import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { defineCodes, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core'; export const devCodes = defineCodes([ { code: 'LOCALNET_UNAVAILABLE', exitCode: EXIT_NETWORK_ERROR, order: 160, summary: "`mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build.", recovery: 'Ask the user to start their ledger-9 stack and point mn at it (endpoint config).' }, diff --git a/src/commands/dev.definition.ts b/src/commands/dev.definition.ts index 820d9ee9..4ac5cc83 100644 --- a/src/commands/dev.definition.ts +++ b/src/commands/dev.definition.ts @@ -1,8 +1,8 @@ // The `dev` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const devDefinition: CommandDefinition = { diff --git a/src/commands/dev.guidance.ts b/src/commands/dev.guidance.ts index 487b8eba..d08f5585 100644 --- a/src/commands/dev.guidance.ts +++ b/src/commands/dev.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core'; import { devCodes } from './dev.codes.ts'; export const devGuidance: PackageGuidance = { diff --git a/src/commands/dev.ts b/src/commands/dev.ts index 01f8f464..2717ba17 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -3,9 +3,8 @@ // M2: `d` keypress deploys the current compiled artifact, `q` quits cleanly. import { resolve, relative } from 'node:path'; -import { type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { type ParsedArgs, payerFor, type CallContext, type CallOutput } from '@kuiralabs/midnight-cli-core'; +import { header, divider, keyValue, bold, dim, red, teal, yellow } from '@kuiralabs/midnight-cli-core/ui'; import { isPassphraseSet, unlockPassphrase } from '../lib/passphrase.ts'; import { detectProject, type ProjectInfo } from '../lib/dev/detect-project.ts'; import { runCompile, type CompileResult } from '../lib/dev/compile.ts'; @@ -19,8 +18,6 @@ import { } from '../lib/dev/provision-wallets.ts'; import { startKeyDispatcher } from '../ui/dev-keys.ts'; import { findWitnessFile, buildMissingWitnessError } from '../lib/contract/witness-discovery.ts'; -import { header, divider, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim, red, teal, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; /** Wallet used when `d` deploys. Must be one of the provisioned dev-* names. */ diff --git a/src/commands/dust.definition.ts b/src/commands/dust.definition.ts index 933f25d2..bf66ca63 100644 --- a/src/commands/dust.definition.ts +++ b/src/commands/dust.definition.ts @@ -1,8 +1,8 @@ // The `dust` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const dustDefinition: CommandDefinition = { diff --git a/src/commands/dust.ts b/src/commands/dust.ts index cb78d88f..ad5cce97 100644 --- a/src/commands/dust.ts +++ b/src/commands/dust.ts @@ -2,20 +2,13 @@ // Usage: midnight dust register | midnight dust status | midnight dust export -import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import type { ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import type { DustExportResult } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, rejectNoCacheForWrites, UsageError, networkChoiceFromArgs, type ProgressEvent, type DustExportResult, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatDust, successMessage, toDust, bold, dim, yellow, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; import { walletSourceOf } from '../lib/seed-resolver.ts'; import { exportDustSnapshot, readDustStatus, registerDust, type DustRegistrationResult, type DustStatus } from '../lib/wallet/dust.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; -import { header, keyValue, divider, formatDust, successMessage, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain'; import { receiptText } from '../ui/receipt.ts'; export default async function dustCommand(args: ParsedArgs, ctx: CallContext): Promise { diff --git a/src/commands/generate.definition.ts b/src/commands/generate.definition.ts index 25a9f054..3d7b78ff 100644 --- a/src/commands/generate.definition.ts +++ b/src/commands/generate.definition.ts @@ -1,8 +1,7 @@ // The `generate` command, described once. -import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { getValidNetworkNames, type CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const generateDefinition: CommandDefinition = { diff --git a/src/commands/generate.ts b/src/commands/generate.ts index f87ead3a..d6f61d58 100644 --- a/src/commands/generate.ts +++ b/src/commands/generate.ts @@ -5,18 +5,14 @@ import * as fs from 'fs'; import * as path from 'path'; -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { type ParsedArgs, getFlag, hasFlag, resolveNetworkName, type CallContext, UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatAddress, bold, yellow, dim, green } from '@kuiralabs/midnight-cli-core/ui'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; import { passphraseForNewSecret } from '../lib/passphrase.ts'; import { parseSeedHex } from '../lib/seed-resolver.ts'; -import { header, keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, yellow, dim, green } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { getDefaultWalletPath } from '../lib/wallet-paths.ts'; -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function generateCommand(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; diff --git a/src/commands/genesis-address.definition.ts b/src/commands/genesis-address.definition.ts index 17a8e788..e9ac910e 100644 --- a/src/commands/genesis-address.definition.ts +++ b/src/commands/genesis-address.definition.ts @@ -1,7 +1,7 @@ // The `genesis-address` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; export const genesisAddressDefinition: CommandDefinition = { name: 'genesis-address', diff --git a/src/commands/genesis-address.ts b/src/commands/genesis-address.ts index 2ec98618..e19e5996 100644 --- a/src/commands/genesis-address.ts +++ b/src/commands/genesis-address.ts @@ -1,11 +1,7 @@ // genesis-address command — display the genesis wallet address (seed 0x01) -import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { GENESIS_SEED } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; +import { type ParsedArgs, hasFlag, GENESIS_SEED, resolveNetworkName, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { keyValue, divider, formatAddress, dim } from '@kuiralabs/midnight-cli-core/ui'; export default async function genesisAddressCommand(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; diff --git a/src/commands/grant.codes.ts b/src/commands/grant.codes.ts index 1fb7eec4..d1f6de02 100644 --- a/src/commands/grant.codes.ts +++ b/src/commands/grant.codes.ts @@ -1,7 +1,6 @@ // The error codes the grant package owns. -import { defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { defineCodes, EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core'; export const grantCodes = defineCodes([ { code: 'NO_ACCOUNT', exitCode: EXIT_GENERAL_ERROR, order: 210, summary: 'A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network.', recovery: 'Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow).' }, diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index 75cfc7e6..fc98bd76 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -1,8 +1,8 @@ // The `grant` command, described once. -import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; /** A grant request can run: its arguments, the network, the account and the wallet are all in order. */ diff --git a/src/commands/grant.guidance.ts b/src/commands/grant.guidance.ts index bb4835dc..d8a8beef 100644 --- a/src/commands/grant.guidance.ts +++ b/src/commands/grant.guidance.ts @@ -2,7 +2,7 @@ // its pieces of `help --agent` and of the two skills, each naming its section // and its place there, and its tools' rows in the manual's tools table. -import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core'; import { grantCodes } from './grant.codes.ts'; export const grantGuidance: PackageGuidance = { diff --git a/src/commands/grant.ts b/src/commands/grant.ts index aeadf319..0375f1cc 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -9,21 +9,14 @@ import { existsSync } from 'node:fs'; // confirmed. The others are paid by this wallet, through its DApp connector in // this process: no server, no port. -import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { DustRequiredError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type ParsedArgs, hasFlag, getFlag, DustRequiredError, UsageError, type CallContext, payerFor, throwIfCancelled, withTransportCode } from '@kuiralabs/midnight-cli-core'; +import { dim, header, keyValue, formatNight, type Spinner } from '@kuiralabs/midnight-cli-core/ui'; import { type GrantAccount, openGrantAccount, ownerDeviceOf } from '../lib/grant/account.ts'; import { deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; import { type OwnerCommandOutput, grantRequestOf, grantsOf, issue, issuePreview, revoke, revokeAll, statusOf } from '../lib/grant/owner-commands.ts'; import { prepareGrant } from '../lib/grant/prepare.ts'; import { type GrantRequest, paysAFee } from '../lib/grant/request.ts'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { type PayingWallet, openPayingWallet } from '../lib/grant/fee-wallet.ts'; -import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { header, keyValue, formatNight } from '@kuiralabs/midnight-cli-core/ui/format'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { withTransportCode } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; const SPINNER_LABEL: Record = { deploy: 'Deploying the account...', diff --git a/src/commands/help.definition.ts b/src/commands/help.definition.ts index 4e1e4f2a..85eb7200 100644 --- a/src/commands/help.definition.ts +++ b/src/commands/help.definition.ts @@ -1,7 +1,7 @@ // The `help` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; export const helpDefinition: CommandDefinition = { name: 'help', diff --git a/src/commands/help.ts b/src/commands/help.ts index 2680f032..c7cfba3e 100644 --- a/src/commands/help.ts +++ b/src/commands/help.ts @@ -5,18 +5,14 @@ // Every list of commands it shows comes from the command registry, and the // agent manual from the installed packages' guidance. -import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { bold, teal, gray, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { header } from '@kuiralabs/midnight-cli-core/ui/format'; +import { type ParsedArgs, hasFlag, commandHelpSpecs, introBriefs, type CommandHelpSpec, UsageError, type CallContext, type CallOutput } from '@kuiralabs/midnight-cli-core'; +import { bold, teal, gray, dim, header } from '@kuiralabs/midnight-cli-core/ui'; import { animateMaterialize } from '../ui/animate.ts'; import { WORDMARK_BIG } from '../ui/art.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { agentManual } from '../lib/agent-manual.ts'; import { commandCodeLines } from '../lib/code-tables.ts'; -import { commandHelpSpecs, introBriefs, type CommandHelpSpec } from '@kuiralabs/midnight-cli-core/lib/command-definition'; import { hasShownIntroThisSession, markIntroShown } from '../lib/intro-marker.ts'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; import { PKG_NAME, PKG_VERSION, PKG_DESCRIPTION } from '../lib/pkg.ts'; type CommandSpec = CommandHelpSpec; diff --git a/src/commands/info.definition.ts b/src/commands/info.definition.ts index 18f97cae..79c85bfd 100644 --- a/src/commands/info.definition.ts +++ b/src/commands/info.definition.ts @@ -1,8 +1,7 @@ // The `info` command, described once. -import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; -import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { getValidNetworkNames, type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const infoDefinition: CommandDefinition = { diff --git a/src/commands/info.ts b/src/commands/info.ts index df7c6b45..f9203b56 100644 --- a/src/commands/info.ts +++ b/src/commands/info.ts @@ -1,13 +1,9 @@ // info command — display wallet metadata (no secrets) // Shows addresses for all networks + shielded, creation date, file path -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { type ParsedArgs, getFlag, hasFlag, resolveNetworkName, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, divider, formatAddress, bold, dim, teal } from '@kuiralabs/midnight-cli-core/ui'; import { loadWalletConfig, resolveWalletPath, walletAddress } from '../lib/wallet-config.ts'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; -import { formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim, teal } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function infoCommand(args: ParsedArgs, ctx: CallContext): Promise { const root = ctx.config.paths.stateRoot; diff --git a/src/commands/inspect-cost.definition.ts b/src/commands/inspect-cost.definition.ts index 2bc91a76..2a9e3e47 100644 --- a/src/commands/inspect-cost.definition.ts +++ b/src/commands/inspect-cost.definition.ts @@ -1,8 +1,8 @@ // The `inspect-cost` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; export const inspectCostDefinition: CommandDefinition = { name: 'inspect-cost', diff --git a/src/commands/inspect-cost.ts b/src/commands/inspect-cost.ts index 3be49552..90bd21f7 100644 --- a/src/commands/inspect-cost.ts +++ b/src/commands/inspect-cost.ts @@ -2,13 +2,10 @@ // ledger parameters of its latest block, as the engine for the chain's SDK // set reads them. -import { type ParsedArgs, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { header, keyValue, divider } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; +import { type ParsedArgs, hasFlag, type CallContext, resolveNetwork } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, bold, dim } from '@kuiralabs/midnight-cli-core/ui'; import { fetchLedgerParameters } from '../lib/chain-params.ts'; -import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { assertLedgerSupported, fetchProtocolVersion } from '@kuiralabs/midnight-chain'; const UNITS: Record = { readTime: 'picoseconds', diff --git a/src/commands/localnet.definition.ts b/src/commands/localnet.definition.ts index 2a2233d6..e4f2095b 100644 --- a/src/commands/localnet.definition.ts +++ b/src/commands/localnet.definition.ts @@ -1,7 +1,7 @@ // The `localnet` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; export const localnetDefinition: CommandDefinition = { name: 'localnet', diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index df9cb2e5..c74d13be 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -2,9 +2,8 @@ // Subcommands: up, down, status, logs import { spawn } from 'child_process'; -import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { CancelledError, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { execProgram, ProgramFailedError, type ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; +import { type ParsedArgs, hasFlag, getFlag, CancelledError, UsageError, execProgram, ProgramFailedError, type ExecRunner, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, divider, bold, green, red, dim, yellow } from '@kuiralabs/midnight-cli-core/ui'; import { assertLocalnetCanStart, checkDockerAvailable, @@ -18,10 +17,7 @@ import { type DockerCall, type ServiceStatus, } from '../lib/localnet.ts'; -import { header, divider } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, green, red, dim, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; const VALID_SUBCOMMANDS = ['up', 'stop', 'down', 'status', 'logs', 'clean'] as const; type Subcommand = typeof VALID_SUBCOMMANDS[number]; @@ -68,11 +64,11 @@ async function handleUp(jsonMode: boolean, ctx: CallContext, docker: DockerCall) // prove time with "Failed to prove transaction". spinner.update('Waiting for chain to produce first block...'); try { - const { waitForFirstBlock } = await import('@kuiralabs/midnight-chain/lib/node-ready'); - const { waitForAddressFunded } = await import('@kuiralabs/midnight-chain/lib/indexer-ready'); - const { waitForProofServerReady } = await import('@kuiralabs/midnight-chain/lib/proof-server-ready'); - const { getNetworkConfig } = await import('@kuiralabs/midnight-cli-core/lib/network'); - const { GENESIS_SEED } = await import('@kuiralabs/midnight-cli-core/lib/constants'); + const { waitForFirstBlock } = await import('@kuiralabs/midnight-chain'); + const { waitForAddressFunded } = await import('@kuiralabs/midnight-chain'); + const { waitForProofServerReady } = await import('@kuiralabs/midnight-chain'); + const { getNetworkConfig } = await import('@kuiralabs/midnight-cli-core'); + const { GENESIS_SEED } = await import('@kuiralabs/midnight-cli-core'); const netCfg = getNetworkConfig('undeployed'); await waitForFirstBlock(netCfg.node, { timeoutMs: 30_000, signal: ctx.signal }); diff --git a/src/commands/manual.definition.ts b/src/commands/manual.definition.ts index ac6abbc3..2634c6ab 100644 --- a/src/commands/manual.definition.ts +++ b/src/commands/manual.definition.ts @@ -1,7 +1,7 @@ // The `manual` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; export const manualDefinition: CommandDefinition = { name: 'manual', diff --git a/src/commands/manual.ts b/src/commands/manual.ts index abb0e188..80ac9dc4 100644 --- a/src/commands/manual.ts +++ b/src/commands/manual.ts @@ -5,9 +5,8 @@ // search and scroll. Disable with --no-pager. import { spawn } from 'node:child_process'; -import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import type { CallContext, CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { bold, dim, teal, yellow, white } from '@kuiralabs/midnight-cli-core/ui/colors'; +import { type ParsedArgs, hasFlag, getFlag, type CallContext, type CallOutput } from '@kuiralabs/midnight-cli-core'; +import { bold, dim, teal, yellow, white } from '@kuiralabs/midnight-cli-core/ui'; import { helpSpecs, type CommandSpec } from './help.ts'; import { PKG_NAME, PKG_VERSION, PKG_REPOSITORY_URL } from '../lib/pkg.ts'; import { installedCommands } from '../lib/installed-commands.ts'; diff --git a/src/commands/serve.definition.ts b/src/commands/serve.definition.ts index d2d66d84..8306c3cc 100644 --- a/src/commands/serve.definition.ts +++ b/src/commands/serve.definition.ts @@ -1,8 +1,8 @@ // The `serve` command, described once. -import type { CommandDefinition } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const serveDefinition: CommandDefinition = { diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 68463ea0..c3177f99 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -2,23 +2,10 @@ // Usage: midnight serve [--port 9932] [--wallet path] [--network name] // [--approve-all | --approve-fees] [--no-auto-approve-reads] [--json] -import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; +import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites, resolveNetwork, applyEndpointOverrides, type DAppConnector, type DAppConnectorCallbacks, OPERATOR_REJECTED_MESSAGE, type PhaseTiming, DEFAULT_SERVE_PORT, shieldedSyncEnabled, parseFeeLimits, describeApprovalPolicy, type CallContext, UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatAddress, toDust, bold, dim, teal, green, red, type Spinner } from '@kuiralabs/midnight-cli-core/ui'; import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { applyEndpointOverrides } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { DAppConnector, DAppConnectorCallbacks } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import type { PhaseTiming } from '@kuiralabs/midnight-cli-core/lib/phase-tracker'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; -import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { shieldedSyncEnabled } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; -import { header, keyValue, divider, formatAddress, toDust } from '@kuiralabs/midnight-cli-core/ui/format'; -import { parseFeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; -import { describeApprovalPolicy } from '@kuiralabs/midnight-cli-core/lib/approval'; -import { bold, dim, teal, green, red } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; export default async function serveCommand(args: ParsedArgs, ctx: CallContext): Promise { rejectNoCacheForWrites(args); diff --git a/src/commands/swap.definition.ts b/src/commands/swap.definition.ts index 76237ce3..e31bdf43 100644 --- a/src/commands/swap.definition.ts +++ b/src/commands/swap.definition.ts @@ -1,8 +1,8 @@ // The `swap` command, described once. -import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; /** The terms a swap request states, as the maker gives and wants them. */ diff --git a/src/commands/swap.guidance.ts b/src/commands/swap.guidance.ts index 76538e0d..2290488e 100644 --- a/src/commands/swap.guidance.ts +++ b/src/commands/swap.guidance.ts @@ -1,7 +1,7 @@ // What the swap package (mn swap) tells agents: its pieces of `help --agent` // and of the full skill, the manual section it adds, and its tools' rows. -import type { PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import type { PackageGuidance } from '@kuiralabs/midnight-cli-core'; export const swapGuidance: PackageGuidance = { sections: [{ text: 'agent-manual', name: 'swaps', after: 'grants' }], diff --git a/src/commands/swap.ts b/src/commands/swap.ts index de50c2af..c1f01428 100644 --- a/src/commands/swap.ts +++ b/src/commands/swap.ts @@ -5,15 +5,8 @@ // payer's wallet session: no server, no port. inspect and list open no wallet. import { existsSync, writeFileSync } from 'node:fs'; -import { type ParsedArgs, hasFlag, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { payerFor } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import type { SwapLeg, SwapTerms } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; -import { header, keyValue } from '@kuiralabs/midnight-cli-core/ui/format'; -import { dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; +import { type ParsedArgs, hasFlag, getFlag, UsageError, networkChoiceFromArgs, payerFor, type CallContext, type SwapLeg, type SwapTerms } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, dim, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; import { showPaidStep } from '../lib/wallet/paid-call.ts'; import { makeSwapOffer } from '../lib/swap/make.ts'; import { inspectSwapOffer } from '../lib/swap/inspect.ts'; @@ -21,7 +14,7 @@ import { takeSwapOffer } from '../lib/swap/take.ts'; import { cancelSwapOffer } from '../lib/swap/cancel.ts'; import { listSwapOffers } from '../lib/swap/list.ts'; import { makeTermsOf, readOfferText, termsOf } from '../lib/swap/request.ts'; -import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain'; import { receiptText } from '../ui/receipt.ts'; const legJson = ({ token, amount }: SwapLeg) => ({ token, amount: amount.toString() }); diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index a527f02d..95c5f44c 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -1,9 +1,8 @@ // The `test` command, described once. -import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; -import { EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { type CommandDefinition, NETWORK_PARAM, EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const testDefinition: CommandDefinition = { diff --git a/src/commands/test.ts b/src/commands/test.ts index b8368bf6..25cd8ed6 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -2,16 +2,11 @@ // Usage: midnight test [options] // Discovers dapp.test.json in the current directory and executes test suites. -import { isValidNetworkName, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { isValidNetworkName, type NetworkName, type ParsedArgs, getFlag, hasFlag, CancelledError, throwIfCancelled, UsageError, type CallContext, type CallOutput, type CallProgress, type CommandOutcome } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, bold, dim, green, red, teal, yellow, type Spinner } from '@kuiralabs/midnight-cli-core/ui'; import { StringDecoder } from 'node:string_decoder'; import { join } from 'node:path'; import { mkdirSync } from 'node:fs'; -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { CancelledError, throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { CallContext, CallOutput, CallProgress, CommandOutcome } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { header, keyValue, divider } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim, green, red, teal, yellow } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; import { discoverDappConfig, discoverTestSuites, loadAssertions, loadActions, loadPrompt } from '../lib/test/discovery.ts'; import { createPrepContext, type TestRunResult, type PrepStepResult } from '../lib/test/types.ts'; @@ -544,7 +539,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): } const { runActions, diffState } = await import('../lib/test/actions-runner.ts'); - const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core/lib/resolve-network'); + const { resolveNetwork } = await import('@kuiralabs/midnight-cli-core'); const network = config.network ?? 'undeployed'; const { config: networkConfig } = resolveNetwork({ @@ -554,7 +549,7 @@ async function handleRun(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): // mn serve should already be started by the prep step (mn-serve) // Use the serve port from the prep context if available, otherwise default - const { DEFAULT_SERVE_PORT } = await import('@kuiralabs/midnight-cli-core/lib/constants'); + const { DEFAULT_SERVE_PORT } = await import('@kuiralabs/midnight-cli-core'); const servePort = prep.serveHandle?.port ?? DEFAULT_SERVE_PORT; const redeployFlag = hasFlag(args, 'redeploy'); diff --git a/src/commands/transfer.definition.ts b/src/commands/transfer.definition.ts index b5faaa0f..1c340ec7 100644 --- a/src/commands/transfer.definition.ts +++ b/src/commands/transfer.definition.ts @@ -1,8 +1,8 @@ // The `transfer` command, described once. -import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands/chain.codes'; +import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget } from '@kuiralabs/midnight-cli-core'; +import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; +import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const transferDefinition: CommandDefinition = { diff --git a/src/commands/transfer.ts b/src/commands/transfer.ts index da0acdb0..10d686a1 100644 --- a/src/commands/transfer.ts +++ b/src/commands/transfer.ts @@ -1,17 +1,12 @@ // transfer command — send NIGHT from my wallet to another address // Usage: midnight transfer [--shielded] -import { type ParsedArgs, hasFlag, rejectNoCacheForWrites } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { networkChoiceFromArgs } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { nightAmountJson, nightAmountText } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { type ParsedArgs, hasFlag, rejectNoCacheForWrites, networkChoiceFromArgs, nightAmountJson, nightAmountText, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatAddress, successMessage, bold, dim, spinnerReporter } from '@kuiralabs/midnight-cli-core/ui'; import { resolveTransferRequest, type TransferRequest } from '../lib/transfer-request.ts'; import { transferNight, type NightTransfer } from '../lib/wallet/transfer.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; -import { header, keyValue, divider, formatAddress, successMessage } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, dim } from '@kuiralabs/midnight-cli-core/ui/colors'; -import { spinnerReporter } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import { receiptJson } from '@kuiralabs/midnight-chain/lib/tx-receipt'; +import { receiptJson } from '@kuiralabs/midnight-chain'; import { receiptText } from '../ui/receipt.ts'; export default async function transferCommand(args: ParsedArgs, ctx: CallContext): Promise { diff --git a/src/commands/wallet.codes.ts b/src/commands/wallet.codes.ts index be9ed1b8..25b7c358 100644 --- a/src/commands/wallet.codes.ts +++ b/src/commands/wallet.codes.ts @@ -1,8 +1,7 @@ // The error codes the wallet package owns, and the set a command definition // declares when it opens a saved wallet. -import { defineCodeSet, defineCodes } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { EXIT_WALLET_NOT_FOUND } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; +import { defineCodeSet, defineCodes, EXIT_WALLET_NOT_FOUND } from '@kuiralabs/midnight-cli-core'; export const walletCodes = defineCodes([ { code: 'WALLET_NOT_FOUND', exitCode: EXIT_WALLET_NOT_FOUND, order: 20, summary: "Named wallet doesn't exist on disk.", recovery: '`midnight_wallet_list()` — user may have removed it.' }, diff --git a/src/commands/wallet.definition.ts b/src/commands/wallet.definition.ts index 28bcacd7..934ed67a 100644 --- a/src/commands/wallet.definition.ts +++ b/src/commands/wallet.definition.ts @@ -1,8 +1,7 @@ // The `wallet` command, described once. -import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; -import { type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands/core.codes'; +import { getValidNetworkNames, type CommandDefinition, NETWORK_PARAM } from '@kuiralabs/midnight-cli-core'; +import { LOADS_ENGINE, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { OPENS_WALLET } from './wallet.codes.ts'; export const walletDefinition: CommandDefinition = { diff --git a/src/commands/wallet.guidance.ts b/src/commands/wallet.guidance.ts index ef3207d5..c530f091 100644 --- a/src/commands/wallet.guidance.ts +++ b/src/commands/wallet.guidance.ts @@ -3,7 +3,7 @@ // skills, each naming its section and its place there, and its tools' rows in // the manual's tools table. -import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { codeGuidancePieces, type PackageGuidance } from '@kuiralabs/midnight-cli-core'; import { walletCodes } from './wallet.codes.ts'; export const walletGuidance: PackageGuidance = { diff --git a/src/commands/wallet.ts b/src/commands/wallet.ts index e1f555dd..fa604c61 100644 --- a/src/commands/wallet.ts +++ b/src/commands/wallet.ts @@ -2,11 +2,10 @@ // Subcommands: generate, list, use, info, remove import * as fs from 'fs'; -import { type ParsedArgs, getFlag, hasFlag, isMinimalMode } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, UsageError, throwIfCancelled, resolveNetworkName, type CallContext } from '@kuiralabs/midnight-cli-core'; +import { header, keyValue, divider, formatAddress, bold, yellow, dim, green, teal } from '@kuiralabs/midnight-cli-core/ui'; import { mnemonicToEntropy } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; import { parseSeedHex } from '../lib/seed-resolver.ts'; import { loadWalletConfig, @@ -22,9 +21,6 @@ import { import { passphraseForNewSecret } from '../lib/passphrase.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../lib/wallet-create.ts'; import { coinKeyOfWallet, type ProtectorResult, type WalletCommandContext } from '../lib/wallet-protector.ts'; -import { header, keyValue, divider, formatAddress } from '@kuiralabs/midnight-cli-core/ui/format'; -import { bold, yellow, dim, green, teal } from '@kuiralabs/midnight-cli-core/ui/colors'; -import type { CallContext } from '@kuiralabs/midnight-cli-core/lib/call-context'; export default async function walletCommand(args: ParsedArgs, ctx: WalletCommandContext): Promise { const subcommand = args.subcommand; diff --git a/src/lib/agent-manual.ts b/src/lib/agent-manual.ts index 61731369..4bdcbc70 100644 --- a/src/lib/agent-manual.ts +++ b/src/lib/agent-manual.ts @@ -6,8 +6,7 @@ import { PKG_VERSION } from './pkg.ts'; import { codeSetLines } from './code-tables.ts'; -import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type ToolsTableRow } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; -import { commandHelpSpecs, type CommandRegistry, type RegisteredTool } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { GuidanceError, assembleGuidance, sectionsWithAdded, type GuidancePiece, type ToolsTableRow, commandHelpSpecs, type CommandRegistry, type RegisteredTool } from '@kuiralabs/midnight-cli-core'; /** The manual's sections, in order. */ export const AGENT_MANUAL_SECTIONS = [ diff --git a/src/lib/chain-caches.ts b/src/lib/chain-caches.ts index 3e1fe8af..24dfe890 100644 --- a/src/lib/chain-caches.ts +++ b/src/lib/chain-caches.ts @@ -3,10 +3,7 @@ // still referring to it is stale and would fail the next command, and // `cache clear` clears the same set. -import { clearWalletCache } from '@kuiralabs/midnight-cli-core/lib/wallet-cache'; -import { clearDustDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { clearShieldedDirectCache } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; -import { clearNativeDustCheckpoint } from '@kuiralabs/midnight-cli-core/lib/reader-cache-files'; +import { clearWalletCache, clearDustDirectCache, clearShieldedDirectCache, clearNativeDustCheckpoint } from '@kuiralabs/midnight-cli-core'; /** * Clears every wallet cache kept for `network` (all networks when undefined) diff --git a/src/lib/chain-params.ts b/src/lib/chain-params.ts index df2091cf..5a624258 100644 --- a/src/lib/chain-params.ts +++ b/src/lib/chain-params.ts @@ -4,7 +4,7 @@ // parameters: on a ledger-9 localnet the block limits for read time and // block usage are 2x and 5x the initial ones. -import { queryIndexer } from '@kuiralabs/midnight-chain/lib/indexer-graphql'; +import { queryIndexer } from '@kuiralabs/midnight-chain'; export interface ChainLedgerParameters { height: number; diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index b4526ce3..41481212 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -11,10 +11,7 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; import { installSdkNoiseFilters } from './sdk-noise.ts'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { createHost, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { settingsFromEnvironment, type Prompter, MIDNIGHT_DIR, createHost, type Host } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from './installed-engines.ts'; /** The CLI's host, or the MCP server's (`prompter` null: no terminal there). */ diff --git a/src/lib/code-tables.ts b/src/lib/code-tables.ts index a875c926..80763df1 100644 --- a/src/lib/code-tables.ts +++ b/src/lib/code-tables.ts @@ -7,10 +7,8 @@ // The manual's and the skills' rows come from each package's guidance // (codeGuidancePieces). -import { declaredCodeSets, type CommandHelpSpec, type CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import type { CodeDefinition } from '@kuiralabs/midnight-cli-core/lib/error-codes'; -import { wrapWords } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; +import { declaredCodeSets, type CommandHelpSpec, type CommandRegistry, type CodeDefinition, wrapWords } from '@kuiralabs/midnight-cli-core'; +import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands'; import { withGeneratedBlock } from './readme-commands.ts'; /** The markers around the generated table in docs/JSON_CONTRACT.md. */ diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index fb4cf7ed..4a402f26 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -3,14 +3,7 @@ // shell (src/wallet.ts) owns the process: it passes in what a handler may be // given and where a notice goes, and decides the heap and the exit. -import type { ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import type { CommandDefinition, CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { writeJsonResult } from '@kuiralabs/midnight-cli-core/lib/json-output'; -import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { type ParsedArgs, createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput, type CommandDefinition, type CommandRegistry, UsageError, writeJsonResult, type Payer, type CallSdkWarnings, type Host } from '@kuiralabs/midnight-cli-core'; import type { WalletProtector } from './wallet-protector.ts'; /** What the shell can give a handler: its call's signal and output, and, as its definition's `shell` field asks, the payer or protectors, loaded only then. */ diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index 0172bf66..c7fe41e8 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -1,11 +1,7 @@ // Calling a circuit of a deployed contract: the call script, run against the // wallet the payer serves (served-wallet.ts). `mn contract call` calls through here. -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { type Host, throwIfCancelled, type NetworkName, networkTargetOf, withCallSdkWarnings } from '@kuiralabs/midnight-cli-core'; import { networkChoiceOf } from '../wallet/wallet-call.ts'; import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; import { withServedWallet } from './served-wallet.ts'; diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index 5aa42e4c..d5056049 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -1,11 +1,7 @@ // Deploying a compiled contract: the deploy script, run against the wallet // the payer serves (served-wallet.ts). `mn contract deploy` and `mn dev` both deploy through here. -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { networkTargetOf } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { withCallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { type Host, throwIfCancelled, type NetworkName, networkTargetOf, withCallSdkWarnings } from '@kuiralabs/midnight-cli-core'; import { networkChoiceOf } from '../wallet/wallet-call.ts'; import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; import { withServedWallet } from './served-wallet.ts'; diff --git a/src/lib/contract/request.ts b/src/lib/contract/request.ts index ebd2e1c9..1a57493c 100644 --- a/src/lib/contract/request.ts +++ b/src/lib/contract/request.ts @@ -5,8 +5,7 @@ // working directory the caller gives as their default folder. import { resolve } from 'node:path'; -import { type ParsedArgs, getFlag, requireFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type ParsedArgs, getFlag, requireFlag, UsageError } from '@kuiralabs/midnight-cli-core'; import { findContractInfo, type ContractInfo } from './inspect.ts'; import { findWitnessFile, buildMissingWitnessError } from './witness-discovery.ts'; import { validateCallRequest, validateContractAddress } from './validate.ts'; diff --git a/src/lib/contract/runner.ts b/src/lib/contract/runner.ts index da0e4708..8358f8a3 100644 --- a/src/lib/contract/runner.ts +++ b/src/lib/contract/runner.ts @@ -11,16 +11,12 @@ import { writeFileSync, unlinkSync, existsSync, symlinkSync, readFileSync, mkdir import { join, dirname, delimiter } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; -import { assertEndpointUsable } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; -import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { sdkSetOf, type EngineContractScripts, type HostEngines, type ScriptParts } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { assertEndpointUsable, type NetworkConfig, type NetworkName, sdkSetOf, type EngineContractScripts, type HostEngines, type ScriptParts, CancelledError, throwIfCancelled, isTransportFailure } from '@kuiralabs/midnight-cli-core'; import { findContractInfo } from './inspect.ts'; import { assertContractRunsOn } from './runtime-check.ts'; import { WITNESS_FILE_CANDIDATES } from './witness-discovery.ts'; import { coerceArg } from './arg-coerce.ts'; import { resolvePrivateStateSecretKey } from './private-state-secret.ts'; -import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { isTransportFailure } from '@kuiralabs/midnight-cli-core/lib/transport-failure'; // The generated deploy/call script imports SDK packages by bare specifier // (`@midnight-ntwrk/midnight-js-contracts`, `ws`, etc.); without help, Node diff --git a/src/lib/contract/runtime-check.ts b/src/lib/contract/runtime-check.ts index 7c905a25..12e7259e 100644 --- a/src/lib/contract/runtime-check.ts +++ b/src/lib/contract/runtime-check.ts @@ -3,9 +3,7 @@ // front, naming the compiler this network's set needs, instead of failing in // its script after the wallet has synced ("Version mismatch"). -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { sdkSetOf, type HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { UsageError, sdkSetOf, type HostEngines, type NetworkName } from '@kuiralabs/midnight-cli-core'; import type { ContractInfo } from './inspect.ts'; /** A deploy's or call's contract runs on the network's runtime: paying for it starts next. */ diff --git a/src/lib/contract/served-wallet.ts b/src/lib/contract/served-wallet.ts index 245e5f8e..3357e9ee 100644 --- a/src/lib/contract/served-wallet.ts +++ b/src/lib/contract/served-wallet.ts @@ -2,10 +2,8 @@ // can pay, serve it through the payer, run the script against it with a // progress line, and stop serving whatever happens. -import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type Payer, type PayingTarget, type CallSdkWarnings, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; export interface ServedWalletParams { target: PayingTarget; diff --git a/src/lib/contract/state.ts b/src/lib/contract/state.ts index 820b177c..e97c664c 100644 --- a/src/lib/contract/state.ts +++ b/src/lib/contract/state.ts @@ -3,13 +3,7 @@ // that can't run (no compiled contract there, a script that fails), the // untyped state tree the indexer holds for the address. -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { networkTargetOf, type NetworkChoice } from '@kuiralabs/midnight-cli-core/lib/network-target'; -import { progressSteps, type ProgressEvent } from '@kuiralabs/midnight-cli-core/lib/progress'; -import { untilCancelled } from '@kuiralabs/midnight-cli-core/lib/sleep'; -import type { RawStateValue } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { type Host, CancelledError, throwIfCancelled, type NetworkName, networkTargetOf, type NetworkChoice, progressSteps, type ProgressEvent, untilCancelled, type RawStateValue } from '@kuiralabs/midnight-cli-core'; import { networkChoiceOf } from '../wallet/wallet-call.ts'; import { findContractInfo } from './inspect.ts'; import { validateContractAddress } from './validate.ts'; diff --git a/src/lib/contract/validate.ts b/src/lib/contract/validate.ts index 71063d82..d60a6af5 100644 --- a/src/lib/contract/validate.ts +++ b/src/lib/contract/validate.ts @@ -5,7 +5,7 @@ // length of 32"), and a wrong argument count as the runtime's count, which // includes its own context ("expected 1 argument ... received 4" for 3 args). -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; import type { ContractInfo } from './inspect.ts'; /** A contract address is 32 bytes as 64 hex characters. */ diff --git a/src/lib/dev/deploy.ts b/src/lib/dev/deploy.ts index 0fbeee5d..a0d2cdf0 100644 --- a/src/lib/dev/deploy.ts +++ b/src/lib/dev/deploy.ts @@ -5,11 +5,8 @@ import { deployContract, type DeployedContract } from '../contract/deploy.ts'; import { contractDeployRequest } from '../contract/request.ts'; -import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import type { Payer, Host, NetworkName, CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; /** * Deploys the contract compiled in `projectRoot` on `network`, paid by diff --git a/src/lib/dev/localnet-ready.ts b/src/lib/dev/localnet-ready.ts index 3e3e7c20..c0891b01 100644 --- a/src/lib/dev/localnet-ready.ts +++ b/src/lib/dev/localnet-ready.ts @@ -3,8 +3,8 @@ // running stack at the endpoints `undeployed` resolves to (saved config, or // the single local stack docker shows). -import { resolveNetwork, type NetworkSettings } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { assertLedger9StackReachable } from '@kuiralabs/midnight-chain/lib/ledger-guard'; +import { resolveNetwork, type NetworkSettings } from '@kuiralabs/midnight-cli-core'; +import { assertLedger9StackReachable } from '@kuiralabs/midnight-chain'; export type LocalnetState = 'already-running'; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 569082a0..0f02302b 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -7,13 +7,8 @@ import { existsSync } from 'node:fs'; import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet, type UnlockHost } from '../wallet-config.ts'; import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; import { passphraseForNewSecret } from '../passphrase.ts'; -import { sdkSetOf } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { checkBalance } from '@kuiralabs/midnight-chain/lib/balance-subscription'; -import { resolveNetwork, type NetworkSettings } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import type { NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { nightToMicro } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { sdkSetOf, resolveNetwork, type NetworkSettings, type NetworkConfig, type CallSdkWarnings, throwIfCancelled, nightToMicro } from '@kuiralabs/midnight-cli-core'; +import { checkBalance } from '@kuiralabs/midnight-chain'; /** Default dev wallet names — one per common test persona. */ export const DEFAULT_DEV_WALLET_NAMES = ['dev-alice', 'dev-bob', 'dev-carol'] as const; diff --git a/src/lib/grant/account-backup.ts b/src/lib/grant/account-backup.ts index 0901b46b..7cae8d38 100644 --- a/src/lib/grant/account-backup.ts +++ b/src/lib/grant/account-backup.ts @@ -10,13 +10,10 @@ // a second device (`midnight grant device add`). import * as fs from 'node:fs'; -import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { type HostEngines, UsageError, FileExistsError, writeJsonDurably, type SealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { type OwnerRecord, type Roster, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { FileExistsError, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; -import { type SealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; import { privateStateLocationOf } from './account.ts'; import { type DeviceIdentity, deviceCodeOf } from './device-code.ts'; import { diff --git a/src/lib/grant/account-records.ts b/src/lib/grant/account-records.ts index 5fdfde13..e43a5495 100644 --- a/src/lib/grant/account-records.ts +++ b/src/lib/grant/account-records.ts @@ -5,7 +5,7 @@ import { mkdirSync } from 'node:fs'; import { basename, join } from 'node:path'; -import { DIR_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { DIR_MODE } from '@kuiralabs/midnight-cli-core'; /** The directory under ~/.midnight that holds each network's accounts. */ export const ACCOUNTS_DIR_NAME = 'accounts'; diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 15f56410..7e3d3456 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -35,9 +35,7 @@ import { sealedOwnerStore, sealedPrivateStatePassword, } from './sealed-account.ts'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { isValidNetworkName, sdkSetOfNetwork, type NetworkConfig } from '@kuiralabs/midnight-cli-core/lib/network'; -import type { SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { UsageError, isValidNetworkName, sdkSetOfNetwork, type NetworkConfig, type SdkSet } from '@kuiralabs/midnight-cli-core'; /** Where the account package caches its proving artefacts, under ~/.midnight: each file is fetched the first time a command proves with it. */ const ACCOUNT_ARTIFACTS_DIR_NAME = 'account-artifacts'; diff --git a/src/lib/grant/deploy-cost.ts b/src/lib/grant/deploy-cost.ts index 09fb7a41..1676e4d2 100644 --- a/src/lib/grant/deploy-cost.ts +++ b/src/lib/grant/deploy-cost.ts @@ -13,7 +13,7 @@ // 12.23, 9.87, 10.00, 1.37, 0.26: 33.74 in fees, 43.74 from the wallet, 15.62 for the largest // 13.40, 10.74, 10.82, 1.53, 0.27: 36.75 in fees, 47.51 from the wallet, 17.08 for the largest -import { formatDust } from '@kuiralabs/midnight-cli-core/ui/format'; +import { formatDust } from '@kuiralabs/midnight-cli-core/ui'; export const MEASURED_ACCOUNT_DEPLOY = { transactions: 5, diff --git a/src/lib/grant/device-code.ts b/src/lib/grant/device-code.ts index cab7fc46..022bf6f6 100644 --- a/src/lib/grant/device-code.ts +++ b/src/lib/grant/device-code.ts @@ -12,7 +12,7 @@ import { type Arm, type DeviceKey, type ReadKeyAttestation, deviceCodeOf as libraryDeviceCodeOf, joinCodeOf as libraryJoinCodeOf, parseDeviceCode as libraryParseDeviceCode } from '@kuiralabs/midnight-account'; import type { LocalOwnerDevice, OwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; /** A device named by its arm and public key, with its read key, and its signature of it when the code carries one. */ export interface DeviceIdentity { diff --git a/src/lib/grant/fee-wallet.ts b/src/lib/grant/fee-wallet.ts index a8ec37ca..10fc45b8 100644 --- a/src/lib/grant/fee-wallet.ts +++ b/src/lib/grant/fee-wallet.ts @@ -2,10 +2,8 @@ // process, made into the account package's fee wallet. import type { FeeWallet } from '@kuiralabs/midnight-account-chain/owner'; -import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { Payer, PayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui/spinner'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { NATIVE_TOKEN_TYPE, type Payer, type PayingTarget, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; +import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; /** A fee wallet in this process, and how to stop it. */ export interface PayingWallet { diff --git a/src/lib/grant/owner-commands.ts b/src/lib/grant/owner-commands.ts index 16983b99..2a7a9944 100644 --- a/src/lib/grant/owner-commands.ts +++ b/src/lib/grant/owner-commands.ts @@ -21,7 +21,7 @@ import { sealedResponseLink, termsFor, } from '@kuiralabs/midnight-account-chain/owner'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; import type { GrantLimits as RequestedLimits } from './request.ts'; /** What a command gives: its result, and the lines a person reads. */ diff --git a/src/lib/grant/prepare.ts b/src/lib/grant/prepare.ts index 7ec1fcd9..168d234f 100644 --- a/src/lib/grant/prepare.ts +++ b/src/lib/grant/prepare.ts @@ -3,10 +3,7 @@ // account yet, and for a command that starts one, that its wallet exists. The CLI runs it first; the MCP server runs it before it issues a // confirmation token. -import { type ParsedArgs, getFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { type PayingTarget, resolvePayingTarget } from '@kuiralabs/midnight-cli-core/lib/payer'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import { type ParsedArgs, getFlag, UsageError, type PayingTarget, resolvePayingTarget, type Host } from '@kuiralabs/midnight-cli-core'; import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '../wallet-config.ts'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; diff --git a/src/lib/grant/protect-account.ts b/src/lib/grant/protect-account.ts index cbe2f285..a6b32595 100644 --- a/src/lib/grant/protect-account.ts +++ b/src/lib/grant/protect-account.ts @@ -13,7 +13,7 @@ // never opened under the public password its private state has left. import * as fs from 'node:fs'; -import type { HostEngines } from '@kuiralabs/midnight-cli-core/lib/engine'; +import type { HostEngines } from '@kuiralabs/midnight-cli-core'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; import { changePrivateStatePassword, directoryOwnerStore, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; diff --git a/src/lib/grant/request.ts b/src/lib/grant/request.ts index 21a60eef..34692287 100644 --- a/src/lib/grant/request.ts +++ b/src/lib/grant/request.ts @@ -3,9 +3,7 @@ // server before it issues a confirmation token. import { parseDeviceCode } from './device-code.ts'; -import { type ParsedArgs, getFlag, hasFlag } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { parseAmount } from '@kuiralabs/midnight-cli-core/lib/amount'; +import { type ParsedArgs, getFlag, hasFlag, UsageError, parseAmount } from '@kuiralabs/midnight-cli-core'; export const GRANT_SUBCOMMANDS = ['deploy', 'deposit', 'status', 'list', 'issue', 'revoke', 'revoke-all', 'export', 'import', 'device'] as const; diff --git a/src/lib/grant/sealed-account.ts b/src/lib/grant/sealed-account.ts index e93ac505..79944821 100644 --- a/src/lib/grant/sealed-account.ts +++ b/src/lib/grant/sealed-account.ts @@ -29,11 +29,8 @@ import { freshOwnerDevice, ownerDeviceFromSecret, } from '@kuiralabs/midnight-account-chain/owner'; -import { FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { FILE_MODE, UsageError, FileExistsError, readJsonIfPresent, writeJsonDurably, type KeyedSecret, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '@kuiralabs/midnight-cli-core'; import { deviceCodeOf, joinCodeOf } from './device-code.ts'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { FileExistsError, readJsonIfPresent, writeJsonDurably } from '@kuiralabs/midnight-cli-core/lib/durable-file'; -import { type KeyedSecret, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '@kuiralabs/midnight-cli-core/lib/keystore'; const ACCOUNT_KEY_FILE = 'account-key.json'; // The data key while a plain-text account is being sealed: the account is diff --git a/src/lib/heap-guard.ts b/src/lib/heap-guard.ts index 345da559..6d0662f2 100644 --- a/src/lib/heap-guard.ts +++ b/src/lib/heap-guard.ts @@ -18,11 +18,7 @@ import v8 from 'node:v8'; import os from 'node:os'; import { spawn } from 'node:child_process'; -import { - SYNC_HEAP_TARGET_MB, - SYNC_HEAP_RAM_FRACTION, - SYNC_HEAP_MIN_GAIN_MB, -} from '@kuiralabs/midnight-cli-core/lib/constants'; +import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB } from '@kuiralabs/midnight-cli-core'; /** Set on the re-exec'd child so it doesn't recurse. */ const BUMP_ENV = 'MN_HEAP_BUMPED'; diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 2a5415be..b16638b6 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -6,8 +6,8 @@ // server's tools, the agent manual and skills, and the shell's and the MCP // server's classification of an error by its code. -import { getValidNetworkNames } from '@kuiralabs/midnight-cli-core/lib/network'; -import { createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { getValidNetworkNames, createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core'; +import { configDefinition, coreGuidance, coreCodes } from '@kuiralabs/midnight-cli-core/commands'; import { walletDefinition } from '../commands/wallet.definition.ts'; import { generateDefinition } from '../commands/generate.definition.ts'; import { infoDefinition } from '../commands/info.definition.ts'; @@ -18,7 +18,6 @@ import { inspectCostDefinition } from '../commands/inspect-cost.definition.ts'; import { airdropDefinition } from '../commands/airdrop.definition.ts'; import { transferDefinition } from '../commands/transfer.definition.ts'; import { dustDefinition } from '../commands/dust.definition.ts'; -import { configDefinition } from '@kuiralabs/midnight-cli-core/commands/config.definition'; import { cacheDefinition } from '../commands/cache.definition.ts'; import { serveDefinition } from '../commands/serve.definition.ts'; import { testDefinition } from '../commands/test.definition.ts'; @@ -27,20 +26,15 @@ import { contractDefinition } from '../commands/contract.definition.ts'; import { grantDefinition } from '../commands/grant.definition.ts'; import { swapDefinition } from '../commands/swap.definition.ts'; import { localnetDefinition } from '../commands/localnet.definition.ts'; -import { statusDefinition } from '@kuiralabs/midnight-chain/commands/status.definition'; -import { txDefinition } from '@kuiralabs/midnight-chain/commands/tx.definition'; +import { statusDefinition, txDefinition, chainGuidance, chainCodes } from '@kuiralabs/midnight-chain/commands'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; -import { coreGuidance } from '@kuiralabs/midnight-cli-core/commands/core.guidance'; -import { chainGuidance } from '@kuiralabs/midnight-chain/commands/chain.guidance'; import { walletGuidance } from '../commands/wallet.guidance.ts'; import { contractGuidance } from '../commands/contract.guidance.ts'; import { connectGuidance } from '../commands/connect.guidance.ts'; import { devGuidance } from '../commands/dev.guidance.ts'; import { grantGuidance } from '../commands/grant.guidance.ts'; import { swapGuidance } from '../commands/swap.guidance.ts'; -import { coreCodes } from '@kuiralabs/midnight-cli-core/commands/core.codes'; -import { chainCodes } from '@kuiralabs/midnight-chain/commands/chain.codes'; import { walletCodes } from '../commands/wallet.codes.ts'; import { contractCodes } from '../commands/contract.codes.ts'; import { devCodes } from '../commands/dev.codes.ts'; diff --git a/src/lib/installed-engines.ts b/src/lib/installed-engines.ts index 5cf43812..01570dae 100644 --- a/src/lib/installed-engines.ts +++ b/src/lib/installed-engines.ts @@ -2,8 +2,7 @@ // makes its engine with (its engine loader). Each loads its SDK, so each is // imported only when a call needs it. -import type { Engine, SdkSet } from '@kuiralabs/midnight-cli-core/lib/engine'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; +import type { Engine, SdkSet, Host } from '@kuiralabs/midnight-cli-core'; /** The engine for an SDK set, as this build ships it, made for `host`. */ export async function loadInstalledEngine(set: SdkSet, host: Host): Promise { diff --git a/src/lib/localnet.ts b/src/lib/localnet.ts index 9e1ec35c..1f70b5bf 100644 --- a/src/lib/localnet.ts +++ b/src/lib/localnet.ts @@ -5,10 +5,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; -import { LOCALNET_DIR_NAME, DIR_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { CancelledError, CANCELLED_MESSAGE, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { ExecRunner } from '@kuiralabs/midnight-cli-core/lib/exec-program'; -import { sleep } from '@kuiralabs/midnight-cli-core/lib/sleep'; +import { LOCALNET_DIR_NAME, DIR_MODE, CancelledError, CANCELLED_MESSAGE, throwIfCancelled, type ExecRunner, sleep } from '@kuiralabs/midnight-cli-core'; // Version tag — bump when compose content changes so stale files get overwritten export const COMPOSE_VERSION = '3.0.6'; diff --git a/src/lib/mcp/known-params.ts b/src/lib/mcp/known-params.ts index b7cffe5c..0529ee1f 100644 --- a/src/lib/mcp/known-params.ts +++ b/src/lib/mcp/known-params.ts @@ -2,7 +2,7 @@ // parameter outside the tool's schema is refused, and so is one whose value // is not the type its schema says. -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; /** A parameter's schema as the server checks it. */ interface ParamCheck { diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index bf15f6d8..0675fbbd 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -7,18 +7,7 @@ import { type CommandRun, captureCommand } from '../run-command.ts'; import { listedNames } from '../code-tables.ts'; -import { getEndpointOverridesForNetwork, loadCliConfig } from '@kuiralabs/midnight-cli-core/lib/cli-config'; -import { resolveNetworkName } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { - type CommandRegistry, - type RegisteredTool, - type ToolAnnotations, - type ToolInputSchema, - commandOwnCodes, - confirmationText, - declaredSets, - toolArgv, -} from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { getEndpointOverridesForNetwork, loadCliConfig, resolveNetworkName, type CommandRegistry, type RegisteredTool, type ToolAnnotations, type ToolInputSchema, commandOwnCodes, confirmationText, declaredSets, toolArgv } from '@kuiralabs/midnight-cli-core'; /** A tool as tools/list sends it. */ export interface ListedTool { diff --git a/src/lib/mcp/server-advice.ts b/src/lib/mcp/server-advice.ts index 71de0c61..21e547bd 100644 --- a/src/lib/mcp/server-advice.ts +++ b/src/lib/mcp/server-advice.ts @@ -2,8 +2,7 @@ // runs: a server loads one set's engine, so a call on a network of the other // set is told to use a server of its own. -import { OtherSdkSetError } from '@kuiralabs/midnight-cli-core/lib/engine'; -import { networksOnSdkSet } from '@kuiralabs/midnight-cli-core/lib/network'; +import { OtherSdkSetError, networksOnSdkSet } from '@kuiralabs/midnight-cli-core'; /** The server runs one SDK set: a call on the other set's network (by the config under the state root `root`) is told to use a server of its own. */ export function withServerAdvice(error: Error, root: string): Error { diff --git a/src/lib/mcp/skills.ts b/src/lib/mcp/skills.ts index aaab7df0..f067cec7 100644 --- a/src/lib/mcp/skills.ts +++ b/src/lib/mcp/skills.ts @@ -6,8 +6,7 @@ // at each resources/read; scripts/write-skill-docs.ts writes the same text to // docs/SKILL-CORE.md and docs/SKILL.md, the copies the README links to. -import { assembleGuidance, sectionsWithAdded, type GuidancePiece } from '@kuiralabs/midnight-cli-core/lib/agent-guidance'; -import { declaredCodeSets, type CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import { assembleGuidance, sectionsWithAdded, type GuidancePiece, declaredCodeSets, type CommandRegistry } from '@kuiralabs/midnight-cli-core'; /** skill/core's sections, in order. */ export const SKILL_CORE_SECTIONS = ['title', 'intent-routing', 'safety-rules', 'when-to-fetch'] as const; diff --git a/src/lib/output-redaction.ts b/src/lib/output-redaction.ts index 9041bf95..70ccd99f 100644 --- a/src/lib/output-redaction.ts +++ b/src/lib/output-redaction.ts @@ -8,7 +8,7 @@ // holds a project id. (A wrapper that dropped writes or their callbacks once // made libraries waiting on a write hang; this one drops nothing.) -import { mayHoldProjectId, redactProjectId } from '@kuiralabs/midnight-cli-core/lib/blockfrost'; +import { mayHoldProjectId, redactProjectId } from '@kuiralabs/midnight-cli-core'; type Write = typeof process.stdout.write; diff --git a/src/lib/passphrase.ts b/src/lib/passphrase.ts index 20baac96..4feab6ae 100644 --- a/src/lib/passphrase.ts +++ b/src/lib/passphrase.ts @@ -8,12 +8,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; -import { DIR_MODE, FILE_MODE } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { throwIfCancelled, UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import { openSecret, sealSecret } from '@kuiralabs/midnight-cli-core/lib/keystore'; -import type { Prompter } from '@kuiralabs/midnight-cli-core/lib/prompter'; -import { defineHostSlot, type Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { DIR_MODE, FILE_MODE, throwIfCancelled, UsageError, openSecret, sealSecret, type Prompter, defineHostSlot, type Host, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; /** The variable a non-interactive run sets the passphrase in (named in settings.ts). */ export { PASSPHRASE_ENV }; diff --git a/src/lib/readme-commands.ts b/src/lib/readme-commands.ts index 2f294e23..41fb2f2b 100644 --- a/src/lib/readme-commands.ts +++ b/src/lib/readme-commands.ts @@ -3,7 +3,7 @@ // description. scripts/write-readme-commands.ts writes it between the // README's markers; a test fails when the README differs. -import type { CommandRegistry } from '@kuiralabs/midnight-cli-core/lib/command-definition'; +import type { CommandRegistry } from '@kuiralabs/midnight-cli-core'; /** The markers around the generated table in README.md. */ export const README_COMMANDS_START = ''; diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts index 78750b60..9db105c4 100644 --- a/src/lib/run-command.ts +++ b/src/lib/run-command.ts @@ -1,11 +1,7 @@ // Run a command handler and capture its JSON output // Used by the MCP server to invoke CLI commands programmatically -import { type ParsedArgs, MINIMAL_FLAG } from '@kuiralabs/midnight-cli-core/lib/argv'; -import type { Payer } from '@kuiralabs/midnight-cli-core/lib/payer'; -import { createCallContext, runHandler, type CommandHandler, type CallOutput } from '@kuiralabs/midnight-cli-core/lib/call-context'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import { CommandFailedError } from '@kuiralabs/midnight-cli-core/lib/errors'; +import { type ParsedArgs, MINIMAL_FLAG, type Payer, createCallContext, runHandler, type CommandHandler, type CallOutput, type Host, CommandFailedError } from '@kuiralabs/midnight-cli-core'; export interface CommandRun { /** Cancels the command; a call already cancelled never starts. None: it runs to the end. */ diff --git a/src/lib/sdk-noise.ts b/src/lib/sdk-noise.ts index 552e369e..174fbda4 100644 --- a/src/lib/sdk-noise.ts +++ b/src/lib/sdk-noise.ts @@ -25,7 +25,7 @@ // one call listening, or to none. import { AsyncLocalStorage } from 'node:async_hooks'; -import { createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; +import { createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls } from '@kuiralabs/midnight-cli-core'; let installed: SdkWarningCalls | null = null; diff --git a/src/lib/seed-resolver.ts b/src/lib/seed-resolver.ts index b017c523..5742bb24 100644 --- a/src/lib/seed-resolver.ts +++ b/src/lib/seed-resolver.ts @@ -3,10 +3,7 @@ // `MN_SEED` / `--wallet` separately, which is how `balance` drifted and never // learned `MN_SEED`. Centralizing it keeps the precedence identical everywhere. -import { getFlag, type ParsedArgs } from '@kuiralabs/midnight-cli-core/lib/argv'; -import { UsageError } from '@kuiralabs/midnight-cli-core/lib/errors'; -import type { Host } from '@kuiralabs/midnight-cli-core/lib/host'; -import type { Settings } from '@kuiralabs/midnight-cli-core/lib/settings'; +import { getFlag, type ParsedArgs, UsageError, type Host, type Settings } from '@kuiralabs/midnight-cli-core'; import { resolveWalletPath, unlockWallet, type UnlockHost, type WalletConfig } from './wallet-config.ts'; export interface ResolvedSeed { diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index 5f5c169a..cad7c50a 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -5,14 +5,8 @@ import { Socket } from 'node:net'; import { resolveWalletPath, unlockWallet, walletAddress, type UnlockHost } from './wallet-config.ts'; -import { resolveNetwork } from '@kuiralabs/midnight-cli-core/lib/resolve-network'; -import { applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; -import { sdkSetOf, type DAppConnectorCallbacks, type OpenedConnector } from '@kuiralabs/midnight-cli-core/lib/engine'; +import { resolveNetwork, applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName, sdkSetOf, type DAppConnectorCallbacks, type OpenedConnector, DEFAULT_SERVE_PORT, type CallSdkWarnings, shieldedSyncEnabled, CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; -import { DEFAULT_SERVE_PORT } from '@kuiralabs/midnight-cli-core/lib/constants'; -import type { CallSdkWarnings } from '@kuiralabs/midnight-cli-core/lib/sdk-warnings'; -import { shieldedSyncEnabled } from '@kuiralabs/midnight-cli-core/lib/shielded-policy'; -import { CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core/lib/errors'; /** A running mn serve, and how to stop it. */ export interface ServeHandle { @@ -221,7 +215,7 @@ export async function startServeOrReuse(options: ServeManagerOptions): Promise {} } as const; diff --git a/src/__tests__/helpers/connector-suite.ts b/test-support/connector-suite.ts similarity index 98% rename from src/__tests__/helpers/connector-suite.ts rename to test-support/connector-suite.ts index 5ae5bbac..fa99f60c 100644 --- a/src/__tests__/helpers/connector-suite.ts +++ b/test-support/connector-suite.ts @@ -17,19 +17,11 @@ import { Effect } from 'effect'; import { HISTORY, NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub, type BundleOverrides, type StubConnector, type StubEngine } from './connector-stub.ts'; import { startLocalIndexer, type LocalIndexer } from './local-indexer.ts'; import { ledgerTx, type Ledger } from './ledger-tx.ts'; -import { SWAP_OFFER_HEX, OFFER_GIVE } from '../fixtures/swap-offer.ts'; -import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; -import { OfferCoinsInUseError, type OpenOffer } from '@kuiralabs/midnight-cli-core/lib/open-offers'; +import { SWAP_OFFER_HEX, OFFER_GIVE } from './fixtures/swap-offer.ts'; +import { OfferCoinsInUseError, type OpenOffer, type RpcHandlerContext, classifyError, type NetworkName } from '@kuiralabs/midnight-cli-core'; +import { NotAnOfferError, signedMessageBytes, PROOF_TIMEOUT_MS, toEngineError, withDustShortfall, type FeeLimits, type ApprovalOptions } from '@kuiralabs/midnight-cli-core/engine'; import type { SignatureVerifyingKey } from '@midnightntwrk/ledger-v9'; -import { signedMessageBytes } from '@kuiralabs/midnight-cli-core/lib/sign-data'; -import type { RpcHandlerContext } from '@kuiralabs/midnight-cli-core/lib/connector-api'; -import { PROOF_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { toEngineError, withDustShortfall } from '@kuiralabs/midnight-cli-core/lib/sdk-errors'; -import { classifyError } from '@kuiralabs/midnight-cli-core/lib/exit-codes'; -import { installedCommands } from '../../lib/installed-commands.ts'; -import type { FeeLimits } from '@kuiralabs/midnight-cli-core/lib/fee-limits'; -import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/lib/approval'; -import type { NetworkName } from '@kuiralabs/midnight-cli-core/lib/network'; +import { CORE_CODES } from './core-codes.ts'; /** What the suite takes from an engine. */ export interface ConnectorEngine extends StubEngine { @@ -1133,7 +1125,7 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toContain('The wallet has no Dust available that covers this transaction\'s fee (No dust tokens found in the wallet state)'); expect(err.message).toContain('no balanced transaction is holding any back on this server'); expect(err.message).not.toContain('Retry once they settle'); - expect(classifyError(toEngineError(err) as Error, installedCommands).errorCode).toBe('DUST_REQUIRED'); + expect(classifyError(toEngineError(err) as Error, CORE_CODES).errorCode).toBe('DUST_REQUIRED'); expect(err.mnCode).toBe('DUST_REQUIRED'); expect(callCount).toBe(10); // DUST_RETRY_ATTEMPTS = 10 vi.useRealTimers(); @@ -1184,7 +1176,7 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(err.message).toBe( "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00. " + 'Its registered NIGHT generates the rest in about 4 minutes: retry then, or register more NIGHT to get there sooner.'); - expect(classifyError(toEngineError(err) as Error, installedCommands).errorCode).toBe('DUST_REQUIRED'); + expect(classifyError(toEngineError(err) as Error, CORE_CODES).errorCode).toBe('DUST_REQUIRED'); expect(err.mnCode).toBe('DUST_REQUIRED'); }); @@ -1428,7 +1420,7 @@ export function connectorSuite(engine: ConnectorEngine): void { const err: any = await failure; expect(err.message).toContain('No Dust is free to pay the fee ([Wallet.InsufficientFunds] Insufficient Funds: could not balance dust)'); expect(err.message).toContain('1 balanced transaction(s) are waiting to be submitted on this server. Retry once they settle.'); - expect(classifyError(toEngineError(err) as Error, installedCommands).errorCode).toBe('DUST_REQUIRED'); + expect(classifyError(toEngineError(err) as Error, CORE_CODES).errorCode).toBe('DUST_REQUIRED'); expect(err.mnCode).toBe('DUST_REQUIRED'); } finally { process.stderr.write = stderrWrite; diff --git a/test-support/core-codes.ts b/test-support/core-codes.ts new file mode 100644 index 00000000..f38923f8 --- /dev/null +++ b/test-support/core-codes.ts @@ -0,0 +1,14 @@ +// Codes as a registry an error is classified through: what a test of a +// package below the shell classifies with, where the shell would use every +// installed package's codes. CORE_CODES is core's; a package adds its own. + +import type { CodeDefinition, CodeRegistry } from '@kuiralabs/midnight-cli-core'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; + +/** A registry of the codes `lists` define. */ +export function codeRegistry(...lists: readonly (readonly CodeDefinition[])[]): CodeRegistry { + const codes = lists.flat(); + return { code: (code) => codes.find((definition) => definition.code === code) }; +} + +export const CORE_CODES = codeRegistry(coreCodes); diff --git a/src/__tests__/fixtures/ledger9-parameters.ts b/test-support/fixtures/ledger9-parameters.ts similarity index 100% rename from src/__tests__/fixtures/ledger9-parameters.ts rename to test-support/fixtures/ledger9-parameters.ts diff --git a/src/__tests__/fixtures/swap-offer.ts b/test-support/fixtures/swap-offer.ts similarity index 100% rename from src/__tests__/fixtures/swap-offer.ts rename to test-support/fixtures/swap-offer.ts diff --git a/test-support/fixtures/tx-status.ts b/test-support/fixtures/tx-status.ts new file mode 100644 index 00000000..f7231bac --- /dev/null +++ b/test-support/fixtures/tx-status.ts @@ -0,0 +1,17 @@ +// A transaction as stagenet's indexer described it on 2026-11-03 (the City's +// first swap; a 4.4 indexer, 4.3's transaction fields the same): what the +// chain's transaction-status tests and mn tx status's are answered with. + +export const IDENTIFIER = '00408d0e7f195ae3a57b908f10513f2200386533960fcdc3fb152076dd84559086'; +export const HASH = '1dc5749135a08df5fb95560e1ef1ff3fea6febdd8b263dbd2b371e2f9cb178f8'; +export const BLOCK = { height: 1146592, hash: 'd3d3af4c0a35110377d12c1296274603fa75583b274191c8b7063bc913db2f75', timestamp: 1793696118000 }; + +export const answer = (transactions: unknown[]) => JSON.stringify({ data: { transactions } }); +export const regular = (status: string, segments: unknown = null) => ({ + __typename: 'RegularTransaction', + hash: HASH, + block: BLOCK, + identifiers: [IDENTIFIER], + fee: '845170285714286', + transactionResult: { status, segments }, +}); diff --git a/src/__tests__/fixtures/zswap-events-localnet.json b/test-support/fixtures/zswap-events-localnet.json similarity index 100% rename from src/__tests__/fixtures/zswap-events-localnet.json rename to test-support/fixtures/zswap-events-localnet.json diff --git a/src/__tests__/helpers/ledger-tx.ts b/test-support/ledger-tx.ts similarity index 100% rename from src/__tests__/helpers/ledger-tx.ts rename to test-support/ledger-tx.ts diff --git a/src/__tests__/helpers/local-indexer.ts b/test-support/local-indexer.ts similarity index 95% rename from src/__tests__/helpers/local-indexer.ts rename to test-support/local-indexer.ts index 9cf31516..59f48b77 100644 --- a/src/__tests__/helpers/local-indexer.ts +++ b/test-support/local-indexer.ts @@ -37,7 +37,7 @@ export async function startLocalIndexer(respond: (request: { query: string; vari * and ledger parameters), and the endpoint flags that point a command at it. */ export async function localIndexerFlags(): Promise<{ flags: string[]; close: () => Promise }> { - const { LEDGER9_PARAMETERS_HEX } = await import('../fixtures/ledger9-parameters.ts'); + const { LEDGER9_PARAMETERS_HEX } = await import('./fixtures/ledger9-parameters.ts'); const indexer = await startLocalIndexer(() => JSON.stringify({ data: { block: { height: 26919, protocolVersion: 2001000, ledgerParameters: LEDGER9_PARAMETERS_HEX } } })); const ws = indexer.url.replace(/^http:/, 'ws:') + '/ws'; diff --git a/src/__tests__/helpers/offer-reader-suite.ts b/test-support/offer-reader-suite.ts similarity index 92% rename from src/__tests__/helpers/offer-reader-suite.ts rename to test-support/offer-reader-suite.ts index bb8af395..6bf76fa6 100644 --- a/src/__tests__/helpers/offer-reader-suite.ts +++ b/test-support/offer-reader-suite.ts @@ -5,9 +5,10 @@ import { createHash } from 'node:crypto'; import { describe, it, expect, beforeAll } from 'vitest'; -import { NotAnOfferError, type OfferContents } from '@kuiralabs/midnight-cli-core/lib/swap-offer'; +import type { OfferContents } from '@kuiralabs/midnight-cli-core'; +import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/engine'; import { ledgerTx, type Ledger } from './ledger-tx.ts'; -import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../fixtures/swap-offer.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from './fixtures/swap-offer.ts'; export interface OfferReaderEngine { set: string; diff --git a/test-support/rc-engine.ts b/test-support/rc-engine.ts new file mode 100644 index 00000000..94d98a69 --- /dev/null +++ b/test-support/rc-engine.ts @@ -0,0 +1,9 @@ +// An rc engine made through its entry point, for tests outside the engine: +// its keys and addresses (what a wallet's addresses are compared with; every +// engine derives the same ones), its ledger reads and its contract scripts. + +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { testHost } from './test-host.ts'; + +export const rcEngine = createRcEngine(testHost()); +export const rcKeys = rcEngine.keys; diff --git a/src/__tests__/helpers/shielded-direct-suite.ts b/test-support/shielded-direct-suite.ts similarity index 99% rename from src/__tests__/helpers/shielded-direct-suite.ts rename to test-support/shielded-direct-suite.ts index c9a3ae63..8e1d83a8 100644 --- a/src/__tests__/helpers/shielded-direct-suite.ts +++ b/test-support/shielded-direct-suite.ts @@ -5,7 +5,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { WebSocketServer, type WebSocket as WsSocket } from 'ws'; import type { AddressInfo } from 'node:net'; -import zswapEvents from '../fixtures/zswap-events-localnet.json'; +import zswapEvents from './fixtures/zswap-events-localnet.json'; /** An engine's reader, and a wallet's secret keys made with the engine's own ledger. */ export interface ShieldedDirectEngine { diff --git a/src/__tests__/helpers/stand-in-indexer.ts b/test-support/stand-in-indexer.ts similarity index 98% rename from src/__tests__/helpers/stand-in-indexer.ts rename to test-support/stand-in-indexer.ts index b00bb413..9e25f2a5 100644 --- a/src/__tests__/helpers/stand-in-indexer.ts +++ b/test-support/stand-in-indexer.ts @@ -15,7 +15,7 @@ import { createServer, type Server, type Socket } from 'node:net'; import { createServer as createHttpServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { WebSocketServer, type WebSocket } from 'ws'; -import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core/lib/constants'; +import { NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core'; /** One subscription the stand-in indexer took. */ export interface Subscription { diff --git a/src/__tests__/helpers/test-host.ts b/test-support/test-host.ts similarity index 68% rename from src/__tests__/helpers/test-host.ts rename to test-support/test-host.ts index 5af6b6b4..c8c01f3d 100644 --- a/src/__tests__/helpers/test-host.ts +++ b/test-support/test-host.ts @@ -6,10 +6,8 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; -import { createHost, type Host, type HostOptions } from '@kuiralabs/midnight-cli-core/lib/host'; -import { settingsFromEnvironment } from '@kuiralabs/midnight-cli-core/lib/settings'; -import { MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core/lib/constants'; -import { loadInstalledEngine } from '../../lib/installed-engines.ts'; +import { createHost, type Host, type HostOptions, settingsFromEnvironment, MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core'; +import { loadInstalledEngine } from '../src/lib/installed-engines.ts'; export function testHost(overrides: HostOptions = {}): Host { return createHost({ diff --git a/tsconfig.json b/tsconfig.json index a7f80773..0a04d83b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts"], + "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts"], "exclude": ["node_modules"] } diff --git a/vitest.live.config.ts b/vitest.live.config.ts index 495bb623..c3480240 100644 --- a/vitest.live.config.ts +++ b/vitest.live.config.ts @@ -10,7 +10,7 @@ export default defineConfig({ ssr: base.ssr, test: { ...base.test, - include: ['src/**/*.live.test.ts'], + include: ['src/**/*.live.test.ts', 'packages/*/src/**/*.live.test.ts'], exclude: [...configDefaults.exclude, '**/.claude/**'], }, }); From efe3075a6dc1a0afcaf9d56771d0416f5d156cde Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 18:28:47 -0800 Subject: [PATCH 71/88] The wallet package, with swap (3F, 5 of 10) @kuiralabs/midnight-wallet holds the wallet commands (wallet, generate, address, genesis-address, info, balance, transfer, airdrop, dust, cache) and swap, their codes and guidance, and the wallet libraries: passphrase, seeds, wallet files, the 3E library functions and swap offers. Its entry points: "." (the library API, 99 names) and "./commands" (the definitions, codes, guidance and showPaidStep). mn's registry keeps its entries and order, so help and the manuals are unchanged. Dependencies, as approved (Y59): the wallet package declares core, chain and @scure/bip39 (moved from mn's root, same range); mn's root declares the wallet package instead. The lockfile keeps every other entry's resolution and integrity. wallet remove's confirmation imports readline statically (a require worked only inside the bundle). Suite 2916, beta 184; snapshot unchanged; fresh install (one copy, both entry points load, a deep path refused); scratch chain swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads. --- .github/workflows/release-sidecar.yml | 4 +- docs/JSON_CONTRACT.md | 4 +- package-lock.json | 22 +- package.json | 7 +- packages/wallet/api-report.md | 383 ++++++++++++++++++ packages/wallet/package.json | 42 ++ .../src}/__tests__/cache-local-stacks.test.ts | 0 .../src}/__tests__/host-engines.test.ts | 4 +- .../src}/__tests__/multi-wallet.test.ts | 6 +- .../wallet/src}/__tests__/passphrase.test.ts | 2 +- .../src}/__tests__/sealed-wallet.test.ts | 6 +- .../src}/__tests__/seed-resolver.test.ts | 5 +- .../wallet/src}/__tests__/settings.test.ts | 0 .../wallet/src}/__tests__/swap-lib.test.ts | 8 +- .../src}/__tests__/swap-request.test.ts | 6 +- .../wallet/src}/__tests__/sync-eta.test.ts | 0 .../src}/__tests__/transfer-request.test.ts | 21 +- .../src}/__tests__/wallet-airdrop-lib.test.ts | 8 +- .../src}/__tests__/wallet-balance-lib.test.ts | 8 +- .../src}/__tests__/wallet-config.test.ts | 8 +- .../src}/__tests__/wallet-create.test.ts | 6 +- .../src}/__tests__/wallet-dust-lib.test.ts | 8 +- .../__tests__/wallet-transfer-lib.test.ts | 8 +- packages/wallet/src/commands.ts | 22 + .../src}/commands/address.definition.ts | 0 .../wallet/src}/commands/address.ts | 0 .../src}/commands/airdrop.definition.ts | 0 .../wallet/src}/commands/airdrop.ts | 0 .../src}/commands/balance.definition.ts | 0 .../wallet/src}/commands/balance.ts | 0 .../wallet/src}/commands/cache.definition.ts | 0 .../wallet/src}/commands/cache.ts | 0 .../wallet/src}/commands/dust.definition.ts | 4 +- {src => packages/wallet/src}/commands/dust.ts | 0 .../src}/commands/generate.definition.ts | 0 .../wallet/src}/commands/generate.ts | 0 .../commands/genesis-address.definition.ts | 0 .../wallet/src}/commands/genesis-address.ts | 0 .../wallet/src}/commands/info.definition.ts | 0 {src => packages/wallet/src}/commands/info.ts | 0 .../wallet/src}/commands/swap.definition.ts | 0 .../wallet/src}/commands/swap.guidance.ts | 0 {src => packages/wallet/src}/commands/swap.ts | 0 .../src}/commands/transfer.definition.ts | 0 .../wallet/src}/commands/transfer.ts | 0 .../wallet/src}/commands/wallet.codes.ts | 0 .../wallet/src}/commands/wallet.definition.ts | 0 .../wallet/src}/commands/wallet.guidance.ts | 0 .../wallet/src}/commands/wallet.ts | 2 +- packages/wallet/src/index.ts | 56 +++ .../wallet/src}/lib/chain-caches.ts | 0 .../wallet/src}/lib/passphrase.ts | 0 .../wallet/src}/lib/seed-resolver.ts | 0 .../wallet/src}/lib/swap/cancel.ts | 0 .../wallet/src}/lib/swap/inspect.ts | 0 {src => packages/wallet/src}/lib/swap/list.ts | 0 {src => packages/wallet/src}/lib/swap/make.ts | 0 .../wallet/src}/lib/swap/offers.ts | 0 .../wallet/src}/lib/swap/request.ts | 0 .../wallet/src}/lib/swap/swap-session.ts | 0 {src => packages/wallet/src}/lib/swap/take.ts | 0 {src => packages/wallet/src}/lib/sync-eta.ts | 0 .../wallet/src}/lib/transfer-request.ts | 0 .../wallet/src}/lib/wallet-can-pay.ts | 0 .../wallet/src}/lib/wallet-config.ts | 0 .../wallet/src}/lib/wallet-create.ts | 0 .../wallet/src}/lib/wallet-paths.ts | 0 .../wallet/src}/lib/wallet-protector.ts | 0 .../wallet/src}/lib/wallet/airdrop.ts | 0 .../wallet/src}/lib/wallet/balance.ts | 0 .../wallet/src}/lib/wallet/dust.ts | 0 .../wallet/src}/lib/wallet/paid-call.ts | 0 .../wallet/src}/lib/wallet/submit-steps.ts | 0 .../wallet/src}/lib/wallet/transfer.ts | 0 .../wallet/src}/lib/wallet/wallet-call.ts | 2 +- {src => packages/wallet/src}/ui/receipt.ts | 0 packages/wallet/tsconfig.build.json | 31 ++ scripts/api-report.mjs | 2 +- scripts/check-layering.mjs | 12 +- scripts/fresh-install-check.mjs | 1 + src/__tests__/account-backup.test.ts | 6 +- src/__tests__/address-command.test.ts | 5 +- src/__tests__/agent-guidance.test.ts | 6 +- src/__tests__/airdrop-command.test.ts | 7 +- src/__tests__/balance-command.live.test.ts | 7 +- src/__tests__/balance-command.test.ts | 7 +- src/__tests__/chain-reset-clearing.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 20 +- src/__tests__/command-registry.test.ts | 2 +- src/__tests__/config-command.test.ts | 2 +- src/__tests__/contract-deploy.test.ts | 2 +- src/__tests__/declared-codes.test.ts | 2 +- src/__tests__/dust-command.test.ts | 7 +- src/__tests__/entry-points.test.ts | 1 + src/__tests__/error-code-parity.test.ts | 24 +- src/__tests__/exit-codes.test.ts | 2 +- src/__tests__/generate-command.test.ts | 12 +- src/__tests__/genesis-address-command.test.ts | 5 +- src/__tests__/grant-account.test.ts | 6 +- src/__tests__/handler-library-calls.test.ts | 10 +- src/__tests__/host-paths.test.ts | 7 +- src/__tests__/host-slots.test.ts | 9 +- src/__tests__/info-command.test.ts | 7 +- src/__tests__/json-output.test.ts | 15 +- src/__tests__/network-cancellation.test.ts | 5 +- src/__tests__/notices.test.ts | 4 +- src/__tests__/package-metadata.test.ts | 4 +- src/__tests__/payer.test.ts | 4 +- src/__tests__/protect-account.test.ts | 6 +- src/__tests__/provision-wallets.test.ts | 2 +- src/__tests__/run-command.test.ts | 13 +- src/__tests__/serve-manager.test.ts | 4 +- src/__tests__/state-root.test.ts | 5 +- src/__tests__/swap-command.test.ts | 5 +- src/__tests__/transfer-command.test.ts | 7 +- src/__tests__/two-hosts.test.ts | 2 +- src/__tests__/verbose-per-call.test.ts | 5 +- src/__tests__/wallet-protect.test.ts | 15 +- src/commands/contract.definition.ts | 4 +- src/commands/contract.ts | 2 +- src/commands/dev.definition.ts | 2 +- src/commands/dev.ts | 2 +- src/commands/grant.definition.ts | 4 +- src/commands/grant.ts | 8 +- src/commands/localnet.ts | 2 +- src/commands/serve.definition.ts | 2 +- src/commands/serve.ts | 2 +- src/commands/test.definition.ts | 2 +- src/lib/command-dispatch.ts | 2 +- src/lib/contract/call.ts | 3 +- src/lib/contract/deploy.ts | 3 +- src/lib/contract/state.ts | 2 +- src/lib/dev/provision-wallets.ts | 4 +- src/lib/grant/account-protector.ts | 2 +- src/lib/grant/account.ts | 3 +- src/lib/grant/prepare.ts | 2 +- src/lib/installed-commands.ts | 15 +- src/lib/serve-manager.ts | 2 +- src/lib/serve-payer.ts | 2 +- src/lib/test/prep-runner.ts | 2 +- src/lib/test/types.ts | 2 +- src/wallet.ts | 2 +- .../helpers => test-support}/plain-wallet.ts | 0 .../helpers => test-support}/state-root-in.ts | 0 test-support/test-host.ts | 3 + tsconfig.json | 2 +- 146 files changed, 808 insertions(+), 225 deletions(-) create mode 100644 packages/wallet/api-report.md create mode 100644 packages/wallet/package.json rename {src => packages/wallet/src}/__tests__/cache-local-stacks.test.ts (100%) rename {src => packages/wallet/src}/__tests__/host-engines.test.ts (96%) rename {src => packages/wallet/src}/__tests__/multi-wallet.test.ts (98%) rename {src => packages/wallet/src}/__tests__/passphrase.test.ts (98%) rename {src => packages/wallet/src}/__tests__/sealed-wallet.test.ts (96%) rename {src => packages/wallet/src}/__tests__/seed-resolver.test.ts (98%) rename {src => packages/wallet/src}/__tests__/settings.test.ts (100%) rename {src => packages/wallet/src}/__tests__/swap-lib.test.ts (97%) rename {src => packages/wallet/src}/__tests__/swap-request.test.ts (95%) rename {src => packages/wallet/src}/__tests__/sync-eta.test.ts (100%) rename {src => packages/wallet/src}/__tests__/transfer-request.test.ts (79%) rename {src => packages/wallet/src}/__tests__/wallet-airdrop-lib.test.ts (96%) rename {src => packages/wallet/src}/__tests__/wallet-balance-lib.test.ts (97%) rename {src => packages/wallet/src}/__tests__/wallet-config.test.ts (97%) rename {src => packages/wallet/src}/__tests__/wallet-create.test.ts (95%) rename {src => packages/wallet/src}/__tests__/wallet-dust-lib.test.ts (96%) rename {src => packages/wallet/src}/__tests__/wallet-transfer-lib.test.ts (96%) create mode 100644 packages/wallet/src/commands.ts rename {src => packages/wallet/src}/commands/address.definition.ts (100%) rename {src => packages/wallet/src}/commands/address.ts (100%) rename {src => packages/wallet/src}/commands/airdrop.definition.ts (100%) rename {src => packages/wallet/src}/commands/airdrop.ts (100%) rename {src => packages/wallet/src}/commands/balance.definition.ts (100%) rename {src => packages/wallet/src}/commands/balance.ts (100%) rename {src => packages/wallet/src}/commands/cache.definition.ts (100%) rename {src => packages/wallet/src}/commands/cache.ts (100%) rename {src => packages/wallet/src}/commands/dust.definition.ts (98%) rename {src => packages/wallet/src}/commands/dust.ts (100%) rename {src => packages/wallet/src}/commands/generate.definition.ts (100%) rename {src => packages/wallet/src}/commands/generate.ts (100%) rename {src => packages/wallet/src}/commands/genesis-address.definition.ts (100%) rename {src => packages/wallet/src}/commands/genesis-address.ts (100%) rename {src => packages/wallet/src}/commands/info.definition.ts (100%) rename {src => packages/wallet/src}/commands/info.ts (100%) rename {src => packages/wallet/src}/commands/swap.definition.ts (100%) rename {src => packages/wallet/src}/commands/swap.guidance.ts (100%) rename {src => packages/wallet/src}/commands/swap.ts (100%) rename {src => packages/wallet/src}/commands/transfer.definition.ts (100%) rename {src => packages/wallet/src}/commands/transfer.ts (100%) rename {src => packages/wallet/src}/commands/wallet.codes.ts (100%) rename {src => packages/wallet/src}/commands/wallet.definition.ts (100%) rename {src => packages/wallet/src}/commands/wallet.guidance.ts (100%) rename {src => packages/wallet/src}/commands/wallet.ts (99%) create mode 100644 packages/wallet/src/index.ts rename {src => packages/wallet/src}/lib/chain-caches.ts (100%) rename {src => packages/wallet/src}/lib/passphrase.ts (100%) rename {src => packages/wallet/src}/lib/seed-resolver.ts (100%) rename {src => packages/wallet/src}/lib/swap/cancel.ts (100%) rename {src => packages/wallet/src}/lib/swap/inspect.ts (100%) rename {src => packages/wallet/src}/lib/swap/list.ts (100%) rename {src => packages/wallet/src}/lib/swap/make.ts (100%) rename {src => packages/wallet/src}/lib/swap/offers.ts (100%) rename {src => packages/wallet/src}/lib/swap/request.ts (100%) rename {src => packages/wallet/src}/lib/swap/swap-session.ts (100%) rename {src => packages/wallet/src}/lib/swap/take.ts (100%) rename {src => packages/wallet/src}/lib/sync-eta.ts (100%) rename {src => packages/wallet/src}/lib/transfer-request.ts (100%) rename {src => packages/wallet/src}/lib/wallet-can-pay.ts (100%) rename {src => packages/wallet/src}/lib/wallet-config.ts (100%) rename {src => packages/wallet/src}/lib/wallet-create.ts (100%) rename {src => packages/wallet/src}/lib/wallet-paths.ts (100%) rename {src => packages/wallet/src}/lib/wallet-protector.ts (100%) rename {src => packages/wallet/src}/lib/wallet/airdrop.ts (100%) rename {src => packages/wallet/src}/lib/wallet/balance.ts (100%) rename {src => packages/wallet/src}/lib/wallet/dust.ts (100%) rename {src => packages/wallet/src}/lib/wallet/paid-call.ts (100%) rename {src => packages/wallet/src}/lib/wallet/submit-steps.ts (100%) rename {src => packages/wallet/src}/lib/wallet/transfer.ts (100%) rename {src => packages/wallet/src}/lib/wallet/wallet-call.ts (96%) rename {src => packages/wallet/src}/ui/receipt.ts (100%) create mode 100644 packages/wallet/tsconfig.build.json rename {src/__tests__/helpers => test-support}/plain-wallet.ts (100%) rename {src/__tests__/helpers => test-support}/state-root-in.ts (100%) diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index 55ac1637..96cbea54 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -159,7 +159,7 @@ jobs: fi done # mn depends on its workspace packages (core, chain, one engine per SDK - # set) at exact versions: each publishes first, unless that version is + # set, wallet) at exact versions: each publishes first, unless that version is # on npm already, under the same dist-tag as mn. - run: npm run build - name: Publish the workspace packages mn depends on @@ -168,7 +168,7 @@ jobs: shell: bash run: | set -euo pipefail - for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta; do + for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta packages/wallet; do name="$(node -p "require('./$dir/package.json').name")" version="$(node -p "require('./$dir/package.json').version")" if npm view "$name@$version" version >/dev/null 2>&1; then diff --git a/docs/JSON_CONTRACT.md b/docs/JSON_CONTRACT.md index 7a85a9b0..e80b21f8 100644 --- a/docs/JSON_CONTRACT.md +++ b/docs/JSON_CONTRACT.md @@ -158,7 +158,7 @@ backward-compatibility mirrors of another field in the same object. ### `mn balance --wallet --json` Wallet-based balance also includes shielded fields. Shape per current -code in `src/commands/balance.ts`. (Subject to the same additive-only +code in `packages/wallet/src/commands/balance.ts`. (Subject to the same additive-only rule once formally documented here.) ### `mn info --wallet --json` @@ -275,7 +275,7 @@ rule once formally documented here.) ### `mn wallet list --json` -Per `src/commands/wallet.ts`, list of wallet names, addresses, +Per `packages/wallet/src/commands/wallet.ts`, list of wallet names, addresses, networks, with the active wallet marked. Shape stable. ### `mn config get ` diff --git a/package-lock.json b/package-lock.json index ff0b7af8..1ff2d5a8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,8 @@ "packages/cli-core", "packages/chain", "packages/engine-rc", - "packages/engine-beta" + "packages/engine-beta", + "packages/wallet" ], "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", @@ -22,8 +23,8 @@ "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1", "@modelcontextprotocol/sdk": "^1.27.1", - "@scure/bip39": "^2.0.1", "ws": "^8.19.0" }, "bin": { @@ -682,6 +683,10 @@ "resolved": "packages/engine-rc", "link": true }, + "node_modules/@kuiralabs/midnight-wallet": { + "resolved": "packages/wallet", + "link": true + }, "node_modules/@midnight-ntwrk/compact-js": { "version": "3.0.0-rc.3", "resolved": "https://registry.npmjs.org/@midnight-ntwrk/compact-js/-/compact-js-3.0.0-rc.3.tgz", @@ -6253,6 +6258,19 @@ "engines": { "node": ">=22" } + }, + "packages/wallet": { + "name": "@kuiralabs/midnight-wallet", + "version": "0.1.0-rc.1", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@scure/bip39": "^2.0.1" + }, + "engines": { + "node": ">=22" + } } } } diff --git a/package.json b/package.json index 0275c43b..ef9f2dce 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,8 @@ "packages/cli-core", "packages/chain", "packages/engine-rc", - "packages/engine-beta" + "packages/engine-beta", + "packages/wallet" ], "bin": { "midnight": "dist/wallet.js", @@ -50,7 +51,7 @@ }, "scripts": { "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", - "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && npm run build -w @kuiralabs/midnight-wallet && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", @@ -71,8 +72,8 @@ "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1", "@modelcontextprotocol/sdk": "^1.27.1", - "@scure/bip39": "^2.0.1", "ws": "^8.19.0" }, "devDependencies": { diff --git a/packages/wallet/api-report.md b/packages/wallet/api-report.md new file mode 100644 index 00000000..1c2a1828 --- /dev/null +++ b/packages/wallet/api-report.md @@ -0,0 +1,383 @@ +# API report: @kuiralabs/midnight-wallet + +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-wallet` + +```ts +export declare function clearChainCaches(network: string | undefined, root: string): void; +export declare function checkPassphrase(root: string, passphrase: string): void; +export declare function establishPassphrase(root: string, passphrase: string): void; +export declare function isPassphraseSet(root: string): boolean; +export declare class NoPassphraseError extends UsageError { + readonly code = "PASSPHRASE_REQUIRED"; + constructor(); +} +export type PassphraseHost = Pick; +export declare function passphraseForNewSecret(host: PassphraseHost, root: string, source?: PassphraseSource): Promise; +export interface PassphraseSource { + env?: Record; + confirm?: boolean; + signal?: AbortSignal; +} +export declare function readPassphrase(prompter: Prompter | null, source?: PassphraseSource): Promise; +export declare function unlockPassphrase(host: PassphraseHost, root: string, source?: PassphraseSource): Promise; +export interface ResolvedSeed { + seed: Buffer; + walletPath: string | null; + config: WalletConfig | null; +} +export type SeedHost = UnlockHost & Pick; +export declare function seedOf(host: SeedHost, source: WalletSource): Promise; +export type WalletSource = { + wallet?: string; +} | { + seed: Uint8Array; +}; +export interface CancelSwapOfferOptions extends PaidCallOptions { + id: string; + receiptWaitMs?: number; +} +export declare function cancelSwapOffer(host: Host, options: CancelSwapOfferOptions): Promise; +export interface CancelledSwapOffer { + readonly network: NetworkName; + readonly id: string; + readonly cancelled: boolean; + readonly txHash?: string; + readonly receipt?: Receipt; +} +export interface InspectSwapOfferOptions extends NetworkChoice { + offer: string; + now?: Date; + signal?: AbortSignal; + onProgress?: (event: ProgressEvent) => void; +} +export declare function inspectSwapOffer(host: Host, options: InspectSwapOfferOptions): Promise; +export interface SwapOfferStanding { + readonly network: NetworkName; + readonly id: string; + readonly terms: SwapTerms; + readonly expiresAt: Date; + readonly expired: boolean; + readonly live: boolean; + readonly spends: readonly CoinSpend[]; +} +export interface ListSwapOffersOptions extends NetworkChoice { + wallet?: string; + now?: Date; + signal?: AbortSignal; + onProgress?: (event: ProgressEvent) => void; +} +export declare function listSwapOffers(host: Host, options?: ListSwapOffersOptions): Promise; +export interface SwapOffersListed { + readonly network: NetworkName; + readonly offers: readonly ListedOffer[]; +} +export interface MadeSwapOffer { + readonly network: NetworkName; + readonly id: string; + readonly terms: SwapTerms; + readonly expiresAt: Date; + readonly file: string; +} +export declare function makeSwapOffer(host: Host, options: MakeSwapOfferOptions): Promise; +export interface MakeSwapOfferOptions extends PaidCallOptions { + terms: SwapTerms; + expiresAt: Date; + now?: Date; +} +export interface SwapNetworkChosen { + readonly kind: 'swap-network'; + readonly network: NetworkName; +} +export declare function cancelOffer(session: WalletSession, root: string, networkConfig: NetworkConfig, walletAddress: string, id: string, signal?: AbortSignal): Promise; +export interface CancelOutcome { + txHash: string | undefined; + cancelled: OpenOffer[]; + alreadyTaken: OpenOffer[]; +} +export interface MadeOffer { + envelope: OfferEnvelope; + file: string; +} +export declare function makeOffer(session: WalletSession, engine: Engine, root: string, walletAddress: string, terms: SwapTerms, expiresAt: Date, now?: Date): Promise; +export declare class NoSuchOfferError extends UsageError { + constructor(id: string); +} +export interface ReadOffer { + envelope: OfferEnvelope; + contents: OfferContents; +} +export declare function readOfferFile(root: string, text: string, network: NetworkName, engines: HostEngines): Promise; +export declare function takeOffer(session: WalletSession, offer: ReadOffer, agreed: SwapTerms, networkConfig: NetworkConfig, now?: Date, signal?: AbortSignal): Promise; +export interface SwapOfferChecked { + readonly kind: 'offer-checked'; + readonly network: NetworkName; + readonly id: string; + readonly terms: SwapTerms; +} +export declare function takeSwapOffer(host: Host, options: TakeSwapOfferOptions): Promise; +export interface TakeSwapOfferOptions extends PaidCallOptions { + offer: string; + agreed: SwapTerms; + now?: Date; + receiptWaitMs?: number; +} +export interface TakenSwapOffer { + readonly network: NetworkName; + readonly id: string; + readonly txHash: string; + readonly receipt?: Receipt; +} +export interface AirdropAddressed { + readonly kind: 'airdrop-addressed'; + readonly network: NetworkName; + readonly recipient: string; + readonly shielded: boolean; +} +export declare function airdropNight(host: Host, options: AirdropNightOptions): Promise; +export interface AirdropNightOptions extends WalletCallOptions { + to: AirdropRecipient; + amount: bigint; + shielded?: boolean; + receiptWaitMs?: number; +} +export type AirdropRecipient = { + wallet?: string; +} | { + address: string; +}; +export interface NightAirdrop { + readonly network: NetworkName; + readonly txHash: string; + readonly recipient: string; + readonly shielded: boolean; + readonly receipt?: Receipt; +} +export interface AddressBalance { + readonly address: string; + readonly network: NetworkName; + readonly balances: ReadonlyMap; + readonly utxoCount: number; + readonly txCount: number; +} +export declare function readAddressBalance(host: Host, address: string, options?: ReadAddressBalanceOptions): Promise; +export interface ReadAddressBalanceOptions extends Omit { + forceFresh?: boolean; +} +export declare function readWalletBalance(host: Host, source: WalletSource, options?: ReadWalletBalanceOptions): Promise; +export interface ReadWalletBalanceOptions extends WalletCallOptions { + forceFresh?: boolean; + forceShielded?: boolean; +} +export interface ShieldedHoldings { + readonly night: bigint; + readonly availableCoins: number; + readonly tokens: ReadonlyMap; +} +export interface UnshieldedRead { + readonly kind: 'unshielded-read'; + readonly night: bigint; + readonly utxoCount: number; +} +export interface WalletBalance { + readonly network: NetworkName; + readonly address: string; + readonly shieldedAddress?: string; + readonly unshielded: { + readonly night: bigint; + readonly utxoCount: number; + }; + readonly shielded: ShieldedHoldings | null; +} +export interface DustRegistered extends DustRegistrationCounts { + readonly registered: true; + readonly dust: bigint; + readonly availableCoins: number; + readonly ownedUtxos: number; + readonly eventsApplied: number; + readonly fromCache: boolean; +} +export interface DustRegistrationCounts { + readonly network: NetworkName; + readonly registeredUtxos: number; + readonly unregisteredUtxos: number; +} +export interface DustRegistrationResult { + readonly network: NetworkName; + readonly alreadyAvailable: boolean; + readonly dust: bigint; + readonly txHash?: string; + readonly receipt?: Receipt; +} +export type DustStatus = DustUnregistered | DustRegistered; +export interface DustUnregistered extends DustRegistrationCounts { + readonly registered: false; +} +export declare function exportDustSnapshot(host: Host, source: WalletSource, options?: WalletCallOptions): Promise; +export declare function readDustStatus(host: Host, source: WalletSource, options?: ReadDustStatusOptions): Promise; +export interface ReadDustStatusOptions extends WalletCallOptions { + forceFresh?: boolean; +} +export declare function registerDust(host: Host, source: WalletSource, options?: RegisterDustOptions): Promise; +export interface RegisterDustOptions extends WalletCallOptions { + receiptWaitMs?: number; +} +export interface PaidCallOptions extends NetworkChoice { + payer: Payer; + wallet?: string; + signal?: AbortSignal; + onProgress?: (event: ProgressEvent | StepFailed | Event) => void; + sdkWarnings?: CallSdkWarnings; +} +export interface StepFailed { + readonly kind: 'step-failed'; + readonly message: string; +} +export declare function stepSpinner(onProgress: ((event: ProgressEvent | StepFailed) => void) | undefined, message: string): Spinner; +export interface NightTransfer { + readonly network: NetworkName; + readonly txHash: string; + readonly receipt?: Receipt; +} +export declare function transferNight(host: Host, source: WalletSource, options: TransferNightOptions): Promise; +export interface TransferNightOptions extends WalletCallOptions { + recipient: string; + amount: bigint; + shielded?: boolean; + forceShielded?: boolean; + receiptWaitMs?: number; +} +export declare function networkChoiceOf(options: NetworkChoice): NetworkChoice; +export interface WalletCallOptions extends NetworkChoice { + signal?: AbortSignal; + onProgress?: (event: ProgressEvent | Event) => void; + log?: VerboseLog; + sdkWarnings?: CallSdkWarnings; +} +export interface WalletOpened { + readonly kind: 'wallet-opened'; + readonly network: NetworkName; + readonly address: string; + readonly shieldedAddress?: string; +} +export declare function assertWalletCanPay({ network, root, host, networkConfig }: PayingTarget, wallet: string | undefined, progress: Spinner, signal?: AbortSignal): Promise<{ + nightBalance: bigint; + dustBalance: bigint; +}>; +export declare function assertWalletFileExists(resolvedPath: string): void; +export declare function assertWalletRemovable(root: string, name: string): string; +export declare function getActiveWalletName(root: string): string; +export declare function listWallets(root: string, engines: HostEngines): Promise; +export declare function loadWalletConfig(walletPath: string, engines: HostEngines): Promise; +export interface ProtectedWallet { + name: string; + file: string; + sealedNow: boolean; +} +export declare function protectAllWallets(root: string, passphrase: string, engines: HostEngines, signal?: AbortSignal): Promise; +export declare function resolveWalletPath(root: string, nameOrPath?: string): string; +export declare function setActiveWallet(root: string, name: string): void; +export type UnlockedWallet = WalletConfig & WalletSecrets; +export type UnlockHost = PassphraseHost & Pick; +export interface UnlockOptions { + root: string; + host: UnlockHost; + source?: PassphraseSource; + warn?: (line: string) => void; +} +export declare function unlockWallet(walletPath: string, options: UnlockOptions): Promise; +export declare function walletAddress(walletPath: string, network: NetworkName, root: string, host: UnlockHost): Promise; +export interface WalletConfig { + addresses: Record; + shieldedAddresses?: Record; + createdAt: string; + isSealed: boolean; +} +export interface WalletInfo { + name: string; + addresses: Record; + shieldedAddresses?: Record; + isActive: boolean; + createdAt?: string; + file: string; +} +export declare class WalletNotFoundError extends Error { + readonly code = "WALLET_NOT_FOUND"; + constructor(message: string); +} +export interface WalletSecrets { + seed: string; + mnemonic?: string; +} +export declare function createWallet(root: string, name: string, secret: WalletSecret, passphrase: string, engine: Engine, { overwrite }?: { + overwrite?: boolean; +}): Promise; +export interface CreatedWallet { + name: string; + addresses: WalletPublic['addresses']; + shieldedAddresses: NonNullable; + seed: Buffer; + mnemonic?: string; + file: string; + createdAt: string; +} +export declare function walletFilePath(root: string, name: string): string; +export interface WalletSecret { + seed: Buffer; + mnemonic?: string; +} +export declare function walletSecretFrom(given?: { + seed?: Buffer; + mnemonic?: string; +}): WalletSecret; +export declare function migrateOldWallet(root: string): void; +export type ProtectedItem = { + subject: string; + outcome: 'sealed-now'; + sealedNote: string; +} | { + subject: string; + outcome: 'already-sealed'; +} | { + subject: string; + error: string; +}; +export interface ProtectorResult { + items: ProtectedItem[]; + report: unknown; +} +export interface WalletProtector { + name: string; + protect(root: string, passphrase: string, coinKeyOf: (wallet: string) => Promise, engines: HostEngines): Promise; +} +``` + +## `@kuiralabs/midnight-wallet/commands` + +```ts +export declare const addressDefinition: CommandDefinition; +export declare const airdropDefinition: CommandDefinition; +export declare const balanceDefinition: CommandDefinition; +export declare const cacheDefinition: CommandDefinition; +export declare const dustDefinition: CommandDefinition; +export declare const generateDefinition: CommandDefinition; +export declare const genesisAddressDefinition: CommandDefinition; +export declare const infoDefinition: CommandDefinition; +export declare const swapDefinition: CommandDefinition; +export declare const swapGuidance: PackageGuidance; +export declare const transferDefinition: CommandDefinition; +export declare const OPENS_WALLET: import("@kuiralabs/midnight-cli-core").CodeSet; +export declare const walletCodes: readonly [ + { + readonly code: "WALLET_NOT_FOUND"; + readonly exitCode: 3; + readonly order: 20; + readonly summary: "Named wallet doesn't exist on disk."; + readonly recovery: "`midnight_wallet_list()` — user may have removed it."; + } +]; +export declare const walletDefinition: CommandDefinition; +export declare const walletGuidance: PackageGuidance; +export declare function showPaidStep(reporter: SpinnerReporter, event: ProgressEvent | StepFailed): void; +``` diff --git a/packages/wallet/package.json b/packages/wallet/package.json new file mode 100644 index 00000000..c4f66820 --- /dev/null +++ b/packages/wallet/package.json @@ -0,0 +1,42 @@ +{ + "name": "@kuiralabs/midnight-wallet", + "version": "0.1.0-rc.1", + "type": "module", + "description": "Wallets for the Midnight CLI packages: mn's passphrase and sealed wallet files, seeds, balances, NIGHT transfers and airdrops, Dust registration, and swap offers", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/wallet" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@scure/bip39": "^2.0.1" + } +} diff --git a/src/__tests__/cache-local-stacks.test.ts b/packages/wallet/src/__tests__/cache-local-stacks.test.ts similarity index 100% rename from src/__tests__/cache-local-stacks.test.ts rename to packages/wallet/src/__tests__/cache-local-stacks.test.ts diff --git a/src/__tests__/host-engines.test.ts b/packages/wallet/src/__tests__/host-engines.test.ts similarity index 96% rename from src/__tests__/host-engines.test.ts rename to packages/wallet/src/__tests__/host-engines.test.ts index 0ed33bed..5aa242c7 100644 --- a/src/__tests__/host-engines.test.ts +++ b/packages/wallet/src/__tests__/host-engines.test.ts @@ -11,10 +11,10 @@ import { createHost, type Host, type SdkSet, type NetworkConfig, type PayingTarg import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; import type { BalanceSummary } from '@kuiralabs/midnight-chain'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { rcKeys } from '../../test-support/rc-engine.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; import { listWallets } from '../lib/wallet-config.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; // The chain and the indexer stand in at the repository's seams; the rest is each engine's own. const NETWORK: NetworkConfig = { diff --git a/src/__tests__/multi-wallet.test.ts b/packages/wallet/src/__tests__/multi-wallet.test.ts similarity index 98% rename from src/__tests__/multi-wallet.test.ts rename to packages/wallet/src/__tests__/multi-wallet.test.ts index 982c9726..73c5001b 100644 --- a/src/__tests__/multi-wallet.test.ts +++ b/packages/wallet/src/__tests__/multi-wallet.test.ts @@ -11,10 +11,10 @@ import { loadWalletConfig, } from '../lib/wallet-config.ts'; import { migrateOldWallet } from '../lib/wallet-paths.ts'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../../../test-support/plain-wallet.ts'; import { loadCliConfig, saveCliConfig, type CliConfig, MIDNIGHT_DIR, WALLETS_DIR_NAME, DEFAULT_WALLET_NAME, DEFAULT_WALLET_FILENAME, DIR_MODE, FILE_MODE, isValidWalletName, createHost } from '@kuiralabs/midnight-cli-core'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The engines the wallet functions derive a wallet's missing addresses with: a host's of the engines the CLI ships. const { engines } = createHost({ engineLoader: loadInstalledEngine }); diff --git a/src/__tests__/passphrase.test.ts b/packages/wallet/src/__tests__/passphrase.test.ts similarity index 98% rename from src/__tests__/passphrase.test.ts rename to packages/wallet/src/__tests__/passphrase.test.ts index b0b4ae5e..f964d43f 100644 --- a/src/__tests__/passphrase.test.ts +++ b/packages/wallet/src/__tests__/passphrase.test.ts @@ -20,7 +20,7 @@ import { readPassphrase, unlockPassphrase, } from '../lib/passphrase.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/sealed-wallet.test.ts b/packages/wallet/src/__tests__/sealed-wallet.test.ts similarity index 96% rename from src/__tests__/sealed-wallet.test.ts rename to packages/wallet/src/__tests__/sealed-wallet.test.ts index 3765be49..b39f4a3e 100644 --- a/src/__tests__/sealed-wallet.test.ts +++ b/packages/wallet/src/__tests__/sealed-wallet.test.ts @@ -11,9 +11,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { WrongPassphraseError, FILE_MODE, createHost } from '@kuiralabs/midnight-cli-core'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { loadWalletConfig, protectAllWallets, sealWalletInPlace, unlockWallet, writeSealedWallet } from '../lib/wallet-config.ts'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = createHost({ engineLoader: loadInstalledEngine }); diff --git a/src/__tests__/seed-resolver.test.ts b/packages/wallet/src/__tests__/seed-resolver.test.ts similarity index 98% rename from src/__tests__/seed-resolver.test.ts rename to packages/wallet/src/__tests__/seed-resolver.test.ts index 76cac1bc..9f0dc361 100644 --- a/src/__tests__/seed-resolver.test.ts +++ b/packages/wallet/src/__tests__/seed-resolver.test.ts @@ -8,12 +8,11 @@ import { join } from 'node:path'; import { parseArgs, createHost, settingsFromEnvironment } from '@kuiralabs/midnight-cli-core'; import { parseSeedHex, resolveSeedSource, resolveSeed, seedOf, walletSourceOf } from '../lib/seed-resolver.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { mkdirSync } from 'node:fs'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; import { type WalletPublic, writeSealedWallet } from '../lib/wallet-config.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; -import { testHost } from '../../test-support/test-host.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine, testHost } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = testHost(); diff --git a/src/__tests__/settings.test.ts b/packages/wallet/src/__tests__/settings.test.ts similarity index 100% rename from src/__tests__/settings.test.ts rename to packages/wallet/src/__tests__/settings.test.ts diff --git a/src/__tests__/swap-lib.test.ts b/packages/wallet/src/__tests__/swap-lib.test.ts similarity index 97% rename from src/__tests__/swap-lib.test.ts rename to packages/wallet/src/__tests__/swap-lib.test.ts index 3da80d67..e7a57d24 100644 --- a/src/__tests__/swap-lib.test.ts +++ b/packages/wallet/src/__tests__/swap-lib.test.ts @@ -17,15 +17,15 @@ import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { WebSocketServer } from 'ws'; import { createHost, type Host, saveCliConfig, type ConnectOptions, type Payer, type PayingTarget, encodeOfferEnvelope, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; -import { rcEngine, rcKeys } from '../../test-support/rc-engine.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcEngine, rcKeys } from '../../../../test-support/rc-engine.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { makeSwapOffer } from '../lib/swap/make.ts'; import { inspectSwapOffer } from '../lib/swap/inspect.ts'; import { takeSwapOffer } from '../lib/swap/take.ts'; import { cancelSwapOffer } from '../lib/swap/cancel.ts'; import { listSwapOffers } from '../lib/swap/list.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../test-support/fixtures/swap-offer.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../../../test-support/fixtures/swap-offer.ts'; const NOW = new Date('2026-11-02T12:00:00.000Z'); const SEED = 'c4'.repeat(32); diff --git a/src/__tests__/swap-request.test.ts b/packages/wallet/src/__tests__/swap-request.test.ts similarity index 95% rename from src/__tests__/swap-request.test.ts rename to packages/wallet/src/__tests__/swap-request.test.ts index 19313a06..a7c2154f 100644 --- a/src/__tests__/swap-request.test.ts +++ b/packages/wallet/src/__tests__/swap-request.test.ts @@ -9,9 +9,9 @@ import { join } from 'node:path'; import { parseArgs, UsageError, encodeOfferEnvelope, OfferExpiredError, TermsMismatchError } from '@kuiralabs/midnight-cli-core'; import { NotAnOfferError } from '@kuiralabs/midnight-cli-core/engine'; import { DEFAULT_OFFER_LIFETIME_S, prepareMake, prepareTake, termsOf } from '../lib/swap/request.ts'; -import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../test-support/fixtures/swap-offer.ts'; -import { testHost } from '../../test-support/test-host.ts'; -import { rcEngine } from '../../test-support/rc-engine.ts'; +import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../../../test-support/fixtures/swap-offer.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; +import { rcEngine } from '../../../../test-support/rc-engine.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = testHost(); diff --git a/src/__tests__/sync-eta.test.ts b/packages/wallet/src/__tests__/sync-eta.test.ts similarity index 100% rename from src/__tests__/sync-eta.test.ts rename to packages/wallet/src/__tests__/sync-eta.test.ts diff --git a/src/__tests__/transfer-request.test.ts b/packages/wallet/src/__tests__/transfer-request.test.ts similarity index 79% rename from src/__tests__/transfer-request.test.ts rename to packages/wallet/src/__tests__/transfer-request.test.ts index e27c264f..4ac943d2 100644 --- a/src/__tests__/transfer-request.test.ts +++ b/packages/wallet/src/__tests__/transfer-request.test.ts @@ -8,10 +8,12 @@ import * as os from 'os'; import * as path from 'path'; import { resolveTransferRequest } from '../lib/transfer-request.ts'; import { parseArgs, MIDNIGHT_DIR, WALLETS_DIR_NAME, UsageError, classifyError, createHost } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { installedCommands } from '../lib/installed-commands.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; +import { walletCodes } from '../commands/wallet.codes.ts'; +import { codeRegistry } from '../../../../test-support/core-codes.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = createHost({ engineLoader: loadInstalledEngine }); @@ -90,7 +92,7 @@ describe('resolveTransferRequest', () => { let err: unknown; try { await request(...argv, '--wallet', 'sender'); } catch (e) { err = e; } expect(err).toBeInstanceOf(UsageError); - expect(classifyError(err as Error, installedCommands).errorCode).toBe('INVALID_ARGS'); + expect(classifyError(err as Error, codeRegistry(coreCodes, walletCodes)).errorCode).toBe('INVALID_ARGS'); }); it('refuses a shielded transfer where shielded is off before reading the address', async () => { @@ -98,3 +100,12 @@ describe('resolveTransferRequest', () => { .rejects.toThrow(/Shielded is unavailable on preprod/); }); }); + +// The error-code parity table's row for a transfer's arguments (src/__tests__/error-code-parity.test.ts +// lists every typed error where mn throws it; this one is the wallet's transfer request's own). +describe('a shielded transfer where shielded is off, in the error-code parity table', () => { + it('reports INVALID_ARGS, exit 2, as before codes were owned per package', async () => { + const err = await request(rcKeys.shieldedAddresses(SENDER_SEED).preprod, '1', '--wallet', 'sender', '--shielded', '--network', 'preprod').catch((e: Error) => e); + expect(classifyError(err as Error, codeRegistry(coreCodes, walletCodes))).toStrictEqual({ errorCode: 'INVALID_ARGS', exitCode: 2 }); + }); +}); diff --git a/src/__tests__/wallet-airdrop-lib.test.ts b/packages/wallet/src/__tests__/wallet-airdrop-lib.test.ts similarity index 96% rename from src/__tests__/wallet-airdrop-lib.test.ts rename to packages/wallet/src/__tests__/wallet-airdrop-lib.test.ts index e5438a6c..61f82740 100644 --- a/src/__tests__/wallet-airdrop-lib.test.ts +++ b/packages/wallet/src/__tests__/wallet-airdrop-lib.test.ts @@ -11,12 +11,12 @@ import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { createHost, type Host, settingsFromEnvironment, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { airdropNight, type AirdropAddressed, type AirdropNightOptions } from '../lib/wallet/airdrop.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from '../../test-support/stand-in-indexer.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from '../../../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED = Buffer.from('a7'.repeat(32), 'hex'); diff --git a/src/__tests__/wallet-balance-lib.test.ts b/packages/wallet/src/__tests__/wallet-balance-lib.test.ts similarity index 97% rename from src/__tests__/wallet-balance-lib.test.ts rename to packages/wallet/src/__tests__/wallet-balance-lib.test.ts index 674c1be3..89f30ced 100644 --- a/src/__tests__/wallet-balance-lib.test.ts +++ b/packages/wallet/src/__tests__/wallet-balance-lib.test.ts @@ -9,14 +9,14 @@ import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { createHost, type Host, settingsFromEnvironment, NATIVE_TOKEN_TYPE, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { establishPassphrase, PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { writeSealedWallet, type WalletPublic } from '../lib/wallet-config.ts'; import { readAddressBalance, readWalletBalance, type UnshieldedRead } from '../lib/wallet/balance.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED_A = 'a1'.repeat(32); diff --git a/src/__tests__/wallet-config.test.ts b/packages/wallet/src/__tests__/wallet-config.test.ts similarity index 97% rename from src/__tests__/wallet-config.test.ts rename to packages/wallet/src/__tests__/wallet-config.test.ts index 7077f882..9e58203b 100644 --- a/src/__tests__/wallet-config.test.ts +++ b/packages/wallet/src/__tests__/wallet-config.test.ts @@ -4,11 +4,11 @@ import * as path from 'path'; import * as os from 'os'; import { loadWalletConfig, matchWalletAddress, unlockWallet, walletAddress, writeSealedWallet, type WalletInfo } from '../lib/wallet-config.ts'; import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../../../test-support/plain-wallet.ts'; import { DIR_MODE, FILE_MODE, createHost } from '@kuiralabs/midnight-cli-core'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = createHost({ engineLoader: loadInstalledEngine }); diff --git a/src/__tests__/wallet-create.test.ts b/packages/wallet/src/__tests__/wallet-create.test.ts similarity index 95% rename from src/__tests__/wallet-create.test.ts rename to packages/wallet/src/__tests__/wallet-create.test.ts index 6b36f5f9..2b0c5f21 100644 --- a/src/__tests__/wallet-create.test.ts +++ b/packages/wallet/src/__tests__/wallet-create.test.ts @@ -10,10 +10,10 @@ import * as path from 'node:path'; import { mnemonicToSeedSync } from '@scure/bip39'; import { createWallet, walletFilePath, walletSecretFrom } from '../lib/wallet-create.ts'; import { getActiveWalletName, unlockWallet } from '../lib/wallet-config.ts'; -import { rcKeys } from '../../test-support/rc-engine.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; -import { testHost } from '../../test-support/test-host.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = testHost(); diff --git a/src/__tests__/wallet-dust-lib.test.ts b/packages/wallet/src/__tests__/wallet-dust-lib.test.ts similarity index 96% rename from src/__tests__/wallet-dust-lib.test.ts rename to packages/wallet/src/__tests__/wallet-dust-lib.test.ts index 9a6dbeef..651d27e3 100644 --- a/src/__tests__/wallet-dust-lib.test.ts +++ b/packages/wallet/src/__tests__/wallet-dust-lib.test.ts @@ -11,13 +11,13 @@ import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { createHost, type Host, settingsFromEnvironment, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { exportDustSnapshot, readDustStatus, registerDust } from '../lib/wallet/dust.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED_A = 'c3'.repeat(32); diff --git a/src/__tests__/wallet-transfer-lib.test.ts b/packages/wallet/src/__tests__/wallet-transfer-lib.test.ts similarity index 96% rename from src/__tests__/wallet-transfer-lib.test.ts rename to packages/wallet/src/__tests__/wallet-transfer-lib.test.ts index 43b2cd1f..a4e7a6fd 100644 --- a/src/__tests__/wallet-transfer-lib.test.ts +++ b/packages/wallet/src/__tests__/wallet-transfer-lib.test.ts @@ -11,13 +11,13 @@ import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { createHost, type Host, settingsFromEnvironment, saveCliConfig, type Prompter, type ProgressEvent } from '@kuiralabs/midnight-cli-core'; -import { rcKeys } from '../../test-support/rc-engine.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; import { transferNight, type TransferNightOptions } from '../lib/wallet/transfer.ts'; import type { WalletOpened } from '../lib/wallet/wallet-call.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from '../../test-support/stand-in-indexer.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { startLedger8Indexer, startRefusingEndpoint, type Ledger8Indexer } from '../../../../test-support/stand-in-indexer.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED_A = 'e5'.repeat(32); diff --git a/packages/wallet/src/commands.ts b/packages/wallet/src/commands.ts new file mode 100644 index 00000000..f8dc42d1 --- /dev/null +++ b/packages/wallet/src/commands.ts @@ -0,0 +1,22 @@ +// @kuiralabs/midnight-wallet/commands: the wallet's commands (wallet, +// generate, info, balance, address, genesis-address, airdrop, transfer, +// dust, cache) and swap, its codes and the code set other packages' +// definitions name, its agent guidance and swap's, for the shell that +// installs them; and the terminal step a command above shows a paid call's +// progress with. + +export { addressDefinition } from './commands/address.definition.ts'; +export { airdropDefinition } from './commands/airdrop.definition.ts'; +export { balanceDefinition } from './commands/balance.definition.ts'; +export { cacheDefinition } from './commands/cache.definition.ts'; +export { dustDefinition } from './commands/dust.definition.ts'; +export { generateDefinition } from './commands/generate.definition.ts'; +export { genesisAddressDefinition } from './commands/genesis-address.definition.ts'; +export { infoDefinition } from './commands/info.definition.ts'; +export { swapDefinition } from './commands/swap.definition.ts'; +export { swapGuidance } from './commands/swap.guidance.ts'; +export { transferDefinition } from './commands/transfer.definition.ts'; +export { OPENS_WALLET, walletCodes } from './commands/wallet.codes.ts'; +export { walletDefinition } from './commands/wallet.definition.ts'; +export { walletGuidance } from './commands/wallet.guidance.ts'; +export { showPaidStep } from './lib/wallet/paid-call.ts'; diff --git a/src/commands/address.definition.ts b/packages/wallet/src/commands/address.definition.ts similarity index 100% rename from src/commands/address.definition.ts rename to packages/wallet/src/commands/address.definition.ts diff --git a/src/commands/address.ts b/packages/wallet/src/commands/address.ts similarity index 100% rename from src/commands/address.ts rename to packages/wallet/src/commands/address.ts diff --git a/src/commands/airdrop.definition.ts b/packages/wallet/src/commands/airdrop.definition.ts similarity index 100% rename from src/commands/airdrop.definition.ts rename to packages/wallet/src/commands/airdrop.definition.ts diff --git a/src/commands/airdrop.ts b/packages/wallet/src/commands/airdrop.ts similarity index 100% rename from src/commands/airdrop.ts rename to packages/wallet/src/commands/airdrop.ts diff --git a/src/commands/balance.definition.ts b/packages/wallet/src/commands/balance.definition.ts similarity index 100% rename from src/commands/balance.definition.ts rename to packages/wallet/src/commands/balance.definition.ts diff --git a/src/commands/balance.ts b/packages/wallet/src/commands/balance.ts similarity index 100% rename from src/commands/balance.ts rename to packages/wallet/src/commands/balance.ts diff --git a/src/commands/cache.definition.ts b/packages/wallet/src/commands/cache.definition.ts similarity index 100% rename from src/commands/cache.definition.ts rename to packages/wallet/src/commands/cache.definition.ts diff --git a/src/commands/cache.ts b/packages/wallet/src/commands/cache.ts similarity index 100% rename from src/commands/cache.ts rename to packages/wallet/src/commands/cache.ts diff --git a/src/commands/dust.definition.ts b/packages/wallet/src/commands/dust.definition.ts similarity index 98% rename from src/commands/dust.definition.ts rename to packages/wallet/src/commands/dust.definition.ts index bf66ca63..be09975f 100644 --- a/src/commands/dust.definition.ts +++ b/packages/wallet/src/commands/dust.definition.ts @@ -39,7 +39,7 @@ export const dustDefinition: CommandDefinition = { agent: { type: 'string' }, }, { - // Help says register only, but every subcommand resolves its network with it (src/commands/dust.ts). + // Help says register only, but every subcommand resolves its network with it (commands/dust.ts). name: 'node', takesValue: true, help: ['--node Override substrate node RPC URL (register only)'], @@ -52,7 +52,7 @@ export const dustDefinition: CommandDefinition = { agent: ENDPOINT_PARAMS['indexer-ws'], }, { - // Help says register only, but every subcommand resolves its network with it (src/commands/dust.ts). + // Help says register only, but every subcommand resolves its network with it (commands/dust.ts). name: 'proof-server', takesValue: true, help: ['--proof-server Override proof server URL (register only)'], diff --git a/src/commands/dust.ts b/packages/wallet/src/commands/dust.ts similarity index 100% rename from src/commands/dust.ts rename to packages/wallet/src/commands/dust.ts diff --git a/src/commands/generate.definition.ts b/packages/wallet/src/commands/generate.definition.ts similarity index 100% rename from src/commands/generate.definition.ts rename to packages/wallet/src/commands/generate.definition.ts diff --git a/src/commands/generate.ts b/packages/wallet/src/commands/generate.ts similarity index 100% rename from src/commands/generate.ts rename to packages/wallet/src/commands/generate.ts diff --git a/src/commands/genesis-address.definition.ts b/packages/wallet/src/commands/genesis-address.definition.ts similarity index 100% rename from src/commands/genesis-address.definition.ts rename to packages/wallet/src/commands/genesis-address.definition.ts diff --git a/src/commands/genesis-address.ts b/packages/wallet/src/commands/genesis-address.ts similarity index 100% rename from src/commands/genesis-address.ts rename to packages/wallet/src/commands/genesis-address.ts diff --git a/src/commands/info.definition.ts b/packages/wallet/src/commands/info.definition.ts similarity index 100% rename from src/commands/info.definition.ts rename to packages/wallet/src/commands/info.definition.ts diff --git a/src/commands/info.ts b/packages/wallet/src/commands/info.ts similarity index 100% rename from src/commands/info.ts rename to packages/wallet/src/commands/info.ts diff --git a/src/commands/swap.definition.ts b/packages/wallet/src/commands/swap.definition.ts similarity index 100% rename from src/commands/swap.definition.ts rename to packages/wallet/src/commands/swap.definition.ts diff --git a/src/commands/swap.guidance.ts b/packages/wallet/src/commands/swap.guidance.ts similarity index 100% rename from src/commands/swap.guidance.ts rename to packages/wallet/src/commands/swap.guidance.ts diff --git a/src/commands/swap.ts b/packages/wallet/src/commands/swap.ts similarity index 100% rename from src/commands/swap.ts rename to packages/wallet/src/commands/swap.ts diff --git a/src/commands/transfer.definition.ts b/packages/wallet/src/commands/transfer.definition.ts similarity index 100% rename from src/commands/transfer.definition.ts rename to packages/wallet/src/commands/transfer.definition.ts diff --git a/src/commands/transfer.ts b/packages/wallet/src/commands/transfer.ts similarity index 100% rename from src/commands/transfer.ts rename to packages/wallet/src/commands/transfer.ts diff --git a/src/commands/wallet.codes.ts b/packages/wallet/src/commands/wallet.codes.ts similarity index 100% rename from src/commands/wallet.codes.ts rename to packages/wallet/src/commands/wallet.codes.ts diff --git a/src/commands/wallet.definition.ts b/packages/wallet/src/commands/wallet.definition.ts similarity index 100% rename from src/commands/wallet.definition.ts rename to packages/wallet/src/commands/wallet.definition.ts diff --git a/src/commands/wallet.guidance.ts b/packages/wallet/src/commands/wallet.guidance.ts similarity index 100% rename from src/commands/wallet.guidance.ts rename to packages/wallet/src/commands/wallet.guidance.ts diff --git a/src/commands/wallet.ts b/packages/wallet/src/commands/wallet.ts similarity index 99% rename from src/commands/wallet.ts rename to packages/wallet/src/commands/wallet.ts index fa604c61..eca67d57 100644 --- a/src/commands/wallet.ts +++ b/packages/wallet/src/commands/wallet.ts @@ -2,6 +2,7 @@ // Subcommands: generate, list, use, info, remove import * as fs from 'fs'; +import * as readline from 'readline'; import { type ParsedArgs, getFlag, hasFlag, isMinimalMode, UsageError, throwIfCancelled, resolveNetworkName, type CallContext } from '@kuiralabs/midnight-cli-core'; import { header, keyValue, divider, formatAddress, bold, yellow, dim, green, teal } from '@kuiralabs/midnight-cli-core/ui'; import { mnemonicToEntropy } from '@scure/bip39'; @@ -416,7 +417,6 @@ async function walletProtect(args: ParsedArgs, ctx: WalletCommandContext): Promi function confirm(prompt: string): Promise { return new Promise((resolve) => { - const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stderr }); rl.question(prompt, (answer: string) => { rl.close(); diff --git a/packages/wallet/src/index.ts b/packages/wallet/src/index.ts new file mode 100644 index 00000000..6b476da4 --- /dev/null +++ b/packages/wallet/src/index.ts @@ -0,0 +1,56 @@ +// @kuiralabs/midnight-wallet: mn's wallets for a program and the packages +// above. Reading balances, sending and airdropping NIGHT, Dust status, +// registration and export, and swap offers, each called with plain values; +// the session-level offer steps over a wallet session; seeds, sealed wallet +// files and mn's one passphrase. Each name is listed, so the API is what this +// file says. The wallet's commands, codes and guidance, and the terminal +// helpers the commands above use, are "./commands". + +export { clearChainCaches } from './lib/chain-caches.ts'; +export { + checkPassphrase, establishPassphrase, isPassphraseSet, NoPassphraseError, type PassphraseHost, + passphraseForNewSecret, type PassphraseSource, readPassphrase, unlockPassphrase +} from './lib/passphrase.ts'; +export { type ResolvedSeed, type SeedHost, seedOf, type WalletSource } from './lib/seed-resolver.ts'; +export { + type CancelSwapOfferOptions, cancelSwapOffer, type CancelledSwapOffer +} from './lib/swap/cancel.ts'; +export { + type InspectSwapOfferOptions, inspectSwapOffer, type SwapOfferStanding +} from './lib/swap/inspect.ts'; +export { type ListSwapOffersOptions, listSwapOffers, type SwapOffersListed } from './lib/swap/list.ts'; +export { + type MadeSwapOffer, makeSwapOffer, type MakeSwapOfferOptions, type SwapNetworkChosen +} from './lib/swap/make.ts'; +export { + cancelOffer, type CancelOutcome, type MadeOffer, makeOffer, NoSuchOfferError, type ReadOffer, + readOfferFile, takeOffer +} from './lib/swap/offers.ts'; +export { + type SwapOfferChecked, takeSwapOffer, type TakeSwapOfferOptions, type TakenSwapOffer +} from './lib/swap/take.ts'; +export { + type AirdropAddressed, airdropNight, type AirdropNightOptions, type AirdropRecipient, type NightAirdrop +} from './lib/wallet/airdrop.ts'; +export { + type AddressBalance, readAddressBalance, type ReadAddressBalanceOptions, readWalletBalance, + type ReadWalletBalanceOptions, type ShieldedHoldings, type UnshieldedRead, type WalletBalance +} from './lib/wallet/balance.ts'; +export { + type DustRegistered, type DustRegistrationCounts, type DustRegistrationResult, type DustStatus, + type DustUnregistered, exportDustSnapshot, readDustStatus, type ReadDustStatusOptions, registerDust, + type RegisterDustOptions +} from './lib/wallet/dust.ts'; +export { type PaidCallOptions, type StepFailed, stepSpinner } from './lib/wallet/paid-call.ts'; +export { type NightTransfer, transferNight, type TransferNightOptions } from './lib/wallet/transfer.ts'; +export { networkChoiceOf, type WalletCallOptions, type WalletOpened } from './lib/wallet/wallet-call.ts'; +export { assertWalletCanPay } from './lib/wallet-can-pay.ts'; +export { + assertWalletFileExists, assertWalletRemovable, getActiveWalletName, listWallets, loadWalletConfig, + type ProtectedWallet, protectAllWallets, resolveWalletPath, setActiveWallet, type UnlockedWallet, + type UnlockHost, type UnlockOptions, unlockWallet, walletAddress, type WalletConfig, type WalletInfo, + WalletNotFoundError, type WalletSecrets +} from './lib/wallet-config.ts'; +export { createWallet, type CreatedWallet, walletFilePath, type WalletSecret, walletSecretFrom } from './lib/wallet-create.ts'; +export { migrateOldWallet } from './lib/wallet-paths.ts'; +export { type ProtectedItem, type ProtectorResult, type WalletProtector } from './lib/wallet-protector.ts'; diff --git a/src/lib/chain-caches.ts b/packages/wallet/src/lib/chain-caches.ts similarity index 100% rename from src/lib/chain-caches.ts rename to packages/wallet/src/lib/chain-caches.ts diff --git a/src/lib/passphrase.ts b/packages/wallet/src/lib/passphrase.ts similarity index 100% rename from src/lib/passphrase.ts rename to packages/wallet/src/lib/passphrase.ts diff --git a/src/lib/seed-resolver.ts b/packages/wallet/src/lib/seed-resolver.ts similarity index 100% rename from src/lib/seed-resolver.ts rename to packages/wallet/src/lib/seed-resolver.ts diff --git a/src/lib/swap/cancel.ts b/packages/wallet/src/lib/swap/cancel.ts similarity index 100% rename from src/lib/swap/cancel.ts rename to packages/wallet/src/lib/swap/cancel.ts diff --git a/src/lib/swap/inspect.ts b/packages/wallet/src/lib/swap/inspect.ts similarity index 100% rename from src/lib/swap/inspect.ts rename to packages/wallet/src/lib/swap/inspect.ts diff --git a/src/lib/swap/list.ts b/packages/wallet/src/lib/swap/list.ts similarity index 100% rename from src/lib/swap/list.ts rename to packages/wallet/src/lib/swap/list.ts diff --git a/src/lib/swap/make.ts b/packages/wallet/src/lib/swap/make.ts similarity index 100% rename from src/lib/swap/make.ts rename to packages/wallet/src/lib/swap/make.ts diff --git a/src/lib/swap/offers.ts b/packages/wallet/src/lib/swap/offers.ts similarity index 100% rename from src/lib/swap/offers.ts rename to packages/wallet/src/lib/swap/offers.ts diff --git a/src/lib/swap/request.ts b/packages/wallet/src/lib/swap/request.ts similarity index 100% rename from src/lib/swap/request.ts rename to packages/wallet/src/lib/swap/request.ts diff --git a/src/lib/swap/swap-session.ts b/packages/wallet/src/lib/swap/swap-session.ts similarity index 100% rename from src/lib/swap/swap-session.ts rename to packages/wallet/src/lib/swap/swap-session.ts diff --git a/src/lib/swap/take.ts b/packages/wallet/src/lib/swap/take.ts similarity index 100% rename from src/lib/swap/take.ts rename to packages/wallet/src/lib/swap/take.ts diff --git a/src/lib/sync-eta.ts b/packages/wallet/src/lib/sync-eta.ts similarity index 100% rename from src/lib/sync-eta.ts rename to packages/wallet/src/lib/sync-eta.ts diff --git a/src/lib/transfer-request.ts b/packages/wallet/src/lib/transfer-request.ts similarity index 100% rename from src/lib/transfer-request.ts rename to packages/wallet/src/lib/transfer-request.ts diff --git a/src/lib/wallet-can-pay.ts b/packages/wallet/src/lib/wallet-can-pay.ts similarity index 100% rename from src/lib/wallet-can-pay.ts rename to packages/wallet/src/lib/wallet-can-pay.ts diff --git a/src/lib/wallet-config.ts b/packages/wallet/src/lib/wallet-config.ts similarity index 100% rename from src/lib/wallet-config.ts rename to packages/wallet/src/lib/wallet-config.ts diff --git a/src/lib/wallet-create.ts b/packages/wallet/src/lib/wallet-create.ts similarity index 100% rename from src/lib/wallet-create.ts rename to packages/wallet/src/lib/wallet-create.ts diff --git a/src/lib/wallet-paths.ts b/packages/wallet/src/lib/wallet-paths.ts similarity index 100% rename from src/lib/wallet-paths.ts rename to packages/wallet/src/lib/wallet-paths.ts diff --git a/src/lib/wallet-protector.ts b/packages/wallet/src/lib/wallet-protector.ts similarity index 100% rename from src/lib/wallet-protector.ts rename to packages/wallet/src/lib/wallet-protector.ts diff --git a/src/lib/wallet/airdrop.ts b/packages/wallet/src/lib/wallet/airdrop.ts similarity index 100% rename from src/lib/wallet/airdrop.ts rename to packages/wallet/src/lib/wallet/airdrop.ts diff --git a/src/lib/wallet/balance.ts b/packages/wallet/src/lib/wallet/balance.ts similarity index 100% rename from src/lib/wallet/balance.ts rename to packages/wallet/src/lib/wallet/balance.ts diff --git a/src/lib/wallet/dust.ts b/packages/wallet/src/lib/wallet/dust.ts similarity index 100% rename from src/lib/wallet/dust.ts rename to packages/wallet/src/lib/wallet/dust.ts diff --git a/src/lib/wallet/paid-call.ts b/packages/wallet/src/lib/wallet/paid-call.ts similarity index 100% rename from src/lib/wallet/paid-call.ts rename to packages/wallet/src/lib/wallet/paid-call.ts diff --git a/src/lib/wallet/submit-steps.ts b/packages/wallet/src/lib/wallet/submit-steps.ts similarity index 100% rename from src/lib/wallet/submit-steps.ts rename to packages/wallet/src/lib/wallet/submit-steps.ts diff --git a/src/lib/wallet/transfer.ts b/packages/wallet/src/lib/wallet/transfer.ts similarity index 100% rename from src/lib/wallet/transfer.ts rename to packages/wallet/src/lib/wallet/transfer.ts diff --git a/src/lib/wallet/wallet-call.ts b/packages/wallet/src/lib/wallet/wallet-call.ts similarity index 96% rename from src/lib/wallet/wallet-call.ts rename to packages/wallet/src/lib/wallet/wallet-call.ts index 729fb79b..d7082787 100644 --- a/src/lib/wallet/wallet-call.ts +++ b/packages/wallet/src/lib/wallet/wallet-call.ts @@ -1,4 +1,4 @@ -// What every wallet operation of src/lib/wallet takes besides its own inputs, +// What every wallet operation of lib/wallet takes besides its own inputs, // what it says once its wallet is open, and the wallet's address it acts on. import type { NetworkChoice, ProgressEvent, VerboseLog, CallSdkWarnings, HostEngines, NetworkName } from '@kuiralabs/midnight-cli-core'; diff --git a/src/ui/receipt.ts b/packages/wallet/src/ui/receipt.ts similarity index 100% rename from src/ui/receipt.ts rename to packages/wallet/src/ui/receipt.ts diff --git a/packages/wallet/tsconfig.build.json b/packages/wallet/tsconfig.build.json new file mode 100644 index 00000000..70e97051 --- /dev/null +++ b/packages/wallet/tsconfig.build.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node" + ] + }, + "include": [ + "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" + ] +} diff --git a/scripts/api-report.mjs b/scripts/api-report.mjs index 9e500558..0e2af99c 100644 --- a/scripts/api-report.mjs +++ b/scripts/api-report.mjs @@ -21,7 +21,7 @@ import { barrelExports } from './check-layering.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); /** The public packages, by folder under packages/. */ -export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta']; +export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta', 'wallet']; /** The report's path for the package in `dir` (a folder under packages/). */ export function reportPath(dir) { diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index cfa69890..6607c94d 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -51,7 +51,7 @@ const UNSCANNED_SCRIPTS = { const LAYERING_FIXTURES = join(SRC, '__tests__', 'fixtures', 'layering'); // The packages of the split, in the layering's order. -const PACKAGES = ['core', 'chain', 'wallet', 'contract', 'connect', 'swap', 'dev', 'grant']; +const PACKAGES = ['core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'grant']; // Which package a file belongs to: the first pattern that matches its path // under src/ wins. A file that matches nothing fails the check. @@ -85,6 +85,9 @@ const HOMES = [ ['wallet', /^lib\/(dust-[a-z-]+|shielded-[a-z-]+)\.ts$/], ['wallet', /^lib\/wallet\//], ['wallet', /^ui\/receipt\.ts$/], + // Swap is the wallet's: its offers are made, taken and cancelled by a wallet. + ['wallet', /^commands\/swap(\.definition|\.guidance)?\.ts$/], + ['wallet', /^lib\/swap\//], ['contract', /^commands\/(contract|inspect-cost)(\.definition)?\.ts$/], ['contract', /^lib\/contract\//], @@ -93,9 +96,6 @@ const HOMES = [ ['connect', /^commands\/serve(\.definition)?\.ts$/], ['connect', /^lib\/(dapp-connector|ws-rpc|sign-recipe|serve-manager|serve-payer)\.ts$/], - ['swap', /^commands\/swap(\.definition)?\.ts$/], - ['swap', /^lib\/swap\//], - ['dev', /^commands\/(dev|test|localnet)(\.definition)?\.ts$/], ['dev', /^lib\/localnet\.ts$/], ['dev', /^lib\/(dev|test)\//], @@ -106,7 +106,7 @@ const HOMES = [ // The packages each package may import, its own included. Dependencies point // one way: core, chain, wallet, then contract and connect side by side, then -// swap (on connect's wallet session), then dev, then grant. An engine sits beside chain: it uses core and chain, and +// dev, then grant. An engine sits beside chain: it uses core and chain, and // nothing imports it but core's loader. const MAY_IMPORT = { engine: ['core', 'chain', 'engine'], @@ -115,7 +115,6 @@ const MAY_IMPORT = { wallet: ['core', 'chain', 'wallet'], contract: ['core', 'chain', 'wallet', 'contract'], connect: ['core', 'chain', 'wallet', 'connect'], - swap: ['core', 'chain', 'wallet', 'connect', 'swap'], dev: ['core', 'chain', 'wallet', 'contract', 'connect', 'dev'], grant: ['core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'grant'], // The shell installs every package's commands and guidance, picks the payer @@ -154,6 +153,7 @@ const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|^\s*import\s+)(['"])([^'"]+)\1/gm; export const WORKSPACE_PACKAGES = [ { name: '@kuiralabs/midnight-cli-core', root: join(ROOT, 'packages', 'cli-core'), dir: join(ROOT, 'packages', 'cli-core', 'src'), home: 'core' }, { name: '@kuiralabs/midnight-chain', root: join(ROOT, 'packages', 'chain'), dir: join(ROOT, 'packages', 'chain', 'src'), home: 'chain' }, + { name: '@kuiralabs/midnight-wallet', root: join(ROOT, 'packages', 'wallet'), dir: join(ROOT, 'packages', 'wallet', 'src'), home: 'wallet' }, // The rc engine: its files read as engine/rc/, its index the package itself. { name: '@kuiralabs/midnight-engine-rc', root: join(ROOT, 'packages', 'engine-rc'), dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/', home: 'engine' }, { name: '@kuiralabs/midnight-engine-beta', root: join(ROOT, 'packages', 'engine-beta'), dir: join(ROOT, 'packages', 'engine-beta', 'src'), prefix: 'engine/beta/', home: 'engine' }, diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 752443d3..72daca8a 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -270,6 +270,7 @@ try { ['@kuiralabs/midnight-chain', 'lib/chain-id'], ['@kuiralabs/midnight-engine-rc', 'derive-address'], ['@kuiralabs/midnight-engine-beta', 'derive-address'], + ['@kuiralabs/midnight-wallet', 'lib/passphrase'], ]) { check(`a program outside mn finds ${name}'s ${deepPath} built`, existsSync(join(outside, 'node_modules', name, 'dist', `${deepPath}.js`))); const deep = run(process.execPath, ['entry.mjs', `${name}/${deepPath}`], outside).trim(); diff --git a/src/__tests__/account-backup.test.ts b/src/__tests__/account-backup.test.ts index 99b7ccf4..b535a33d 100644 --- a/src/__tests__/account-backup.test.ts +++ b/src/__tests__/account-backup.test.ts @@ -13,14 +13,14 @@ import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { type FeeWallet, accountProviders, freshOwnerDevice } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_ID } from '@kuiralabs/midnight-account-chain/contract'; -import { WrongPassphraseError, getNetworkConfig, createHost } from '@kuiralabs/midnight-cli-core'; -import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; +import { WrongPassphraseError, getNetworkConfig, createHost, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; +import { establishPassphrase } from '@kuiralabs/midnight-wallet'; import { openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { exportAccount, importAccount } from '../lib/grant/account-backup.ts'; import { createPendingDevice, openAccountKey, ownDeviceCode, sealedDeviceList } from '../lib/grant/sealed-account.ts'; import { parseDeviceCode } from '../lib/grant/device-code.ts'; import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStatePassword } from '../lib/grant/sealed-account.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. diff --git a/src/__tests__/address-command.test.ts b/src/__tests__/address-command.test.ts index db6308ad..fb9233eb 100644 --- a/src/__tests__/address-command.test.ts +++ b/src/__tests__/address-command.test.ts @@ -2,11 +2,14 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import addressCommand from '../commands/address.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { addressDefinition } from '@kuiralabs/midnight-wallet/commands'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: addressCommand } = await addressDefinition.load(); + const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; const TEST_DIR = path.join(os.tmpdir(), `midnight-address-cmd-test-${process.pid}`); diff --git a/src/__tests__/agent-guidance.test.ts b/src/__tests__/agent-guidance.test.ts index e73306bd..0f953a49 100644 --- a/src/__tests__/agent-guidance.test.ts +++ b/src/__tests__/agent-guidance.test.ts @@ -179,9 +179,11 @@ describe('the installed packages\' guidance', () => { }); it('lives in one file beside its package\'s commands, which the layering check places in that package', () => { + // Swap's commands and guidance are a registry entry of their own (help and the manual list them apart) and live in the wallet package. + const packageOf = (entry: string) => (entry === 'swap' ? 'wallet' : entry); for (const pkg of installedCommands.packages.filter((p) => p.name !== 'shell')) { - expect(homeOf(join(SRC, 'commands', `${pkg.name}.guidance.ts`))).toBe(pkg.name); - for (const command of pkg.commands) expect([command.name, homeOf(join(SRC, 'commands', `${command.name}.definition.ts`))]).toStrictEqual([command.name, pkg.name]); + expect(homeOf(join(SRC, 'commands', `${pkg.name}.guidance.ts`))).toBe(packageOf(pkg.name)); + for (const command of pkg.commands) expect([command.name, homeOf(join(SRC, 'commands', `${command.name}.definition.ts`))]).toStrictEqual([command.name, packageOf(pkg.name)]); } }); diff --git a/src/__tests__/airdrop-command.test.ts b/src/__tests__/airdrop-command.test.ts index 980456d6..444336f7 100644 --- a/src/__tests__/airdrop-command.test.ts +++ b/src/__tests__/airdrop-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import airdropCommand from '../commands/airdrop.ts'; import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { airdropDefinition } from '@kuiralabs/midnight-wallet/commands'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; @@ -9,6 +9,9 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: airdropCommand } = await airdropDefinition.load(); + const TEST_DIR = path.join(os.tmpdir(), `midnight-airdrop-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; diff --git a/src/__tests__/balance-command.live.test.ts b/src/__tests__/balance-command.live.test.ts index 2cd95b95..83691d57 100644 --- a/src/__tests__/balance-command.live.test.ts +++ b/src/__tests__/balance-command.live.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest'; -import balanceCommand from '../commands/balance.ts'; import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { testHost } from '../../test-support/test-host.ts'; @@ -10,6 +10,9 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: balanceCommand } = await balanceDefinition.load(); + // Live tests against a running ledger-9 indexer: run by `npm run test:live`, // never by `npm test`. They read balances only, from undeployed's saved // endpoints (`midnight config set ...`) or the defaults, never docker diff --git a/src/__tests__/balance-command.test.ts b/src/__tests__/balance-command.test.ts index 00b6efee..4233be29 100644 --- a/src/__tests__/balance-command.test.ts +++ b/src/__tests__/balance-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import balanceCommand from '../commands/balance.ts'; import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; @@ -9,6 +9,9 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: balanceCommand } = await balanceDefinition.load(); + // The balance command's checks that need no chain. Those that read a live // indexer are in balance-command.live.test.ts (npm run test:live). diff --git a/src/__tests__/chain-reset-clearing.test.ts b/src/__tests__/chain-reset-clearing.test.ts index 5f29ab5f..150ad55d 100644 --- a/src/__tests__/chain-reset-clearing.test.ts +++ b/src/__tests__/chain-reset-clearing.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { clearChainCaches } from '../lib/chain-caches.ts'; +import { clearChainCaches } from '@kuiralabs/midnight-wallet'; import { getCachePath, getDustCachePath, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/engine'; import { PRIVATE_STATE_DATABASE, clearDappPrivateState } from '../lib/contract/private-state.ts'; diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 81c0d970..21e7bf2b 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -17,26 +17,26 @@ import { Buffer } from 'node:buffer'; import { parseArgs, type Prompter, type CommandHandler } from '@kuiralabs/midnight-cli-core'; import { getCachePath } from '@kuiralabs/midnight-cli-core/engine'; import { installedCommands } from '../lib/installed-commands.ts'; -import { establishPassphrase, isPassphraseSet } from '../lib/passphrase.ts'; +import { establishPassphrase, isPassphraseSet, loadWalletConfig, protectAllWallets, createWallet, walletSecretFrom, type WalletProtector } from '@kuiralabs/midnight-wallet'; import { rcKeys } from '../../test-support/rc-engine.ts'; -import { loadWalletConfig, protectAllWallets } from '../lib/wallet-config.ts'; -import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; -import type { WalletProtector } from '../lib/wallet-protector.ts'; -import balanceCommand from '../commands/balance.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; import { statusDefinition } from '@kuiralabs/midnight-chain/commands'; -import generateCommand from '../commands/generate.ts'; -import walletCommand from '../commands/wallet.ts'; -import cacheCommand from '../commands/cache.ts'; +import { balanceDefinition, generateDefinition, walletDefinition, cacheDefinition } from '@kuiralabs/midnight-wallet/commands'; import testCommand from '../commands/test.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; import { testHost } from '../../test-support/test-host.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; +// The handlers, as the shell loads them. +const { default: balanceCommand } = await balanceDefinition.load(); +const { default: generateCommand } = await generateDefinition.load(); +const { default: walletCommand } = await walletDefinition.load(); +const { default: cacheCommand } = await cacheDefinition.load(); + // The status handler, as the shell loads it. const { default: statusCommand } = await statusDefinition.load(); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index ce608a7c..c46bc529 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -14,7 +14,7 @@ import { confirmationText, createCommandRegistry, commandHelpSpecs, introBriefs, import { CONFIRM_TOOL, listedTools } from '../lib/mcp/registry-tools.ts'; import { commandNeedsWalletSdk, dispatchCommand, type ShellProvisions } from '../lib/command-dispatch.ts'; import { testHost } from '../../test-support/test-host.ts'; -import type { WalletProtector } from '../lib/wallet-protector.ts'; +import type { WalletProtector } from '@kuiralabs/midnight-wallet'; const SRC = join(import.meta.dirname, '..'); const registry = installedCommands; diff --git a/src/__tests__/config-command.test.ts b/src/__tests__/config-command.test.ts index d81e10f0..ee1d9cdc 100644 --- a/src/__tests__/config-command.test.ts +++ b/src/__tests__/config-command.test.ts @@ -6,7 +6,7 @@ import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { parseArgs, loadCliConfig } from '@kuiralabs/midnight-cli-core'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; // The config handler, as the shell loads it. const { default: configCommand } = await configDefinition.load(); diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 8fdb7122..5deca6a4 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -10,7 +10,7 @@ import { contractDeployRequest } from '../lib/contract/request.ts'; import { deployContract } from '../lib/contract/deploy.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; import { createSdkWarningRouter, CancelledError, createHost, type Host } from '@kuiralabs/midnight-cli-core'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; const ENDPOINTS = { network: 'undeployed' as const, node: 'ws://localhost:29944', indexerWS: 'ws://localhost:28088/api/v4/graphql/ws', proofServer: 'http://localhost:26300' }; diff --git a/src/__tests__/declared-codes.test.ts b/src/__tests__/declared-codes.test.ts index 45e73f59..fe100d29 100644 --- a/src/__tests__/declared-codes.test.ts +++ b/src/__tests__/declared-codes.test.ts @@ -24,7 +24,7 @@ import { refusalCodeOf, toEngineError } from '@kuiralabs/midnight-cli-core/engin import { ContractScriptError, SCRIPT_ERROR_MARKER, scriptFailureOf } from '../lib/contract/runner.ts'; import { PrepStepFailedError } from '../lib/test/prep-runner.ts'; import { installedCommands } from '../lib/installed-commands.ts'; -import { WalletNotFoundError } from '../lib/wallet-config.ts'; +import { WalletNotFoundError } from '@kuiralabs/midnight-wallet'; import { expectDeclared, expectDeclaredToolResult } from './helpers/expect-declared.ts'; import { fixtureDefinition } from './fixtures/code-reach/fixture.definition.ts'; import { barrelFixtureDefinition } from './fixtures/code-reach/barrel.definition.ts'; diff --git a/src/__tests__/dust-command.test.ts b/src/__tests__/dust-command.test.ts index 4975a79f..c9895bbb 100644 --- a/src/__tests__/dust-command.test.ts +++ b/src/__tests__/dust-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import dustCommand from '../commands/dust.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { dustDefinition } from '@kuiralabs/midnight-wallet/commands'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; @@ -9,6 +9,9 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: dustCommand } = await dustDefinition.load(); + const TEST_DIR = path.join(os.tmpdir(), `midnight-dust-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; diff --git a/src/__tests__/entry-points.test.ts b/src/__tests__/entry-points.test.ts index 80f8a507..2ad75384 100644 --- a/src/__tests__/entry-points.test.ts +++ b/src/__tests__/entry-points.test.ts @@ -16,6 +16,7 @@ const ENTRY_POINTS: Record = { chain: ['.', './commands'], 'engine-rc': ['.'], 'engine-beta': ['.'], + wallet: ['.', './commands'], }; describe('the public entry points', () => { diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index 351c3d04..9a45db0f 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -34,29 +34,27 @@ import { LocalStackUnreachableError, UnsupportedLedgerError, ChainClockBehindErr import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import { rcKeys } from '../../test-support/rc-engine.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; -import { readPassphrase } from '../lib/passphrase.ts'; -import { assertWalletFileExists, assertWalletRemovable, setActiveWallet } from '../lib/wallet-config.ts'; -import { walletSecretFrom } from '../lib/wallet-create.ts'; -import { resolveTransferRequest } from '../lib/transfer-request.ts'; -import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; +import { readPassphrase, assertWalletFileExists, assertWalletRemovable, setActiveWallet, walletSecretFrom, assertWalletCanPay, NoSuchOfferError } from '@kuiralabs/midnight-wallet'; +import { walletDefinition, generateDefinition, addressDefinition, airdropDefinition, balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; import { PrepStepFailedError, runPrepSteps } from '../lib/test/prep-runner.ts'; import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import walletCommand from '../commands/wallet.ts'; -import generateCommand from '../commands/generate.ts'; -import addressCommand from '../commands/address.ts'; -import airdropCommand from '../commands/airdrop.ts'; -import balanceCommand from '../commands/balance.ts'; import { cliCall } from './helpers/cli-call.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; import { UnsupportedNodeError } from '../lib/node-version.ts'; import { LocalnetUnavailableError } from '../lib/localnet.ts'; import { scriptRuntime } from '../lib/contract/runner.ts'; -import { NoSuchOfferError } from '../lib/swap/offers.ts'; import { NoAccountError } from '../lib/grant/prepare.ts'; import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; import { installedCommands } from '../lib/installed-commands.ts'; +// The handlers, as the shell loads them. +const { default: walletCommand } = await walletDefinition.load(); +const { default: generateCommand } = await generateDefinition.load(); +const { default: addressCommand } = await addressDefinition.load(); +const { default: airdropCommand } = await airdropDefinition.load(); +const { default: balanceCommand } = await balanceDefinition.load(); + let root: string; beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'mn-code-parity-')); @@ -172,7 +170,7 @@ const ROWS: Row[] = [ ['airdrop with no amount', run(airdropCommand, 'airdrop'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], ["balance of an address on another network than --network", run(balanceCommand, 'balance', OTHER_ADDRESSES.undeployed, '--network', 'preprod'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], ["the shielded balance of someone else's address", run(balanceCommand, 'balance', OTHER_ADDRESSES.preview, '--shielded', '--network', 'preview'), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], - ['a shielded transfer where shielded is off', () => resolveTransferRequest(parseArgs(['transfer', rcKeys.shieldedAddresses(SEED).preprod, '1', '--wallet', 'alice', '--shielded', '--network', 'preprod']), root, hostOnRoot()), as('INVALID_ARGS', 2), as('INVALID_ARGS', 2)], + // A shielded transfer where shielded is off is refused by the wallet's transfer request: its row is in the wallet's tests (transfer-request.test.ts). // No such wallet: exit 3, by its message. ['no wallet of that name', () => setActiveWallet(root, 'nobody'), as('WALLET_NOT_FOUND', 3), as('WALLET_NOT_FOUND', 3)], diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 27d6f471..750efb5e 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -3,7 +3,7 @@ import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, E import { MixedSdkLayoutError, toEngineError } from '@kuiralabs/midnight-cli-core/engine'; import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; import { NoAccountError } from '../lib/grant/prepare.ts'; -import { NoPassphraseError } from '../lib/passphrase.ts'; +import { NoPassphraseError } from '@kuiralabs/midnight-wallet'; import { installedCommands } from '../lib/installed-commands.ts'; describe('humanizeNetworkError', () => { diff --git a/src/__tests__/generate-command.test.ts b/src/__tests__/generate-command.test.ts index bf94771c..cc2a7429 100644 --- a/src/__tests__/generate-command.test.ts +++ b/src/__tests__/generate-command.test.ts @@ -1,17 +1,19 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { mnemonicToSeedSync } from '@scure/bip39'; -import generateCommand from '../commands/generate.ts'; -import { unlockWallet } from '../lib/wallet-config.ts'; -import { PASSPHRASE_ENV } from '../lib/passphrase.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { unlockWallet } from '@kuiralabs/midnight-wallet'; +import { parseArgs, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; +import { generateDefinition } from '@kuiralabs/midnight-wallet/commands'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { testHost } from '../../test-support/test-host.ts'; +// The handler, as the shell loads it. +const { default: generateCommand } = await generateDefinition.load(); + // The host the tests' calls run in (test-host.ts): settings from the test's environment, nobody to ask, notices dropped. const host = testHost(); diff --git a/src/__tests__/genesis-address-command.test.ts b/src/__tests__/genesis-address-command.test.ts index f8dc5b95..868bdd70 100644 --- a/src/__tests__/genesis-address-command.test.ts +++ b/src/__tests__/genesis-address-command.test.ts @@ -1,9 +1,12 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import genesisAddressCommand from '../commands/genesis-address.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core'; +import { genesisAddressDefinition } from '@kuiralabs/midnight-wallet/commands'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: genesisAddressCommand } = await genesisAddressDefinition.load(); + let io: CapturedOutput; beforeEach(() => { diff --git a/src/__tests__/grant-account.test.ts b/src/__tests__/grant-account.test.ts index 06e5cca4..3c0c4c23 100644 --- a/src/__tests__/grant-account.test.ts +++ b/src/__tests__/grant-account.test.ts @@ -8,11 +8,11 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { WrongPassphraseError, getNetworkConfig, createHost } from '@kuiralabs/midnight-cli-core'; -import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; +import { WrongPassphraseError, getNetworkConfig, createHost, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; +import { establishPassphrase } from '@kuiralabs/midnight-wallet'; import { openGrantAccount } from '../lib/grant/account.ts'; import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. diff --git a/src/__tests__/handler-library-calls.test.ts b/src/__tests__/handler-library-calls.test.ts index 948e3735..f33cf040 100644 --- a/src/__tests__/handler-library-calls.test.ts +++ b/src/__tests__/handler-library-calls.test.ts @@ -15,12 +15,12 @@ const ROOT = join(import.meta.dirname, '..', '..'); /** Each handler in scope, and the library function of each of its operations. */ const HANDLERS: Record = { - 'src/commands/balance.ts': ['readAddressBalance', 'readWalletBalance'], - 'src/commands/transfer.ts': ['transferNight'], - 'src/commands/airdrop.ts': ['airdropNight'], - 'src/commands/dust.ts': ['readDustStatus', 'registerDust', 'exportDustSnapshot'], + 'packages/wallet/src/commands/balance.ts': ['readAddressBalance', 'readWalletBalance'], + 'packages/wallet/src/commands/transfer.ts': ['transferNight'], + 'packages/wallet/src/commands/airdrop.ts': ['airdropNight'], + 'packages/wallet/src/commands/dust.ts': ['readDustStatus', 'registerDust', 'exportDustSnapshot'], 'src/commands/contract.ts': ['deployContract', 'callContract', 'readContractState'], - 'src/commands/swap.ts': ['makeSwapOffer', 'inspectSwapOffer', 'takeSwapOffer', 'cancelSwapOffer', 'listSwapOffers'], + 'packages/wallet/src/commands/swap.ts': ['makeSwapOffer', 'inspectSwapOffer', 'takeSwapOffer', 'cancelSwapOffer', 'listSwapOffers'], 'packages/chain/src/commands/tx.ts': ['transactionStatus'], }; diff --git a/src/__tests__/host-paths.test.ts b/src/__tests__/host-paths.test.ts index 6ad80ec0..32a3cc26 100644 --- a/src/__tests__/host-paths.test.ts +++ b/src/__tests__/host-paths.test.ts @@ -7,15 +7,12 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host, parseArgs, MIDNIGHT_DIR, loadCliConfig, sdkSetOf, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; +import { createHost, type Host, parseArgs, MIDNIGHT_DIR, loadCliConfig, sdkSetOf, readOpenOffers, recordOpenOffer, type OpenOffer, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; import { cacheRootDir, getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/engine'; import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { captureCommand } from '../lib/run-command.ts'; import { installedCommands } from '../lib/installed-commands.ts'; -import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; -import { getActiveWalletName, listWallets } from '../lib/wallet-config.ts'; -import { PASSPHRASE_ENV, passphraseForNewSecret } from '../lib/passphrase.ts'; -import { clearChainCaches } from '../lib/chain-caches.ts'; +import { createWallet, walletSecretFrom, getActiveWalletName, listWallets, clearChainCaches, passphraseForNewSecret } from '@kuiralabs/midnight-wallet'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The config handler, as the shell loads it. diff --git a/src/__tests__/host-slots.test.ts b/src/__tests__/host-slots.test.ts index 09f5452a..10c2e527 100644 --- a/src/__tests__/host-slots.test.ts +++ b/src/__tests__/host-slots.test.ts @@ -9,15 +9,14 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { WebSocket } from 'ws'; -import { createHost, type Host, type Prompter } from '@kuiralabs/midnight-cli-core'; +import { createHost, type Host, type Prompter, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; import { promptApproval } from '@kuiralabs/midnight-cli-core/engine'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import { NoPassphraseError, PASSPHRASE_ENV, establishPassphrase, unlockPassphrase } from '../lib/passphrase.ts'; -import { unlockWallet } from '../lib/wallet-config.ts'; +import { NoPassphraseError, establishPassphrase, unlockPassphrase, unlockWallet } from '@kuiralabs/midnight-wallet'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; const PASSPHRASE = 'correct horse battery staple'; const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; diff --git a/src/__tests__/info-command.test.ts b/src/__tests__/info-command.test.ts index 8078cef8..e9516f75 100644 --- a/src/__tests__/info-command.test.ts +++ b/src/__tests__/info-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import infoCommand from '../commands/info.ts'; import { parseArgs } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { infoDefinition } from '@kuiralabs/midnight-wallet/commands'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; @@ -9,6 +9,9 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: infoCommand } = await infoDefinition.load(); + const TEST_DIR = path.join(os.tmpdir(), `midnight-info-cmd-test-${process.pid}`); const TEST_SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index 7bd58d24..a363a49e 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -8,18 +8,21 @@ import * as path from 'path'; import * as os from 'os'; // Commands that can be tested without network/Docker -import generateCommand from '../commands/generate.ts'; -import infoCommand from '../commands/info.ts'; -import addressCommand from '../commands/address.ts'; -import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; +import { generateDefinition, infoDefinition, addressDefinition, genesisAddressDefinition } from '@kuiralabs/midnight-wallet/commands'; import helpCommand from '../commands/help.ts'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { localIndexerFlags } from '../../test-support/local-indexer.ts'; import { cliCall } from './helpers/cli-call.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; + +// The handlers, as the shell loads them. +const { default: generateCommand } = await generateDefinition.load(); +const { default: infoCommand } = await infoDefinition.load(); +const { default: addressCommand } = await addressDefinition.load(); +const { default: genesisAddressCommand } = await genesisAddressDefinition.load(); // The config handler, as the shell loads it. const { default: configCommand } = await configDefinition.load(); diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index 7c065e31..5c2cda79 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -13,13 +13,12 @@ import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { parseArgs, type CommandHandler } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; -import { establishPassphrase } from '../lib/passphrase.ts'; -import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; +import { establishPassphrase, createWallet, walletSecretFrom } from '@kuiralabs/midnight-wallet'; import { servePayerAt } from '../lib/serve-payer.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { testHost } from '../../test-support/test-host.ts'; const PASSPHRASE = 'correct horse battery staple'; diff --git a/src/__tests__/notices.test.ts b/src/__tests__/notices.test.ts index 19a07dea..78d6ddc9 100644 --- a/src/__tests__/notices.test.ts +++ b/src/__tests__/notices.test.ts @@ -9,9 +9,9 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { createHost } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import { unlockWallet } from '../lib/wallet-config.ts'; +import { unlockWallet } from '@kuiralabs/midnight-wallet'; import { rcKeys } from '../../test-support/rc-engine.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; const ROOT = path.resolve(import.meta.dirname, '..', '..'); const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; diff --git a/src/__tests__/package-metadata.test.ts b/src/__tests__/package-metadata.test.ts index f9857039..231db02c 100644 --- a/src/__tests__/package-metadata.test.ts +++ b/src/__tests__/package-metadata.test.ts @@ -56,7 +56,7 @@ describe('the SDK in the manifests', () => { } }); - it('is no dependency of core or chain', () => { - for (const dir of ['cli-core', 'chain']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); + it('is no dependency of core, chain or wallet', () => { + for (const dir of ['cli-core', 'chain', 'wallet']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); }); }); diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index df4268e1..344d306e 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -12,11 +12,11 @@ import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; import { NoAccountError } from '../lib/grant/prepare.ts'; import { servePayerAt } from '../lib/serve-payer.ts'; import { probeServeNetwork } from '../lib/serve-manager.ts'; -import { assertWalletCanPay } from '../lib/wallet-can-pay.ts'; +import { assertWalletCanPay } from '@kuiralabs/midnight-wallet'; import contractCommand from '../commands/contract.ts'; import grantCommand from '../commands/grant.ts'; import { cliCall } from './helpers/cli-call.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/protect-account.test.ts b/src/__tests__/protect-account.test.ts index 407176e9..fc903e89 100644 --- a/src/__tests__/protect-account.test.ts +++ b/src/__tests__/protect-account.test.ts @@ -12,12 +12,12 @@ import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { type FeeWallet, accountProviders, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_ID } from '@kuiralabs/midnight-account-chain/contract'; -import { PASSPHRASE_ENV, establishPassphrase } from '../lib/passphrase.ts'; -import { getNetworkConfig, createHost } from '@kuiralabs/midnight-cli-core'; +import { establishPassphrase } from '@kuiralabs/midnight-wallet'; +import { getNetworkConfig, createHost, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; import { LEGACY_STORE_PASSWORD, openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { AccountMigrationInterruptedError, protectAccount } from '../lib/grant/protect-account.ts'; import { isSealedAccount } from '../lib/grant/sealed-account.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. diff --git a/src/__tests__/provision-wallets.test.ts b/src/__tests__/provision-wallets.test.ts index d52ea585..d1f9d627 100644 --- a/src/__tests__/provision-wallets.test.ts +++ b/src/__tests__/provision-wallets.test.ts @@ -8,7 +8,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { provisionDevWallets, type ProvisionSteps } from '../lib/dev/provision-wallets.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; let home: string; let originalHome: string | undefined; diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index 2d355180..5e81e239 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -2,22 +2,25 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { captureCommand } from '../lib/run-command.ts'; import { SecondResultError, type CommandHandler, CancelledError, CommandFailedError, classifyError, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; +import { generateDefinition, infoDefinition, addressDefinition, genesisAddressDefinition } from '@kuiralabs/midnight-wallet/commands'; import { installedCommands } from '../lib/installed-commands.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import generateCommand from '../commands/generate.ts'; -import infoCommand from '../commands/info.ts'; -import addressCommand from '../commands/address.ts'; -import genesisAddressCommand from '../commands/genesis-address.ts'; import inspectCostCommand from '../commands/inspect-cost.ts'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { localIndexerFlags } from '../../test-support/local-indexer.ts'; import { ownCall } from './helpers/own-call.ts'; +// The handlers, as the shell loads them. +const { default: generateCommand } = await generateDefinition.load(); +const { default: infoCommand } = await infoDefinition.load(); +const { default: addressCommand } = await addressDefinition.load(); +const { default: genesisAddressCommand } = await genesisAddressDefinition.load(); + const TEST_DIR = path.join(os.tmpdir(), `midnight-run-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; diff --git a/src/__tests__/serve-manager.test.ts b/src/__tests__/serve-manager.test.ts index 0d310ff9..b9b777ae 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/src/__tests__/serve-manager.test.ts @@ -9,8 +9,8 @@ import * as path from 'node:path'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; import { createSdkWarningRouter, createHost } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 5e358c50..dad92047 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -8,13 +8,12 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { NoStateRootError, createHost, parseArgs, setConfigValue, MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core'; +import { NoStateRootError, createHost, parseArgs, setConfigValue, MIDNIGHT_DIR, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; import { bindCachesToIndexer, getCachePath, getDustCachePath, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/engine'; import { testHost } from '../../test-support/test-host.ts'; import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { cliCall } from './helpers/cli-call.ts'; -import { passphraseForNewSecret, PASSPHRASE_ENV } from '../lib/passphrase.ts'; -import { createWallet, walletSecretFrom } from '../lib/wallet-create.ts'; +import { passphraseForNewSecret, createWallet, walletSecretFrom } from '@kuiralabs/midnight-wallet'; import { accountRecordsDir } from '../lib/grant/account-records.ts'; import { accountArtifactsDir } from '../lib/grant/account.ts'; import { getComposePath } from '../lib/localnet.ts'; diff --git a/src/__tests__/swap-command.test.ts b/src/__tests__/swap-command.test.ts index 8d96db2f..f765b1b5 100644 --- a/src/__tests__/swap-command.test.ts +++ b/src/__tests__/swap-command.test.ts @@ -8,11 +8,14 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { parseArgs, encodeOfferEnvelope, type ConnectOptions, type Payer } from '@kuiralabs/midnight-cli-core'; -import swapCommand from '../commands/swap.ts'; +import { swapDefinition } from '@kuiralabs/midnight-wallet/commands'; import { cliCall } from './helpers/cli-call.ts'; import { OFFER_GIVE, OFFER_WANT, SWAP_OFFER_HEX } from '../../test-support/fixtures/swap-offer.ts'; import { rcEngine } from '../../test-support/rc-engine.ts'; +// The handler, as the shell loads it. +const { default: swapCommand } = await swapDefinition.load(); + const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; const TERMS = ['--give', '10', '--give-token', OFFER_GIVE, '--want', '7', '--want-token', OFFER_WANT]; diff --git a/src/__tests__/transfer-command.test.ts b/src/__tests__/transfer-command.test.ts index 1c2964c7..a5d7fe3a 100644 --- a/src/__tests__/transfer-command.test.ts +++ b/src/__tests__/transfer-command.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import transferCommand from '../commands/transfer.ts'; import { parseArgs, GENESIS_SEED } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from './helpers/plain-wallet.ts'; +import { transferDefinition } from '@kuiralabs/midnight-wallet/commands'; +import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import * as fs from 'fs'; @@ -9,6 +9,9 @@ import * as path from 'path'; import * as os from 'os'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: transferCommand } = await transferDefinition.load(); + const TEST_DIR = path.join(os.tmpdir(), `midnight-transfer-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; diff --git a/src/__tests__/two-hosts.test.ts b/src/__tests__/two-hosts.test.ts index b343d618..d598fb21 100644 --- a/src/__tests__/two-hosts.test.ts +++ b/src/__tests__/two-hosts.test.ts @@ -17,7 +17,7 @@ import { createHost, type Host, parseArgs, MIDNIGHT_DIR, settingsFromEnvironment import { dispatchCommand } from '../lib/command-dispatch.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -import { checkPassphrase } from '../lib/passphrase.ts'; +import { checkPassphrase } from '@kuiralabs/midnight-wallet'; const PASSPHRASE_A = 'host A passphrase, twelve or more'; const PASSPHRASE_B = 'host B passphrase, twelve or more'; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index 42b6f517..be5b3e73 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -12,11 +12,14 @@ import { captureCommand } from '../lib/run-command.ts'; import { callDiagnostics, parseArgs, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import balanceCommand from '../commands/balance.ts'; +import { balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { ownCall } from './helpers/own-call.ts'; import { testHost } from '../../test-support/test-host.ts'; +// The handler, as the shell loads it. +const { default: balanceCommand } = await balanceDefinition.load(); + // One host for every call, as the MCP server has: its notices are where verbose lines go. const host = testHost({ notice: (line) => notices.push(line) }); diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index db1d7ec2..a3d03616 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -9,19 +9,20 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import walletCommand from '../commands/wallet.ts'; -import { parseArgs } from '@kuiralabs/midnight-cli-core'; -import { PASSPHRASE_ENV, isPassphraseSet } from '../lib/passphrase.ts'; -import { loadWalletConfig } from '../lib/wallet-config.ts'; +import { parseArgs, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; +import { isPassphraseSet, loadWalletConfig, type WalletProtector } from '@kuiralabs/midnight-wallet'; +import { walletDefinition } from '@kuiralabs/midnight-wallet/commands'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; -import { saveWalletConfig } from './helpers/plain-wallet.ts'; +import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; import { accountProtector } from '../lib/grant/account-protector.ts'; -import type { WalletProtector } from '../lib/wallet-protector.ts'; -import { stateRootIn } from './helpers/state-root-in.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; import { cliCall } from './helpers/cli-call.ts'; import { testHost } from '../../test-support/test-host.ts'; +// The handler, as the shell loads it. +const { default: walletCommand } = await walletDefinition.load(); + const PASSPHRASE = 'correct horse battery staple'; const SEED = 'aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233'; const ORIGINAL_HOME = process.env.HOME; diff --git a/src/commands/contract.definition.ts b/src/commands/contract.definition.ts index 8956fda2..8bb65751 100644 --- a/src/commands/contract.definition.ts +++ b/src/commands/contract.definition.ts @@ -3,14 +3,14 @@ import { type CommandDefinition, ENDPOINT_PARAMS, NETWORK_PARAM, confirmationTarget, type HostEngines } from '@kuiralabs/midnight-cli-core'; import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; -import { OPENS_WALLET } from './wallet.codes.ts'; +import { OPENS_WALLET } from '@kuiralabs/midnight-wallet/commands'; /** The subcommands that reach a chain: inspect reads only the compiled contract (--path, --managed, --name). */ const ON_CHAIN: readonly string[] = ['deploy', 'call', 'state']; /** The wallet a deploy or call pays from, under the state root `root`, exists and can be read (with the host's `engines`). */ async function checkSendingWallet(params: Readonly>, root: string, engines: HostEngines): Promise { - const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); + const { loadWalletConfig, resolveWalletPath } = await import('@kuiralabs/midnight-wallet'); await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined), engines); } diff --git a/src/commands/contract.ts b/src/commands/contract.ts index 5cca5ab2..1cc5b187 100644 --- a/src/commands/contract.ts +++ b/src/commands/contract.ts @@ -6,7 +6,7 @@ import { header, keyValue, bold, dim, teal, yellow, green, spinnerReporter } fro import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { readContractState } from '../lib/contract/state.ts'; -import { showPaidStep } from '../lib/wallet/paid-call.ts'; +import { showPaidStep } from '@kuiralabs/midnight-wallet/commands'; import { resolveContractCallRequest, resolveContractDeployRequest, resolveDappDir, resolveScanDir } from '../lib/contract/request.ts'; import { findContractInfo, diff --git a/src/commands/dev.definition.ts b/src/commands/dev.definition.ts index 4ac5cc83..5a7728cc 100644 --- a/src/commands/dev.definition.ts +++ b/src/commands/dev.definition.ts @@ -3,7 +3,7 @@ import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; -import { OPENS_WALLET } from './wallet.codes.ts'; +import { OPENS_WALLET } from '@kuiralabs/midnight-wallet/commands'; export const devDefinition: CommandDefinition = { name: 'dev', diff --git a/src/commands/dev.ts b/src/commands/dev.ts index 2717ba17..fd3a4eb7 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -5,7 +5,7 @@ import { resolve, relative } from 'node:path'; import { type ParsedArgs, payerFor, type CallContext, type CallOutput } from '@kuiralabs/midnight-cli-core'; import { header, divider, keyValue, bold, dim, red, teal, yellow } from '@kuiralabs/midnight-cli-core/ui'; -import { isPassphraseSet, unlockPassphrase } from '../lib/passphrase.ts'; +import { isPassphraseSet, unlockPassphrase } from '@kuiralabs/midnight-wallet'; import { detectProject, type ProjectInfo } from '../lib/dev/detect-project.ts'; import { runCompile, type CompileResult } from '../lib/dev/compile.ts'; import { runTests } from '../lib/dev/test.ts'; diff --git a/src/commands/grant.definition.ts b/src/commands/grant.definition.ts index fc98bd76..daf2317f 100644 --- a/src/commands/grant.definition.ts +++ b/src/commands/grant.definition.ts @@ -3,14 +3,14 @@ import { type CommandDefinition, type ToolCheckCall, ENDPOINT_PARAMS, confirmationTarget } from '@kuiralabs/midnight-cli-core'; import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; -import { OPENS_WALLET } from './wallet.codes.ts'; +import { OPENS_WALLET } from '@kuiralabs/midnight-wallet/commands'; /** A grant request can run: its arguments, the network, the account and the wallet are all in order. */ async function checkGrant(params: Readonly>, call: ToolCheckCall) { const { prepareGrant } = await import('../lib/grant/prepare.ts'); const root = call.host.paths().stateRoot; const prepared = await prepareGrant(call.argv(), root, call.host); - const { loadWalletConfig, resolveWalletPath } = await import('../lib/wallet-config.ts'); + const { loadWalletConfig, resolveWalletPath } = await import('@kuiralabs/midnight-wallet'); await loadWalletConfig(resolveWalletPath(root, params.wallet as string | undefined), call.host.engines); return prepared; } diff --git a/src/commands/grant.ts b/src/commands/grant.ts index 0375f1cc..12ae38b4 100644 --- a/src/commands/grant.ts +++ b/src/commands/grant.ts @@ -87,7 +87,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, // This machine's device, made where no account is yet: it opens no account first. if (request.subcommand === 'device' && request.action === 'new') { const { createPendingDevice, openAccountKey, ownJoinCode } = await import('../lib/grant/sealed-account.ts'); - const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('../lib/passphrase.ts'); + const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('@kuiralabs/midnight-wallet'); const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(ctx.host, target.root) : await passphraseForNewSecret(ctx.host, target.root); const device = createPendingDevice(recordsDir, passphrase); const code = ownJoinCode(recordsDir, openAccountKey(recordsDir, passphrase), device); @@ -106,7 +106,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, // An import brings an account in where there is none: it opens no account first. if (request.subcommand === 'import') { const { importAccount } = await import('../lib/grant/account-backup.ts'); - const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('../lib/passphrase.ts'); + const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('@kuiralabs/midnight-wallet'); try { const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(ctx.host, target.root) : await passphraseForNewSecret(ctx.host, target.root); const { contractAddress } = await importAccount(recordsDir, target.network, passphrase, request.file); @@ -225,7 +225,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, case 'device': { if (owned.protection !== 'sealed') throw new UsageError('The account is not protected: its devices are managed once it is. Encrypt it first: midnight wallet protect'); const { openAccountKey, sealedDeviceList } = await import('../lib/grant/sealed-account.ts'); - const { unlockPassphrase } = await import('../lib/passphrase.ts'); + const { unlockPassphrase } = await import('@kuiralabs/midnight-wallet'); const passphrase = await unlockPassphrase(ctx.host, target.root); const devices = sealedDeviceList(recordsDir, openAccountKey(recordsDir, passphrase)); if (owned.ownCode === undefined) throw new Error('A sealed account names its own device code'); @@ -274,7 +274,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, } case 'export': { const { exportAccount } = await import('../lib/grant/account-backup.ts'); - const { unlockPassphrase } = await import('../lib/passphrase.ts'); + const { unlockPassphrase } = await import('@kuiralabs/midnight-wallet'); const outcome = await exportAccount(recordsDir, target.network, await unlockPassphrase(ctx.host, target.root), request.file, ctx.host.engines); spinner.stop('Written'); if (jsonMode) { diff --git a/src/commands/localnet.ts b/src/commands/localnet.ts index c74d13be..5129beb2 100644 --- a/src/commands/localnet.ts +++ b/src/commands/localnet.ts @@ -160,7 +160,7 @@ async function handleDown(jsonMode: boolean, ctx: CallContext, docker: DockerCal // removed, so any wallet cache still referencing it is guaranteed stale // and would trigger "applied > highest" on the next command. Clearing // here means the next `mn ` starts with a truthful cache. - const { clearChainCaches } = await import('../lib/chain-caches.ts'); + const { clearChainCaches } = await import('@kuiralabs/midnight-wallet'); clearChainCaches('undeployed', docker.root); // Also wipe the dapp-local LevelDB private-state store if the user is diff --git a/src/commands/serve.definition.ts b/src/commands/serve.definition.ts index 8306c3cc..52ff2e1a 100644 --- a/src/commands/serve.definition.ts +++ b/src/commands/serve.definition.ts @@ -3,7 +3,7 @@ import type { CommandDefinition } from '@kuiralabs/midnight-cli-core'; import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; -import { OPENS_WALLET } from './wallet.codes.ts'; +import { OPENS_WALLET } from '@kuiralabs/midnight-wallet/commands'; export const serveDefinition: CommandDefinition = { name: 'serve', diff --git a/src/commands/serve.ts b/src/commands/serve.ts index c3177f99..eb56d2ab 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -4,7 +4,7 @@ import { type ParsedArgs, getFlag, hasFlag, rejectNoCacheForWrites, resolveNetwork, applyEndpointOverrides, type DAppConnector, type DAppConnectorCallbacks, OPERATOR_REJECTED_MESSAGE, type PhaseTiming, DEFAULT_SERVE_PORT, shieldedSyncEnabled, parseFeeLimits, describeApprovalPolicy, type CallContext, UsageError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { header, keyValue, divider, formatAddress, toDust, bold, dim, teal, green, red, type Spinner } from '@kuiralabs/midnight-cli-core/ui'; -import { resolveWalletPath, unlockWallet } from '../lib/wallet-config.ts'; +import { resolveWalletPath, unlockWallet } from '@kuiralabs/midnight-wallet'; import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; export default async function serveCommand(args: ParsedArgs, ctx: CallContext): Promise { diff --git a/src/commands/test.definition.ts b/src/commands/test.definition.ts index 95c5f44c..3c12a60f 100644 --- a/src/commands/test.definition.ts +++ b/src/commands/test.definition.ts @@ -3,7 +3,7 @@ import { type CommandDefinition, NETWORK_PARAM, EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core'; import { ENGINE_SYNC, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from '@kuiralabs/midnight-cli-core/commands'; import { READS_CHAIN } from '@kuiralabs/midnight-chain/commands'; -import { OPENS_WALLET } from './wallet.codes.ts'; +import { OPENS_WALLET } from '@kuiralabs/midnight-wallet/commands'; export const testDefinition: CommandDefinition = { name: 'test', diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index 4a402f26..ed2a5437 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -4,7 +4,7 @@ // given and where a notice goes, and decides the heap and the exit. import { type ParsedArgs, createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput, type CommandDefinition, type CommandRegistry, UsageError, writeJsonResult, type Payer, type CallSdkWarnings, type Host } from '@kuiralabs/midnight-cli-core'; -import type { WalletProtector } from './wallet-protector.ts'; +import type { WalletProtector } from '@kuiralabs/midnight-wallet'; /** What the shell can give a handler: its call's signal and output, and, as its definition's `shell` field asks, the payer or protectors, loaded only then. */ export interface ShellProvisions { diff --git a/src/lib/contract/call.ts b/src/lib/contract/call.ts index c7fe41e8..1ae48dea 100644 --- a/src/lib/contract/call.ts +++ b/src/lib/contract/call.ts @@ -2,8 +2,7 @@ // wallet the payer serves (served-wallet.ts). `mn contract call` calls through here. import { type Host, throwIfCancelled, type NetworkName, networkTargetOf, withCallSdkWarnings } from '@kuiralabs/midnight-cli-core'; -import { networkChoiceOf } from '../wallet/wallet-call.ts'; -import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; +import { networkChoiceOf, stepSpinner, type PaidCallOptions } from '@kuiralabs/midnight-wallet'; import { withServedWallet } from './served-wallet.ts'; import { assertContractRunsOn, type ContractChecked } from './runtime-check.ts'; import type { ContractCallRequest } from './request.ts'; diff --git a/src/lib/contract/deploy.ts b/src/lib/contract/deploy.ts index d5056049..23aa9a12 100644 --- a/src/lib/contract/deploy.ts +++ b/src/lib/contract/deploy.ts @@ -2,8 +2,7 @@ // the payer serves (served-wallet.ts). `mn contract deploy` and `mn dev` both deploy through here. import { type Host, throwIfCancelled, type NetworkName, networkTargetOf, withCallSdkWarnings } from '@kuiralabs/midnight-cli-core'; -import { networkChoiceOf } from '../wallet/wallet-call.ts'; -import { stepSpinner, type PaidCallOptions } from '../wallet/paid-call.ts'; +import { networkChoiceOf, stepSpinner, type PaidCallOptions } from '@kuiralabs/midnight-wallet'; import { withServedWallet } from './served-wallet.ts'; import { assertContractRunsOn, type ContractChecked } from './runtime-check.ts'; import type { ContractDeployRequest } from './request.ts'; diff --git a/src/lib/contract/state.ts b/src/lib/contract/state.ts index e97c664c..f1c0263e 100644 --- a/src/lib/contract/state.ts +++ b/src/lib/contract/state.ts @@ -4,7 +4,7 @@ // untyped state tree the indexer holds for the address. import { type Host, CancelledError, throwIfCancelled, type NetworkName, networkTargetOf, type NetworkChoice, progressSteps, type ProgressEvent, untilCancelled, type RawStateValue } from '@kuiralabs/midnight-cli-core'; -import { networkChoiceOf } from '../wallet/wallet-call.ts'; +import { networkChoiceOf } from '@kuiralabs/midnight-wallet'; import { findContractInfo } from './inspect.ts'; import { validateContractAddress } from './validate.ts'; diff --git a/src/lib/dev/provision-wallets.ts b/src/lib/dev/provision-wallets.ts index 0f02302b..3091bd7e 100644 --- a/src/lib/dev/provision-wallets.ts +++ b/src/lib/dev/provision-wallets.ts @@ -4,9 +4,7 @@ // left untouched (the user can `mn wallet remove ` to force re-setup). import { existsSync } from 'node:fs'; -import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet, type UnlockHost } from '../wallet-config.ts'; -import { createWallet, walletFilePath, walletSecretFrom } from '../wallet-create.ts'; -import { passphraseForNewSecret } from '../passphrase.ts'; +import { getActiveWalletName, loadWalletConfig, resolveWalletPath, setActiveWallet, unlockWallet, type UnlockHost, createWallet, walletFilePath, walletSecretFrom, passphraseForNewSecret } from '@kuiralabs/midnight-wallet'; import { sdkSetOf, resolveNetwork, type NetworkSettings, type NetworkConfig, type CallSdkWarnings, throwIfCancelled, nightToMicro } from '@kuiralabs/midnight-cli-core'; import { checkBalance } from '@kuiralabs/midnight-chain'; diff --git a/src/lib/grant/account-protector.ts b/src/lib/grant/account-protector.ts index e6943e02..7a01ace4 100644 --- a/src/lib/grant/account-protector.ts +++ b/src/lib/grant/account-protector.ts @@ -3,7 +3,7 @@ // wallets. The caller passes it to the wallet command. The sealing code (and // the account chain it loads) is loaded only when the protector runs. -import type { WalletProtector } from '../wallet-protector.ts'; +import type { WalletProtector } from '@kuiralabs/midnight-wallet'; export const accountProtector: WalletProtector = { name: 'accounts', diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 7e3d3456..018ac682 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -20,8 +20,7 @@ import { directoryOwnerStore, } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_DATABASE } from '../contract/private-state.ts'; -import { type PassphraseSource, passphraseForNewSecret, unlockPassphrase } from '../passphrase.ts'; -import type { UnlockHost } from '../wallet-config.ts'; +import { type PassphraseSource, passphraseForNewSecret, unlockPassphrase, type UnlockHost } from '@kuiralabs/midnight-wallet'; import { AccountMigrationInterruptedError, type SealedDeviceKeys, diff --git a/src/lib/grant/prepare.ts b/src/lib/grant/prepare.ts index 168d234f..e4279964 100644 --- a/src/lib/grant/prepare.ts +++ b/src/lib/grant/prepare.ts @@ -4,7 +4,7 @@ // confirmation token. import { type ParsedArgs, getFlag, UsageError, type PayingTarget, resolvePayingTarget, type Host } from '@kuiralabs/midnight-cli-core'; -import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '../wallet-config.ts'; +import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '@kuiralabs/midnight-wallet'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; import { type GrantRequest, resolveGrantRequest } from './request.ts'; diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index b16638b6..dbb01d08 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -8,34 +8,21 @@ import { getValidNetworkNames, createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core'; import { configDefinition, coreGuidance, coreCodes } from '@kuiralabs/midnight-cli-core/commands'; -import { walletDefinition } from '../commands/wallet.definition.ts'; -import { generateDefinition } from '../commands/generate.definition.ts'; -import { infoDefinition } from '../commands/info.definition.ts'; -import { balanceDefinition } from '../commands/balance.definition.ts'; -import { addressDefinition } from '../commands/address.definition.ts'; -import { genesisAddressDefinition } from '../commands/genesis-address.definition.ts'; +import { walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition, swapDefinition, walletGuidance, swapGuidance, walletCodes } from '@kuiralabs/midnight-wallet/commands'; import { inspectCostDefinition } from '../commands/inspect-cost.definition.ts'; -import { airdropDefinition } from '../commands/airdrop.definition.ts'; -import { transferDefinition } from '../commands/transfer.definition.ts'; -import { dustDefinition } from '../commands/dust.definition.ts'; -import { cacheDefinition } from '../commands/cache.definition.ts'; import { serveDefinition } from '../commands/serve.definition.ts'; import { testDefinition } from '../commands/test.definition.ts'; import { devDefinition } from '../commands/dev.definition.ts'; import { contractDefinition } from '../commands/contract.definition.ts'; import { grantDefinition } from '../commands/grant.definition.ts'; -import { swapDefinition } from '../commands/swap.definition.ts'; import { localnetDefinition } from '../commands/localnet.definition.ts'; import { statusDefinition, txDefinition, chainGuidance, chainCodes } from '@kuiralabs/midnight-chain/commands'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; -import { walletGuidance } from '../commands/wallet.guidance.ts'; import { contractGuidance } from '../commands/contract.guidance.ts'; import { connectGuidance } from '../commands/connect.guidance.ts'; import { devGuidance } from '../commands/dev.guidance.ts'; import { grantGuidance } from '../commands/grant.guidance.ts'; -import { swapGuidance } from '../commands/swap.guidance.ts'; -import { walletCodes } from '../commands/wallet.codes.ts'; import { contractCodes } from '../commands/contract.codes.ts'; import { devCodes } from '../commands/dev.codes.ts'; import { grantCodes } from '../commands/grant.codes.ts'; diff --git a/src/lib/serve-manager.ts b/src/lib/serve-manager.ts index cad7c50a..ed7267ed 100644 --- a/src/lib/serve-manager.ts +++ b/src/lib/serve-manager.ts @@ -4,7 +4,7 @@ // Always runs in approve-all mode. import { Socket } from 'node:net'; -import { resolveWalletPath, unlockWallet, walletAddress, type UnlockHost } from './wallet-config.ts'; +import { resolveWalletPath, unlockWallet, walletAddress, type UnlockHost } from '@kuiralabs/midnight-wallet'; import { resolveNetwork, applyEndpointOverrides, endpointFlags, type EndpointOverrides, type NetworkConfig, type NetworkName, sdkSetOf, type DAppConnectorCallbacks, type OpenedConnector, DEFAULT_SERVE_PORT, type CallSdkWarnings, shieldedSyncEnabled, CancelledError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { createRpcServer, type RpcServer } from './ws-rpc.ts'; diff --git a/src/lib/serve-payer.ts b/src/lib/serve-payer.ts index a89cd409..9ed91d6e 100644 --- a/src/lib/serve-payer.ts +++ b/src/lib/serve-payer.ts @@ -7,7 +7,7 @@ import { DEFAULT_SERVE_PORT, OWN_COMMAND_DUST_WAIT_MS, type ConnectOptions, type Payer, type PayingTarget, type ServedWallet, sdkSetOf, sessionOver, type WalletSession, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; -import { assertWalletCanPay } from './wallet-can-pay.ts'; +import { assertWalletCanPay } from '@kuiralabs/midnight-wallet'; /** * An mn serve on `port` for the command's network and wallet: one already diff --git a/src/lib/test/prep-runner.ts b/src/lib/test/prep-runner.ts index ccc26d0b..cc9faca4 100644 --- a/src/lib/test/prep-runner.ts +++ b/src/lib/test/prep-runner.ts @@ -3,7 +3,7 @@ import { join } from 'node:path'; import { clearWalletCache, resolveNetwork, type NetworkConfig, type NetworkName, OWN_COMMAND_DUST_WAIT_MS, DustRequiredError, InsufficientBalanceError, throwIfCancelled, sdkSetOf, nightToMicro } from '@kuiralabs/midnight-cli-core'; -import { resolveWalletPath, unlockWallet } from '../wallet-config.ts'; +import { resolveWalletPath, unlockWallet } from '@kuiralabs/midnight-wallet'; import { assertLedger9StackReachable, assertLedgerSupported } from '@kuiralabs/midnight-chain'; import type { DappTestConfig, PrepStepId, PrepStepResult, PrepContext, PrepCallbacks } from './types.ts'; diff --git a/src/lib/test/types.ts b/src/lib/test/types.ts index 1e725eab..32ad17d0 100644 --- a/src/lib/test/types.ts +++ b/src/lib/test/types.ts @@ -1,7 +1,7 @@ // Test framework types — schemas for dapp.test.json, suite configs, assertions, and results. import type { ServeHandle } from '../serve-manager.ts'; -import type { UnlockHost } from '../wallet-config.ts'; +import type { UnlockHost } from '@kuiralabs/midnight-wallet'; import type { CallSdkWarnings, NetworkName } from '@kuiralabs/midnight-cli-core'; // ── DApp Test Config (dapp.test.json in dApp root) ── diff --git a/src/wallet.ts b/src/wallet.ts index b8e79fed..e9ddc124 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -8,7 +8,7 @@ import { errorMessage, usageMessage, createTerminalPrompter } from '@kuiralabs/m import { installedCommands } from './lib/installed-commands.ts'; import { commandNeedsWalletSdk, dispatchCommand, processOutput } from './lib/command-dispatch.ts'; import { PKG_VERSION } from './lib/pkg.ts'; -import { migrateOldWallet } from './lib/wallet-paths.ts'; +import { migrateOldWallet } from '@kuiralabs/midnight-wallet'; import { ensureHeapForSync } from './lib/heap-guard.ts'; import { assertNodeSupported } from './lib/node-version.ts'; import { hideProjectIdsInOutput } from './lib/output-redaction.ts'; diff --git a/src/__tests__/helpers/plain-wallet.ts b/test-support/plain-wallet.ts similarity index 100% rename from src/__tests__/helpers/plain-wallet.ts rename to test-support/plain-wallet.ts diff --git a/src/__tests__/helpers/state-root-in.ts b/test-support/state-root-in.ts similarity index 100% rename from src/__tests__/helpers/state-root-in.ts rename to test-support/state-root-in.ts diff --git a/test-support/test-host.ts b/test-support/test-host.ts index c8c01f3d..122c0838 100644 --- a/test-support/test-host.ts +++ b/test-support/test-host.ts @@ -9,6 +9,9 @@ import { join } from 'node:path'; import { createHost, type Host, type HostOptions, settingsFromEnvironment, MIDNIGHT_DIR } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from '../src/lib/installed-engines.ts'; +/** The engines the CLI ships, as a host's engine loader: for a test that makes a host of its own. */ +export { loadInstalledEngine }; + export function testHost(overrides: HostOptions = {}): Host { return createHost({ settings: () => settingsFromEnvironment(process.env), diff --git a/tsconfig.json b/tsconfig.json index 0a04d83b..ef425a85 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts"], + "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts", "packages/wallet/src/**/*.ts"], "exclude": ["node_modules"] } From 0690695240de72977b107d659ccfb0a1323d8871 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 19:42:42 -0800 Subject: [PATCH 72/88] The connect, contract and dev packages (3F, 6-8 of 10) @kuiralabs/midnight-connect holds serve, the serve manager, the serve payer and the RPC server; @kuiralabs/midnight-contract holds contract and inspect-cost, the runner and the 3E contract functions; @kuiralabs/midnight-dev holds dev, test and localnet. Each has "." and "./commands"; mn's registry keeps its order, so help and the manuals are unchanged. connect comes before contract: a contract test of a script failing at mn serve needs connect's RPC server. Dependencies, as approved (Y59): connect declares ws (moved from mn's root, same range); contract and dev declare the workspace packages they import; mn's root declares the three packages. Every other lockfile entry keeps its resolution and integrity. The clean-install check now runs the installed contract package's runner on a compiled fixture for each engine: every script package is found by name and the script loads the dApp's contract. Suite 2933, beta 184; snapshot unchanged; fresh install; scratch chain final pass 84/84 in a clean runner, mn serve probe (reads, signData, a transfer submitted, refusals), mn dev 8/8, swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads. --- .github/workflows/release-sidecar.yml | 4 +- package-lock.json | 65 +++++- package.json | 13 +- packages/connect/api-report.md | 71 ++++++ packages/connect/package.json | 43 ++++ .../src}/__tests__/serve-manager.test.ts | 8 +- .../src}/__tests__/ws-rpc-api-types.test.ts | 0 .../connect/src}/__tests__/ws-rpc.test.ts | 0 packages/connect/src/commands.ts | 5 + .../connect/src}/commands/connect.guidance.ts | 0 .../connect/src}/commands/serve.definition.ts | 0 .../connect/src}/commands/serve.ts | 0 packages/connect/src/index.ts | 11 + .../connect/src}/lib/serve-manager.ts | 2 +- .../connect/src}/lib/serve-payer.ts | 0 {src => packages/connect/src}/lib/ws-rpc.ts | 0 packages/connect/tsconfig.build.json | 31 +++ packages/contract/api-report.md | 211 ++++++++++++++++++ packages/contract/package.json | 42 ++++ .../src}/__tests__/arg-coerce.test.ts | 0 .../src}/__tests__/contract-exists.test.ts | 0 .../src}/__tests__/contract-inspect.test.ts | 0 .../src}/__tests__/contract-lib.test.ts | 4 +- .../src}/__tests__/contract-request.test.ts | 0 .../contract-runner-endpoints.test.ts | 2 +- .../src}/__tests__/contract-runner.test.ts | 4 +- .../__tests__/contract-runtime-check.test.ts | 11 +- .../__tests__/contract-script-errors.test.ts | 93 +++++++- .../contract-script-packages.test.ts | 0 .../src}/__tests__/contract-validate.test.ts | 0 .../__tests__/helpers/serve-script-failure.ts | 2 +- .../__tests__/private-state-secret.test.ts | 0 .../src}/__tests__/witness-discovery.test.ts | 0 packages/contract/src/commands.ts | 8 + .../contract/src}/commands/contract.codes.ts | 0 .../src}/commands/contract.definition.ts | 0 .../src}/commands/contract.guidance.ts | 0 .../contract/src}/commands/contract.ts | 0 .../src}/commands/inspect-cost.definition.ts | 0 .../contract/src}/commands/inspect-cost.ts | 0 packages/contract/src/index.ts | 28 +++ .../contract/src}/lib/chain-params.ts | 0 .../contract/src}/lib/contract/arg-coerce.ts | 0 .../contract/src}/lib/contract/call.ts | 0 .../contract/src}/lib/contract/deploy.ts | 0 .../contract/src}/lib/contract/exists.ts | 0 .../contract/src}/lib/contract/inspect.ts | 0 .../src}/lib/contract/private-state-secret.ts | 0 .../src}/lib/contract/private-state.ts | 0 .../contract/src}/lib/contract/request.ts | 0 .../contract/src}/lib/contract/runner.ts | 0 .../src}/lib/contract/runtime-check.ts | 0 .../src}/lib/contract/served-wallet.ts | 0 .../contract/src}/lib/contract/state.ts | 0 .../contract/src}/lib/contract/validate.ts | 0 .../src}/lib/contract/witness-discovery.ts | 0 packages/contract/tsconfig.build.json | 31 +++ packages/dev/api-report.md | 35 +++ packages/dev/package.json | 44 ++++ .../__tests__/agent-report-no-failure.test.ts | 0 .../dev/src}/__tests__/ai-scaffold.test.ts | 2 +- .../__tests__/browser-test-launch.test.ts | 0 .../__tests__/circuit-witness-deps.test.ts | 0 .../dev/src}/__tests__/dev-compile.test.ts | 0 .../src}/__tests__/dev-detect-project.test.ts | 0 .../dev/src}/__tests__/dev-keys.test.ts | 0 .../src}/__tests__/dev-test-runner.test.ts | 0 .../dev/src}/__tests__/dev-watch.test.ts | 0 .../src}/__tests__/discover-screens.test.ts | 0 .../__tests__/localnet-cancellation.test.ts | 29 ++- .../__tests__/localnet-docker-probe.test.ts | 2 +- packages/dev/src/__tests__/localnet.test.ts | 186 +++++++++++++++ .../prep-runner-cancellation.test.ts | 47 ++++ .../src}/__tests__/provision-wallets.test.ts | 2 +- .../src}/__tests__/test-assertions.test.ts | 0 .../__tests__/test-contract-cache.test.ts | 0 .../dev/src}/__tests__/test-create.test.ts | 2 +- .../dev/src}/__tests__/test-discovery.test.ts | 0 .../dev/src}/__tests__/test-results.test.ts | 0 packages/dev/src/commands.ts | 8 + .../dev/src}/commands/dev.codes.ts | 0 .../dev/src}/commands/dev.definition.ts | 0 .../dev/src}/commands/dev.guidance.ts | 0 {src => packages/dev/src}/commands/dev.ts | 4 +- .../dev/src}/commands/localnet.definition.ts | 0 .../dev/src}/commands/localnet.ts | 2 +- .../dev/src}/commands/test.definition.ts | 0 {src => packages/dev/src}/commands/test.ts | 4 +- packages/dev/src/index.ts | 9 + {src => packages/dev/src}/lib/dev/compile.ts | 0 {src => packages/dev/src}/lib/dev/deploy.ts | 3 +- .../dev/src}/lib/dev/detect-project.ts | 0 .../dev/src}/lib/dev/localnet-ready.ts | 0 .../dev/src}/lib/dev/provision-wallets.ts | 0 {src => packages/dev/src}/lib/dev/test.ts | 0 {src => packages/dev/src}/lib/dev/watch.ts | 0 {src => packages/dev/src}/lib/localnet.ts | 0 .../dev/src}/lib/test/actions-runner.ts | 4 +- .../dev/src}/lib/test/ai-prompts.ts | 2 +- .../dev/src}/lib/test/ai-scaffold.ts | 2 +- .../dev/src}/lib/test/assertions.ts | 0 .../dev/src}/lib/test/browser-test.ts | 0 .../dev/src}/lib/test/build-manager.ts | 0 .../dev/src}/lib/test/circuit-witness-deps.ts | 0 .../dev/src}/lib/test/contract-cache.ts | 0 .../dev/src}/lib/test/create-writer.ts | 0 {src => packages/dev/src}/lib/test/create.ts | 2 +- .../dev/src}/lib/test/discover-screens.ts | 0 .../dev/src}/lib/test/discovery.ts | 0 .../dev/src}/lib/test/prep-runner.ts | 2 +- {src => packages/dev/src}/lib/test/results.ts | 0 .../dev/src}/lib/test/teardown.ts | 0 {src => packages/dev/src}/lib/test/types.ts | 2 +- {src => packages/dev/src}/ui/dev-keys.ts | 0 .../dev/src}/ui/test-create-prompt.ts | 2 +- packages/dev/tsconfig.build.json | 31 +++ scripts/api-report.mjs | 2 +- scripts/check-layering.mjs | 3 + scripts/code-reach.mjs | 2 +- scripts/fresh-install-check.mjs | 53 ++++- src/__tests__/chain-reset-clearing.test.ts | 2 +- src/__tests__/command-cancellation.test.ts | 6 +- src/__tests__/contract-deploy.test.ts | 5 +- src/__tests__/declared-codes.test.ts | 7 +- src/__tests__/entry-points.test.ts | 3 + src/__tests__/error-code-parity.test.ts | 45 +--- src/__tests__/exit-codes.test.ts | 2 +- src/__tests__/handler-library-calls.test.ts | 2 +- src/__tests__/host-slots.test.ts | 2 +- src/__tests__/inspect-cost-command.test.ts | 5 +- src/__tests__/json-output.test.ts | 3 +- src/__tests__/localnet-command.test.ts | 189 +--------------- src/__tests__/network-cancellation.test.ts | 2 +- src/__tests__/package-metadata.test.ts | 4 +- src/__tests__/payer.test.ts | 8 +- .../prep-runner-cancellation.test.ts | 26 --- src/__tests__/run-command.test.ts | 3 +- src/__tests__/serve-command.test.ts | 5 +- src/__tests__/state-root.test.ts | 2 +- src/__tests__/two-hosts.test.ts | 2 +- src/lib/grant/account.ts | 2 +- src/lib/installed-commands.ts | 14 +- src/mcp-server.ts | 2 +- src/wallet.ts | 2 +- tsconfig.json | 2 +- 145 files changed, 1170 insertions(+), 350 deletions(-) create mode 100644 packages/connect/api-report.md create mode 100644 packages/connect/package.json rename {src => packages/connect/src}/__tests__/serve-manager.test.ts (96%) rename {src => packages/connect/src}/__tests__/ws-rpc-api-types.test.ts (100%) rename {src => packages/connect/src}/__tests__/ws-rpc.test.ts (100%) create mode 100644 packages/connect/src/commands.ts rename {src => packages/connect/src}/commands/connect.guidance.ts (100%) rename {src => packages/connect/src}/commands/serve.definition.ts (100%) rename {src => packages/connect/src}/commands/serve.ts (100%) create mode 100644 packages/connect/src/index.ts rename {src => packages/connect/src}/lib/serve-manager.ts (99%) rename {src => packages/connect/src}/lib/serve-payer.ts (100%) rename {src => packages/connect/src}/lib/ws-rpc.ts (100%) create mode 100644 packages/connect/tsconfig.build.json create mode 100644 packages/contract/api-report.md create mode 100644 packages/contract/package.json rename {src => packages/contract/src}/__tests__/arg-coerce.test.ts (100%) rename {src => packages/contract/src}/__tests__/contract-exists.test.ts (100%) rename {src => packages/contract/src}/__tests__/contract-inspect.test.ts (100%) rename {src => packages/contract/src}/__tests__/contract-lib.test.ts (98%) rename {src => packages/contract/src}/__tests__/contract-request.test.ts (100%) rename {src => packages/contract/src}/__tests__/contract-runner-endpoints.test.ts (97%) rename {src => packages/contract/src}/__tests__/contract-runner.test.ts (97%) rename {src => packages/contract/src}/__tests__/contract-runtime-check.test.ts (88%) rename {src => packages/contract/src}/__tests__/contract-script-errors.test.ts (51%) rename {src => packages/contract/src}/__tests__/contract-script-packages.test.ts (100%) rename {src => packages/contract/src}/__tests__/contract-validate.test.ts (100%) rename {src => packages/contract/src}/__tests__/helpers/serve-script-failure.ts (96%) rename {src => packages/contract/src}/__tests__/private-state-secret.test.ts (100%) rename {src => packages/contract/src}/__tests__/witness-discovery.test.ts (100%) create mode 100644 packages/contract/src/commands.ts rename {src => packages/contract/src}/commands/contract.codes.ts (100%) rename {src => packages/contract/src}/commands/contract.definition.ts (100%) rename {src => packages/contract/src}/commands/contract.guidance.ts (100%) rename {src => packages/contract/src}/commands/contract.ts (100%) rename {src => packages/contract/src}/commands/inspect-cost.definition.ts (100%) rename {src => packages/contract/src}/commands/inspect-cost.ts (100%) create mode 100644 packages/contract/src/index.ts rename {src => packages/contract/src}/lib/chain-params.ts (100%) rename {src => packages/contract/src}/lib/contract/arg-coerce.ts (100%) rename {src => packages/contract/src}/lib/contract/call.ts (100%) rename {src => packages/contract/src}/lib/contract/deploy.ts (100%) rename {src => packages/contract/src}/lib/contract/exists.ts (100%) rename {src => packages/contract/src}/lib/contract/inspect.ts (100%) rename {src => packages/contract/src}/lib/contract/private-state-secret.ts (100%) rename {src => packages/contract/src}/lib/contract/private-state.ts (100%) rename {src => packages/contract/src}/lib/contract/request.ts (100%) rename {src => packages/contract/src}/lib/contract/runner.ts (100%) rename {src => packages/contract/src}/lib/contract/runtime-check.ts (100%) rename {src => packages/contract/src}/lib/contract/served-wallet.ts (100%) rename {src => packages/contract/src}/lib/contract/state.ts (100%) rename {src => packages/contract/src}/lib/contract/validate.ts (100%) rename {src => packages/contract/src}/lib/contract/witness-discovery.ts (100%) create mode 100644 packages/contract/tsconfig.build.json create mode 100644 packages/dev/api-report.md create mode 100644 packages/dev/package.json rename {src => packages/dev/src}/__tests__/agent-report-no-failure.test.ts (100%) rename {src => packages/dev/src}/__tests__/ai-scaffold.test.ts (99%) rename {src => packages/dev/src}/__tests__/browser-test-launch.test.ts (100%) rename {src => packages/dev/src}/__tests__/circuit-witness-deps.test.ts (100%) rename {src => packages/dev/src}/__tests__/dev-compile.test.ts (100%) rename {src => packages/dev/src}/__tests__/dev-detect-project.test.ts (100%) rename {src => packages/dev/src}/__tests__/dev-keys.test.ts (100%) rename {src => packages/dev/src}/__tests__/dev-test-runner.test.ts (100%) rename {src => packages/dev/src}/__tests__/dev-watch.test.ts (100%) rename {src => packages/dev/src}/__tests__/discover-screens.test.ts (100%) rename {src => packages/dev/src}/__tests__/localnet-cancellation.test.ts (87%) rename {src => packages/dev/src}/__tests__/localnet-docker-probe.test.ts (97%) create mode 100644 packages/dev/src/__tests__/localnet.test.ts create mode 100644 packages/dev/src/__tests__/prep-runner-cancellation.test.ts rename {src => packages/dev/src}/__tests__/provision-wallets.test.ts (98%) rename {src => packages/dev/src}/__tests__/test-assertions.test.ts (100%) rename {src => packages/dev/src}/__tests__/test-contract-cache.test.ts (100%) rename {src => packages/dev/src}/__tests__/test-create.test.ts (99%) rename {src => packages/dev/src}/__tests__/test-discovery.test.ts (100%) rename {src => packages/dev/src}/__tests__/test-results.test.ts (100%) create mode 100644 packages/dev/src/commands.ts rename {src => packages/dev/src}/commands/dev.codes.ts (100%) rename {src => packages/dev/src}/commands/dev.definition.ts (100%) rename {src => packages/dev/src}/commands/dev.guidance.ts (100%) rename {src => packages/dev/src}/commands/dev.ts (98%) rename {src => packages/dev/src}/commands/localnet.definition.ts (100%) rename {src => packages/dev/src}/commands/localnet.ts (99%) rename {src => packages/dev/src}/commands/test.definition.ts (100%) rename {src => packages/dev/src}/commands/test.ts (99%) create mode 100644 packages/dev/src/index.ts rename {src => packages/dev/src}/lib/dev/compile.ts (100%) rename {src => packages/dev/src}/lib/dev/deploy.ts (90%) rename {src => packages/dev/src}/lib/dev/detect-project.ts (100%) rename {src => packages/dev/src}/lib/dev/localnet-ready.ts (100%) rename {src => packages/dev/src}/lib/dev/provision-wallets.ts (100%) rename {src => packages/dev/src}/lib/dev/test.ts (100%) rename {src => packages/dev/src}/lib/dev/watch.ts (100%) rename {src => packages/dev/src}/lib/localnet.ts (100%) rename {src => packages/dev/src}/lib/test/actions-runner.ts (98%) rename {src => packages/dev/src}/lib/test/ai-prompts.ts (99%) rename {src => packages/dev/src}/lib/test/ai-scaffold.ts (99%) rename {src => packages/dev/src}/lib/test/assertions.ts (100%) rename {src => packages/dev/src}/lib/test/browser-test.ts (100%) rename {src => packages/dev/src}/lib/test/build-manager.ts (100%) rename {src => packages/dev/src}/lib/test/circuit-witness-deps.ts (100%) rename {src => packages/dev/src}/lib/test/contract-cache.ts (100%) rename {src => packages/dev/src}/lib/test/create-writer.ts (100%) rename {src => packages/dev/src}/lib/test/create.ts (99%) rename {src => packages/dev/src}/lib/test/discover-screens.ts (100%) rename {src => packages/dev/src}/lib/test/discovery.ts (100%) rename {src => packages/dev/src}/lib/test/prep-runner.ts (99%) rename {src => packages/dev/src}/lib/test/results.ts (100%) rename {src => packages/dev/src}/lib/test/teardown.ts (100%) rename {src => packages/dev/src}/lib/test/types.ts (98%) rename {src => packages/dev/src}/ui/dev-keys.ts (100%) rename {src => packages/dev/src}/ui/test-create-prompt.ts (99%) create mode 100644 packages/dev/tsconfig.build.json delete mode 100644 src/__tests__/prep-runner-cancellation.test.ts diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index 96cbea54..4e2901fa 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -159,7 +159,7 @@ jobs: fi done # mn depends on its workspace packages (core, chain, one engine per SDK - # set, wallet) at exact versions: each publishes first, unless that version is + # set, wallet, contract, connect, dev) at exact versions: each publishes first, unless that version is # on npm already, under the same dist-tag as mn. - run: npm run build - name: Publish the workspace packages mn depends on @@ -168,7 +168,7 @@ jobs: shell: bash run: | set -euo pipefail - for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta packages/wallet; do + for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta packages/wallet packages/contract packages/connect packages/dev; do name="$(node -p "require('./$dir/package.json').name")" version="$(node -p "require('./$dir/package.json').version")" if npm view "$name@$version" version >/dev/null 2>&1; then diff --git a/package-lock.json b/package-lock.json index 1ff2d5a8..593630f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,18 +14,23 @@ "packages/chain", "packages/engine-rc", "packages/engine-beta", - "packages/wallet" + "packages/wallet", + "packages/contract", + "packages/connect", + "packages/dev" ], "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-connect": "0.1.0-rc.1", + "@kuiralabs/midnight-contract": "0.1.0-rc.1", + "@kuiralabs/midnight-dev": "0.1.0-rc.1", "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", "@kuiralabs/midnight-wallet": "0.1.0-rc.1", - "@modelcontextprotocol/sdk": "^1.27.1", - "ws": "^8.19.0" + "@modelcontextprotocol/sdk": "^1.27.1" }, "bin": { "midnight": "dist/wallet.js", @@ -675,6 +680,18 @@ "resolved": "packages/cli-core", "link": true }, + "node_modules/@kuiralabs/midnight-connect": { + "resolved": "packages/connect", + "link": true + }, + "node_modules/@kuiralabs/midnight-contract": { + "resolved": "packages/contract", + "link": true + }, + "node_modules/@kuiralabs/midnight-dev": { + "resolved": "packages/dev", + "link": true + }, "node_modules/@kuiralabs/midnight-engine-beta": { "resolved": "packages/engine-beta", "link": true @@ -5727,6 +5744,20 @@ "node": ">=22" } }, + "packages/connect": { + "name": "@kuiralabs/midnight-connect", + "version": "0.1.0-rc.1", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1", + "ws": "^8.19.0" + }, + "engines": { + "node": ">=22" + } + }, "packages/connector": { "name": "midnight-wallet-connector", "version": "0.0.6", @@ -5750,6 +5781,34 @@ } } }, + "packages/contract": { + "name": "@kuiralabs/midnight-contract", + "version": "0.1.0-rc.1", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + }, + "engines": { + "node": ">=22" + } + }, + "packages/dev": { + "name": "@kuiralabs/midnight-dev", + "version": "0.1.0-rc.1", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-connect": "0.1.0-rc.1", + "@kuiralabs/midnight-contract": "0.1.0-rc.1", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + }, + "engines": { + "node": ">=22" + } + }, "packages/engine-beta": { "name": "@kuiralabs/midnight-engine-beta", "version": "0.1.0-rc.1", diff --git a/package.json b/package.json index ef9f2dce..0be0469c 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,10 @@ "packages/chain", "packages/engine-rc", "packages/engine-beta", - "packages/wallet" + "packages/wallet", + "packages/contract", + "packages/connect", + "packages/dev" ], "bin": { "midnight": "dist/wallet.js", @@ -51,7 +54,7 @@ }, "scripts": { "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", - "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && npm run build -w @kuiralabs/midnight-wallet && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && npm run build -w @kuiralabs/midnight-wallet && npm run build -w @kuiralabs/midnight-contract && npm run build -w @kuiralabs/midnight-connect && npm run build -w @kuiralabs/midnight-dev && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", @@ -70,11 +73,13 @@ "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-connect": "0.1.0-rc.1", + "@kuiralabs/midnight-contract": "0.1.0-rc.1", + "@kuiralabs/midnight-dev": "0.1.0-rc.1", "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", "@kuiralabs/midnight-wallet": "0.1.0-rc.1", - "@modelcontextprotocol/sdk": "^1.27.1", - "ws": "^8.19.0" + "@modelcontextprotocol/sdk": "^1.27.1" }, "devDependencies": { "@midnightntwrk/dapp-connector-api": "4.1.0-beta.1", diff --git a/packages/connect/api-report.md b/packages/connect/api-report.md new file mode 100644 index 00000000..ae559485 --- /dev/null +++ b/packages/connect/api-report.md @@ -0,0 +1,71 @@ +# API report: @kuiralabs/midnight-connect + +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-connect` + +```ts +export declare const servePayer: Payer; +export declare function servePayerAt(port: number): Payer; +export declare function probeServeNetwork(port: number): Promise; +export interface ServeHandle { + port: number; + stop(): Promise; +} +export interface ServeManagerOptions { + root: string; + host: UnlockHost; + port?: number; + network?: string; + endpoints?: EndpointOverrides; + wallet?: string; + onMessage?: (msg: string) => void; + dustWaitMs?: number; + sdkWarnings: CallSdkWarnings; + forceShielded?: boolean; + signal?: AbortSignal; +} +export declare function startServeOrReuse(options: ServeManagerOptions): Promise; +export declare function createRpcServer(options: RpcServerOptions): RpcServer; +export interface JsonRpcRequest { + jsonrpc: '2.0'; + id: number | string; + method: string; + params?: Record; +} +export interface RpcConnection { + ws: WebSocket; + id: string; + connectedAt: Date; + authenticated: boolean; + networkId?: string; + requestCount: number; + notify(method: string, params?: Record): void; +} +export interface RpcServer { + wss: WebSocketServer; + connections: Map; + ready: Promise; + close(): Promise; +} +export interface RpcServerOptions { + host: Pick; + port: number; + handlers: Record; + refuseBrowsers?: boolean; + onConnect?: (connection: RpcConnection) => void; + onDisconnect?: (connection: RpcConnection) => void; + onRequest?: (connection: RpcConnection, request: JsonRpcRequest) => void; + onResponse?: (connection: RpcConnection, request: JsonRpcRequest, durationMs: number, result?: unknown, error?: { + message: string; + code?: string; + }, metadata?: Record) => void; +} +``` + +## `@kuiralabs/midnight-connect/commands` + +```ts +export declare const connectGuidance: PackageGuidance; +export declare const serveDefinition: CommandDefinition; +``` diff --git a/packages/connect/package.json b/packages/connect/package.json new file mode 100644 index 00000000..05c37b03 --- /dev/null +++ b/packages/connect/package.json @@ -0,0 +1,43 @@ +{ + "name": "@kuiralabs/midnight-connect", + "version": "0.1.0-rc.1", + "type": "module", + "description": "mn serve for the Midnight CLI packages: the DApp connector API over a local WebSocket JSON-RPC server, the serve manager that starts or reuses one, and the payer that pays a command through it", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/connect" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1", + "ws": "^8.19.0" + } +} diff --git a/src/__tests__/serve-manager.test.ts b/packages/connect/src/__tests__/serve-manager.test.ts similarity index 96% rename from src/__tests__/serve-manager.test.ts rename to packages/connect/src/__tests__/serve-manager.test.ts index b9b777ae..6333aa48 100644 --- a/src/__tests__/serve-manager.test.ts +++ b/packages/connect/src/__tests__/serve-manager.test.ts @@ -6,12 +6,12 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { rcKeys } from '../../test-support/rc-engine.ts'; +import { rcKeys } from '../../../../test-support/rc-engine.ts'; import { serveEndpointMismatch, serveWalletMismatch } from '../lib/serve-manager.ts'; import { createSdkWarningRouter, createHost } from '@kuiralabs/midnight-cli-core'; -import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; -import { stateRootIn } from '../../test-support/state-root-in.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { saveWalletConfig } from '../../../../test-support/plain-wallet.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = createHost({ engineLoader: loadInstalledEngine }); diff --git a/src/__tests__/ws-rpc-api-types.test.ts b/packages/connect/src/__tests__/ws-rpc-api-types.test.ts similarity index 100% rename from src/__tests__/ws-rpc-api-types.test.ts rename to packages/connect/src/__tests__/ws-rpc-api-types.test.ts diff --git a/src/__tests__/ws-rpc.test.ts b/packages/connect/src/__tests__/ws-rpc.test.ts similarity index 100% rename from src/__tests__/ws-rpc.test.ts rename to packages/connect/src/__tests__/ws-rpc.test.ts diff --git a/packages/connect/src/commands.ts b/packages/connect/src/commands.ts new file mode 100644 index 00000000..be4ad2df --- /dev/null +++ b/packages/connect/src/commands.ts @@ -0,0 +1,5 @@ +// @kuiralabs/midnight-connect/commands: the serve command and connect's agent +// guidance, for the shell that installs them. + +export { connectGuidance } from './commands/connect.guidance.ts'; +export { serveDefinition } from './commands/serve.definition.ts'; diff --git a/src/commands/connect.guidance.ts b/packages/connect/src/commands/connect.guidance.ts similarity index 100% rename from src/commands/connect.guidance.ts rename to packages/connect/src/commands/connect.guidance.ts diff --git a/src/commands/serve.definition.ts b/packages/connect/src/commands/serve.definition.ts similarity index 100% rename from src/commands/serve.definition.ts rename to packages/connect/src/commands/serve.definition.ts diff --git a/src/commands/serve.ts b/packages/connect/src/commands/serve.ts similarity index 100% rename from src/commands/serve.ts rename to packages/connect/src/commands/serve.ts diff --git a/packages/connect/src/index.ts b/packages/connect/src/index.ts new file mode 100644 index 00000000..343e5a59 --- /dev/null +++ b/packages/connect/src/index.ts @@ -0,0 +1,11 @@ +// @kuiralabs/midnight-connect: mn serve for a program and the packages above. +// The payer a paying command is given (one that starts or reuses an mn serve +// on a port and pays through its wallet), the serve manager that starts or +// reuses that serve and asks which network one on a port runs, and the +// WebSocket JSON-RPC server the DApp connector API is served over, with the +// handlers it is given. Each name is listed, so the API is what this file +// says. The serve command and connect's guidance are "./commands". + +export { servePayer, servePayerAt } from './lib/serve-payer.ts'; +export { probeServeNetwork, type ServeHandle, type ServeManagerOptions, startServeOrReuse } from './lib/serve-manager.ts'; +export { createRpcServer, type JsonRpcRequest, type RpcConnection, type RpcServer, type RpcServerOptions } from './lib/ws-rpc.ts'; diff --git a/src/lib/serve-manager.ts b/packages/connect/src/lib/serve-manager.ts similarity index 99% rename from src/lib/serve-manager.ts rename to packages/connect/src/lib/serve-manager.ts index ed7267ed..666c60d3 100644 --- a/src/lib/serve-manager.ts +++ b/packages/connect/src/lib/serve-manager.ts @@ -1,6 +1,6 @@ // Serve manager — start mn serve programmatically (in-process), for test runs // and for the commands mn serve pays for. Replicates the initialization from -// src/commands/serve.ts but returns a handle instead of blocking on a signal. +// commands/serve.ts but returns a handle instead of blocking on a signal. // Always runs in approve-all mode. import { Socket } from 'node:net'; diff --git a/src/lib/serve-payer.ts b/packages/connect/src/lib/serve-payer.ts similarity index 100% rename from src/lib/serve-payer.ts rename to packages/connect/src/lib/serve-payer.ts diff --git a/src/lib/ws-rpc.ts b/packages/connect/src/lib/ws-rpc.ts similarity index 100% rename from src/lib/ws-rpc.ts rename to packages/connect/src/lib/ws-rpc.ts diff --git a/packages/connect/tsconfig.build.json b/packages/connect/tsconfig.build.json new file mode 100644 index 00000000..70e97051 --- /dev/null +++ b/packages/connect/tsconfig.build.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node" + ] + }, + "include": [ + "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" + ] +} diff --git a/packages/contract/api-report.md b/packages/contract/api-report.md new file mode 100644 index 00000000..ac9abd14 --- /dev/null +++ b/packages/contract/api-report.md @@ -0,0 +1,211 @@ +# API report: @kuiralabs/midnight-contract + +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-contract` + +```ts +export interface CallContractOptions extends PaidCallOptions { + request: ContractCallRequest; +} +export interface CalledCircuit { + readonly network: NetworkName; + readonly contractName: string; + readonly circuit: string; + readonly address: string; + readonly status: string; +} +export declare function callContract(host: Host, options: CallContractOptions): Promise; +export interface DeployContractOptions extends PaidCallOptions { + request: ContractDeployRequest; +} +export interface DeployedContract { + readonly network: NetworkName; + readonly contractName: string; + readonly address: string; +} +export declare function deployContract(host: Host, options: DeployContractOptions): Promise; +export declare function contractExists(indexerUrl: string, address: string, timeoutMs?: number): Promise; +export interface CircuitInfo { + name: string; + pure: boolean; + proof: boolean; + arguments: { + name: string; + type: CompactType; + }[]; + 'result-type': CompactType; +} +export interface CompactType { + 'type-name': string; + length?: number; + maxval?: number; + tsType?: string; + types?: CompactType[]; +} +export interface ContractInfo { + name: string; + managedDir: string; + compilerVersion: string; + languageVersion: string; + runtimeVersion: string; + circuits: CircuitInfo[]; + witnesses: WitnessInfo[]; + siblings: string[]; +} +export declare function findContractInfo(startDir: string, contractName?: string): { + info: ContractInfo; + infoPath: string; +}; +export interface WitnessInfo { + name: string; + arguments: { + name: string; + type: CompactType; + }[]; + 'result type': CompactType; +} +export declare function clearDappPrivateState(dappDir: string): boolean; +export declare const PRIVATE_STATE_DATABASE = "midnight-level-db"; +export interface ContractCallRequest { + dappDir: string; + info: ContractInfo; + address: string; + circuit: string; + callArgs: unknown[]; +} +export declare function contractCallRequest(location: ContractLocation & { + address: string; + circuit: string; + args?: unknown[]; +}): ContractCallRequest; +export interface ContractDeployRequest { + dappDir: string; + info: ContractInfo; + constructorArgs: unknown[]; + privateStateSecretKey?: string; +} +export declare function contractDeployRequest(location: ContractLocation & { + args?: unknown[]; + secretKey?: string; +}): ContractDeployRequest; +export interface ContractLocation { + dappDir: string; + managedDir?: string; + name?: string; +} +export interface CallOptions extends RunnerOptions { + contractAddress: string; + circuit: string; + args?: unknown[]; + privateStateKey?: string; +} +export interface CallResult { + status: string; + circuit: string; +} +export declare class ContractScriptError extends Error { + readonly code: string | undefined; + constructor({ message, code }: ScriptFailure); +} +export interface DeployOptions extends RunnerOptions { + privateStateKey?: string; + privateStateSecretKey?: string; + args?: unknown[]; +} +export interface DeployResult { + contractAddress: string; +} +export declare function runCall(options: CallOptions): Promise; +export declare function runDeploy(options: DeployOptions): Promise; +export interface RunnerOptions { + dappDir: string; + network: NetworkName; + root: string; + engines: HostEngines; + networkConfig: NetworkConfig; + managedDir: string; + contractName: string; + servePort: number; + onMessage?: (msg: string) => void; + signal?: AbortSignal; +} +export declare function runState(options: StateOptions): Promise; +export interface StateOptions { + dappDir: string; + network: NetworkName; + root: string; + engines: HostEngines; + networkConfig: NetworkConfig; + managedDir: string; + contractName: string; + contractAddress: string; + onMessage?: (msg: string) => void; + signal?: AbortSignal; +} +export interface StateResult { + fields: Record; + maps: Record; +} +export interface ContractChecked { + readonly kind: 'contract-checked'; + readonly network: NetworkName; +} +export type ContractState = ParsedContractState | RawContractState; +export interface ParsedContractState { + readonly kind: 'parsed'; + readonly network: NetworkName; + readonly address: string; + readonly fields: Record; + readonly maps: Record; +} +export interface RawContractState { + readonly kind: 'raw'; + readonly network: NetworkName; + readonly address: string; + readonly raw: RawStateValue; +} +export declare function readContractState(host: Host, options: ReadContractStateOptions): Promise; +export interface ReadContractStateOptions extends NetworkChoice { + dappDir: string; + scanDir?: string; + name?: string; + address: string; + signal?: AbortSignal; + onProgress?: (event: ProgressEvent | StateReading | StateFallback) => void; +} +export interface StateFallback { + readonly kind: 'fallback'; + readonly reason: string; +} +export interface StateReading { + readonly kind: 'state-reading'; + readonly network: NetworkName; +} +export declare function buildMissingWitnessError(opts: { + projectRoot: string; + witnessNames: string[]; +}): string; +export declare function findWitnessFile(projectRoot: string): string | null; +``` + +## `@kuiralabs/midnight-contract/commands` + +```ts +export declare const contractCodes: readonly [ + { + readonly code: "NO_NODE_RUNTIME"; + readonly exitCode: 1; + readonly order: 200; + readonly summary: "Contract scripts run under Node.js, and none was found on PATH."; + readonly recovery: "Ask the user to install Node.js 22 or later, or to run mn under Node."; + } +]; +export declare const contractDefinition: CommandDefinition; +export declare const contractGuidance: PackageGuidance; +export declare const inspectCostDefinition: CommandDefinition; +``` diff --git a/packages/contract/package.json b/packages/contract/package.json new file mode 100644 index 00000000..d60fe981 --- /dev/null +++ b/packages/contract/package.json @@ -0,0 +1,42 @@ +{ + "name": "@kuiralabs/midnight-contract", + "version": "0.1.0-rc.1", + "type": "module", + "description": "Contracts for the Midnight CLI packages: deploying, calling and reading a Compact contract from its dApp folder through mn serve, the requests a deploy or call is built from, a compiled contract's circuits and witnesses, and the chain's block limits", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/contract" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + } +} diff --git a/src/__tests__/arg-coerce.test.ts b/packages/contract/src/__tests__/arg-coerce.test.ts similarity index 100% rename from src/__tests__/arg-coerce.test.ts rename to packages/contract/src/__tests__/arg-coerce.test.ts diff --git a/src/__tests__/contract-exists.test.ts b/packages/contract/src/__tests__/contract-exists.test.ts similarity index 100% rename from src/__tests__/contract-exists.test.ts rename to packages/contract/src/__tests__/contract-exists.test.ts diff --git a/src/__tests__/contract-inspect.test.ts b/packages/contract/src/__tests__/contract-inspect.test.ts similarity index 100% rename from src/__tests__/contract-inspect.test.ts rename to packages/contract/src/__tests__/contract-inspect.test.ts diff --git a/src/__tests__/contract-lib.test.ts b/packages/contract/src/__tests__/contract-lib.test.ts similarity index 98% rename from src/__tests__/contract-lib.test.ts rename to packages/contract/src/__tests__/contract-lib.test.ts index dac09eb7..39b446f8 100644 --- a/src/__tests__/contract-lib.test.ts +++ b/packages/contract/src/__tests__/contract-lib.test.ts @@ -11,12 +11,12 @@ import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { createHost, type Host, type Payer, type PayingTarget, InsufficientBalanceError } from '@kuiralabs/midnight-cli-core'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { contractCallRequest, contractDeployRequest } from '../lib/contract/request.ts'; import { deployContract } from '../lib/contract/deploy.ts'; import { callContract } from '../lib/contract/call.ts'; import { readContractState } from '../lib/contract/state.ts'; -import { startLocalIndexer, type LocalIndexer } from '../../test-support/local-indexer.ts'; +import { startLocalIndexer, type LocalIndexer } from '../../../../test-support/local-indexer.ts'; const ADDRESS = 'cb5230e1ac98e07520d3b330016743a05fec38dd8fe894ae5b9ac3f71cac5190'; const ENDPOINTS = { network: 'undeployed' as const, node: 'ws://127.0.0.1:29944', indexerWS: 'ws://127.0.0.1:28088/api/v4/graphql/ws', proofServer: 'http://127.0.0.1:26300' }; diff --git a/src/__tests__/contract-request.test.ts b/packages/contract/src/__tests__/contract-request.test.ts similarity index 100% rename from src/__tests__/contract-request.test.ts rename to packages/contract/src/__tests__/contract-request.test.ts diff --git a/src/__tests__/contract-runner-endpoints.test.ts b/packages/contract/src/__tests__/contract-runner-endpoints.test.ts similarity index 97% rename from src/__tests__/contract-runner-endpoints.test.ts rename to packages/contract/src/__tests__/contract-runner-endpoints.test.ts index b56a8d96..9676a996 100644 --- a/src/__tests__/contract-runner-endpoints.test.ts +++ b/packages/contract/src/__tests__/contract-runner-endpoints.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest'; import { BlockfrostProjectIdRequiredError, blockfrostEndpoints, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; import type { CallScript, DeployScript, StateScript } from '@kuiralabs/midnight-cli-core/engine'; import { SCRIPT_PARTS, indexerEnvironment } from '../lib/contract/runner.ts'; -import { rcEngine } from '../../test-support/rc-engine.ts'; +import { rcEngine } from '../../../../test-support/rc-engine.ts'; // The rc engine's scripts, with the parts the runner gives every engine. const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcEngine.contracts.scripts.deploy(opts, SCRIPT_PARTS); diff --git a/src/__tests__/contract-runner.test.ts b/packages/contract/src/__tests__/contract-runner.test.ts similarity index 97% rename from src/__tests__/contract-runner.test.ts rename to packages/contract/src/__tests__/contract-runner.test.ts index f94a1d62..d874d218 100644 --- a/src/__tests__/contract-runner.test.ts +++ b/packages/contract/src/__tests__/contract-runner.test.ts @@ -12,8 +12,8 @@ import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { SCRIPT_PARTS, SCRIPT_PRELUDE, runCall, runDeploy, runState } from '../lib/contract/runner.ts'; -import { rcEngine } from '../../test-support/rc-engine.ts'; -import { testHost } from '../../test-support/test-host.ts'; +import { rcEngine } from '../../../../test-support/rc-engine.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; // The rc engine's scripts, with the parts the runner gives every engine. const generateDeployScript = (opts: DeployScript & { dappDir?: string }): string => rcEngine.contracts.scripts.deploy(opts, SCRIPT_PARTS); diff --git a/src/__tests__/contract-runtime-check.test.ts b/packages/contract/src/__tests__/contract-runtime-check.test.ts similarity index 88% rename from src/__tests__/contract-runtime-check.test.ts rename to packages/contract/src/__tests__/contract-runtime-check.test.ts index fa4e5a30..216ecbb1 100644 --- a/src/__tests__/contract-runtime-check.test.ts +++ b/packages/contract/src/__tests__/contract-runtime-check.test.ts @@ -6,12 +6,17 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { UsageError, classifyError, createHost } from '@kuiralabs/midnight-cli-core'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; +import { contractCodes } from '../commands/contract.codes.ts'; +import { codeRegistry } from '../../../../test-support/core-codes.ts'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { assertContractRunsOn } from '../lib/contract/runtime-check.ts'; import { runDeploy } from '../lib/contract/runner.ts'; +// What the shell classifies a contract run's errors by: core's codes and contract's. +const CONTRACT_CODES = codeRegistry(coreCodes, contractCodes); + // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); // The engines the checks load the network's engine from: a host's of the engines the CLI ships. @@ -41,7 +46,7 @@ describe('a contract for another compact runtime', () => { expect((refused as Error).message).toBe( 'counter was compiled by compactc 0.30.0 for compact-runtime 0.16.0, but undeployed runs contracts on compact-runtime 0.20.0.\nRecompile it with compactc 0.35.', ); - expect(classifyError(refused as Error, installedCommands).errorCode).toBe('INVALID_ARGS'); + expect(classifyError(refused as Error, CONTRACT_CODES).errorCode).toBe('INVALID_ARGS'); }); it('lets through one compiled for the engine\'s runtime, and one whose compiler recorded none', async () => { diff --git a/src/__tests__/contract-script-errors.test.ts b/packages/contract/src/__tests__/contract-script-errors.test.ts similarity index 51% rename from src/__tests__/contract-script-errors.test.ts rename to packages/contract/src/__tests__/contract-script-errors.test.ts index ddf53411..929d71b7 100644 --- a/src/__tests__/contract-script-errors.test.ts +++ b/packages/contract/src/__tests__/contract-script-errors.test.ts @@ -10,15 +10,19 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; -import { closedPort } from '../../test-support/closed-port.ts'; +import { closedPort } from '../../../../test-support/closed-port.ts'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; -import { ContractScriptError, SCRIPT_PRELUDE, executeScript, rpcClientCode, scriptFailureMessage, scriptFailureOf } from '../lib/contract/runner.ts'; -import { createApiError } from '../lib/ws-rpc.ts'; +import { ContractScriptError, SCRIPT_ERROR_MARKER, SCRIPT_PRELUDE, executeScript, rpcClientCode, scriptFailureMessage, scriptFailureOf, scriptRuntime } from '../lib/contract/runner.ts'; import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; -import { classifyError } from '@kuiralabs/midnight-cli-core'; -import { withEngineCode } from '@kuiralabs/midnight-cli-core/engine'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { classifyError, createApiError, OPERATOR_REJECTED_MESSAGE } from '@kuiralabs/midnight-cli-core'; +import { ProofTimeoutError, withEngineCode } from '@kuiralabs/midnight-cli-core/engine'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; +import { contractCodes } from '../commands/contract.codes.ts'; +import { codeRegistry } from '../../../../test-support/core-codes.ts'; + +// What the shell classifies a contract run's errors by: core's codes and contract's. +const CONTRACT_CODES = codeRegistry(coreCodes, contractCodes); function runScript(body: string): { stderr: string; status: number | null } { const dir = mkdtempSync(join(tmpdir(), 'mn-script-')); @@ -86,7 +90,7 @@ await Promise.reject(new TypeError('Expected an input string with byte length of ); expect(err).toBeInstanceOf(ContractScriptError); expect(err.message).toMatch(/^Cannot connect to mn serve at ws:\/\/127\.0\.0\.1:\d+: connect ECONNREFUSED/); - expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); + expect(classifyError(err, CONTRACT_CODES)).toStrictEqual({ errorCode: 'NETWORK_ERROR', exitCode: 4 }); } finally { rmSync(dir, { recursive: true, force: true }); } @@ -95,6 +99,10 @@ await Promise.reject(new TypeError('Expected an input string with byte length of it("reads an older mn's script, which reported its message alone", () => { expect(scriptFailureOf('__MN_ERROR__ "the message"\n', 1)).toStrictEqual({ message: 'the message' }); }); + + it('gives the error the runner rejects with the code its marked line carries', () => { + expect(new ContractScriptError(scriptFailureOf(`${SCRIPT_ERROR_MARKER} {"message":"refused","code":"PROOF_FAILURE"}\n`, 1)).code).toBe('PROOF_FAILURE'); + }); }); // The whole way a failure at mn serve takes, run for real: helpers/serve-script-failure.ts. @@ -106,7 +114,7 @@ describe("a failure at mn serve, across the wire and the script's process", () = const err = await failedRun(() => createApiError('InternalError', message, 'DUST_REQUIRED')); expect(err).toBeInstanceOf(ContractScriptError); expect(err.message).toBe(message); - expect(classifyError(err, installedCommands)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); + expect(classifyError(err, CONTRACT_CODES)).toStrictEqual({ errorCode: 'DUST_REQUIRED', exitCode: 5 }); }); it("carries a node's refusal by its reason (approved Y54: one with no rule's words was UNKNOWN)", async () => { @@ -118,8 +126,71 @@ describe("a failure at mn serve, across the wire and the script's process", () = }; const other = await refused('1010: Invalid Transaction: Custom error: 199'); expect(other.message).toBe('Transaction submission failed: [SubmissionError] Transaction submission error → 1010: Invalid Transaction: Custom error: 199'); - expect(classifyError(other, installedCommands)).toStrictEqual({ errorCode: 'TX_REJECTED', exitCode: 6 }); - expect(classifyError(await refused('1010: Invalid Transaction: Custom error: 115'), installedCommands)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); - expect(classifyError(await refused('1010: Invalid Transaction: Custom error: 170'), installedCommands)).toStrictEqual({ errorCode: 'INVALID_DUST_PROOF', exitCode: 6 }); + expect(classifyError(other, CONTRACT_CODES)).toStrictEqual({ errorCode: 'TX_REJECTED', exitCode: 6 }); + expect(classifyError(await refused('1010: Invalid Transaction: Custom error: 115'), CONTRACT_CODES)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); + expect(classifyError(await refused('1010: Invalid Transaction: Custom error: 170'), CONTRACT_CODES)).toStrictEqual({ errorCode: 'INVALID_DUST_PROOF', exitCode: 6 }); + }); +}); + +// The error-code parity table's rows for a contract script and a contract run +// (src/__tests__/error-code-parity.test.ts lists every typed error where mn +// throws it; these are the contract runner's own), each with what mn reported +// before codes were owned per package (a record) and what it reports. +describe('a contract script and a contract run, in the error-code parity table', () => { + /** What the runner rejects with when a generated script, its prelude first, runs `body` and fails. */ + async function scriptFailing(body: (port: number) => string): Promise { + const dir = mkdtempSync(join(tmpdir(), 'mn-code-parity-script-')); + try { + const wsModule = pathToFileURL(createRequire(import.meta.url).resolve('ws')).href; + const port = await closedPort(); + await executeScript({ dir, script: SCRIPT_PRELUDE + rpcClientCode(port, wsModule) + body(port), overlaySdk: false, packages: { packages: [], packageFolder: () => null, set: 'rc' } }); + throw new Error('expected the script to fail'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + } + /** The connector's answer to a submission the node refused with `reason`: its own words over the SDK's error, marked with mn's code. */ + const connectorRefusal = async (reason: string) => { + const failure = Effect.runPromise(Effect.fail(new SubmissionError({ message: 'Transaction submission error', cause: new Error(reason) }))); + const thrown = await failure.catch((e: Error) => e); + return withEngineCode(new Error(`Transaction submission failed: [SubmissionError] Transaction submission error → ${reason}`, { cause: thrown })); + }; + /** What the function throws; fails the test when it throws nothing. */ + async function thrownBy(run: () => unknown): Promise { + try { + await run(); + } catch (err) { + return err as Error; + } + throw new Error('expected it to throw'); + } + + type Classified = { errorCode: string; exitCode: number }; + const as = (errorCode: string, exitCode: number): Classified => ({ errorCode, exitCode }); + /** [where it is thrown, how to throw it, what mn reported before codes were owned per package (a record), what it reports]. */ + type Row = [string, () => unknown, Classified, Classified]; + const ROWS: Row[] = [ + // Connections a contract script could not make, named where they are met. + ['a contract script that cannot reach mn serve', () => scriptFailing(() => 'await rpcConnect();\n'), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], + ["a contract script's fetch failing (approved Y53: was UNKNOWN)", () => scriptFailing((port) => `await fetch('http://127.0.0.1:${port}/');\n`), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], + // Balance: exit 5. + ['a contract run short of Dust at mn serve', () => scriptFailureAtServe(() => createApiError('InternalError', "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00.", 'DUST_REQUIRED')).then((err) => { throw err; }), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], + // A contract run: the connector at mn serve, the wire, and the script's process. + ['a contract run the node refused at mn serve (approved Y54: was UNKNOWN)', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 199'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('UNKNOWN', 1), as('TX_REJECTED', 6)], + ['a contract run refused a spent coin at mn serve', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 115'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('STALE_UTXO', 6), as('STALE_UTXO', 6)], + ['a contract run whose proof timed out at mn serve (approved Y54: was UNKNOWN)', () => scriptFailureAtServe(() => new ProofTimeoutError()).then((err) => { throw err; }), as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], + ['a contract run the operator refused at mn serve', () => scriptFailureAtServe(() => createApiError('Rejected', OPERATOR_REJECTED_MESSAGE, 'TX_REJECTED')).then((err) => { throw err; }), as('TX_REJECTED', 6), as('TX_REJECTED', 6)], + // General: exit 1. + ['no Node.js for a contract script (approved: was UNKNOWN)', () => scriptRuntime({ execPath: '/opt/bun/bin/bun', isNode: false }, ''), as('UNKNOWN', 1), as('NO_NODE_RUNTIME', 1)], + ]; + + it.each(ROWS)('%s', async (_where, throwIt, _before, now) => { + expect(classifyError(await thrownBy(throwIt), CONTRACT_CODES)).toStrictEqual(now); + }); + + it('marks every row whose code changed as approved', () => { + const changed = ROWS.filter(([, , before, now]) => before.errorCode !== now.errorCode || before.exitCode !== now.exitCode); + expect(changed.length).toBeGreaterThan(0); + for (const [where] of changed) expect(where).toMatch(/\(approved\b/); }); }); diff --git a/src/__tests__/contract-script-packages.test.ts b/packages/contract/src/__tests__/contract-script-packages.test.ts similarity index 100% rename from src/__tests__/contract-script-packages.test.ts rename to packages/contract/src/__tests__/contract-script-packages.test.ts diff --git a/src/__tests__/contract-validate.test.ts b/packages/contract/src/__tests__/contract-validate.test.ts similarity index 100% rename from src/__tests__/contract-validate.test.ts rename to packages/contract/src/__tests__/contract-validate.test.ts diff --git a/src/__tests__/helpers/serve-script-failure.ts b/packages/contract/src/__tests__/helpers/serve-script-failure.ts similarity index 96% rename from src/__tests__/helpers/serve-script-failure.ts rename to packages/contract/src/__tests__/helpers/serve-script-failure.ts index d0ea4414..b06ed27c 100644 --- a/src/__tests__/helpers/serve-script-failure.ts +++ b/packages/contract/src/__tests__/helpers/serve-script-failure.ts @@ -10,7 +10,7 @@ import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; import type { AddressInfo } from 'node:net'; import { SCRIPT_PRELUDE, executeScript, rpcClientCode } from '../../lib/contract/runner.ts'; -import { createRpcServer } from '../../lib/ws-rpc.ts'; +import { createRpcServer } from '@kuiralabs/midnight-connect'; import { createHost } from '@kuiralabs/midnight-cli-core'; /** What the runner rejects with when a script's call to mn serve fails with what `failure` throws. */ diff --git a/src/__tests__/private-state-secret.test.ts b/packages/contract/src/__tests__/private-state-secret.test.ts similarity index 100% rename from src/__tests__/private-state-secret.test.ts rename to packages/contract/src/__tests__/private-state-secret.test.ts diff --git a/src/__tests__/witness-discovery.test.ts b/packages/contract/src/__tests__/witness-discovery.test.ts similarity index 100% rename from src/__tests__/witness-discovery.test.ts rename to packages/contract/src/__tests__/witness-discovery.test.ts diff --git a/packages/contract/src/commands.ts b/packages/contract/src/commands.ts new file mode 100644 index 00000000..e1bfa0f7 --- /dev/null +++ b/packages/contract/src/commands.ts @@ -0,0 +1,8 @@ +// @kuiralabs/midnight-contract/commands: the contract and inspect-cost +// commands, contract's codes and its agent guidance, for the shell that +// installs them. + +export { contractCodes } from './commands/contract.codes.ts'; +export { contractDefinition } from './commands/contract.definition.ts'; +export { contractGuidance } from './commands/contract.guidance.ts'; +export { inspectCostDefinition } from './commands/inspect-cost.definition.ts'; diff --git a/src/commands/contract.codes.ts b/packages/contract/src/commands/contract.codes.ts similarity index 100% rename from src/commands/contract.codes.ts rename to packages/contract/src/commands/contract.codes.ts diff --git a/src/commands/contract.definition.ts b/packages/contract/src/commands/contract.definition.ts similarity index 100% rename from src/commands/contract.definition.ts rename to packages/contract/src/commands/contract.definition.ts diff --git a/src/commands/contract.guidance.ts b/packages/contract/src/commands/contract.guidance.ts similarity index 100% rename from src/commands/contract.guidance.ts rename to packages/contract/src/commands/contract.guidance.ts diff --git a/src/commands/contract.ts b/packages/contract/src/commands/contract.ts similarity index 100% rename from src/commands/contract.ts rename to packages/contract/src/commands/contract.ts diff --git a/src/commands/inspect-cost.definition.ts b/packages/contract/src/commands/inspect-cost.definition.ts similarity index 100% rename from src/commands/inspect-cost.definition.ts rename to packages/contract/src/commands/inspect-cost.definition.ts diff --git a/src/commands/inspect-cost.ts b/packages/contract/src/commands/inspect-cost.ts similarity index 100% rename from src/commands/inspect-cost.ts rename to packages/contract/src/commands/inspect-cost.ts diff --git a/packages/contract/src/index.ts b/packages/contract/src/index.ts new file mode 100644 index 00000000..818c7145 --- /dev/null +++ b/packages/contract/src/index.ts @@ -0,0 +1,28 @@ +// @kuiralabs/midnight-contract: mn's contracts for a program and the packages +// above. Deploying a contract, calling a circuit and reading a contract's +// state, each called with plain values and paid through a payer; the requests +// they are built from (a dApp folder, the contract in it, its arguments); a +// compiled contract's circuits and witnesses; and the runner the packages +// above run a deploy, a call or a state read with in a dApp's folder, with +// the dApp's private state they share. Each name is listed, so the API is what +// this file says. The contract and inspect-cost commands, contract's codes and +// guidance are "./commands". + +export { type CallContractOptions, type CalledCircuit, callContract } from './lib/contract/call.ts'; +export { type DeployContractOptions, type DeployedContract, deployContract } from './lib/contract/deploy.ts'; +export { contractExists } from './lib/contract/exists.ts'; +export { type CircuitInfo, type CompactType, type ContractInfo, findContractInfo, type WitnessInfo } from './lib/contract/inspect.ts'; +export { clearDappPrivateState, PRIVATE_STATE_DATABASE } from './lib/contract/private-state.ts'; +export { + type ContractCallRequest, contractCallRequest, type ContractDeployRequest, contractDeployRequest, type ContractLocation +} from './lib/contract/request.ts'; +export { + type CallOptions, type CallResult, ContractScriptError, type DeployOptions, type DeployResult, runCall, runDeploy, + type RunnerOptions, runState, type StateOptions, type StateResult +} from './lib/contract/runner.ts'; +export { type ContractChecked } from './lib/contract/runtime-check.ts'; +export { + type ContractState, type ParsedContractState, type RawContractState, readContractState, type ReadContractStateOptions, + type StateFallback, type StateReading +} from './lib/contract/state.ts'; +export { buildMissingWitnessError, findWitnessFile } from './lib/contract/witness-discovery.ts'; diff --git a/src/lib/chain-params.ts b/packages/contract/src/lib/chain-params.ts similarity index 100% rename from src/lib/chain-params.ts rename to packages/contract/src/lib/chain-params.ts diff --git a/src/lib/contract/arg-coerce.ts b/packages/contract/src/lib/contract/arg-coerce.ts similarity index 100% rename from src/lib/contract/arg-coerce.ts rename to packages/contract/src/lib/contract/arg-coerce.ts diff --git a/src/lib/contract/call.ts b/packages/contract/src/lib/contract/call.ts similarity index 100% rename from src/lib/contract/call.ts rename to packages/contract/src/lib/contract/call.ts diff --git a/src/lib/contract/deploy.ts b/packages/contract/src/lib/contract/deploy.ts similarity index 100% rename from src/lib/contract/deploy.ts rename to packages/contract/src/lib/contract/deploy.ts diff --git a/src/lib/contract/exists.ts b/packages/contract/src/lib/contract/exists.ts similarity index 100% rename from src/lib/contract/exists.ts rename to packages/contract/src/lib/contract/exists.ts diff --git a/src/lib/contract/inspect.ts b/packages/contract/src/lib/contract/inspect.ts similarity index 100% rename from src/lib/contract/inspect.ts rename to packages/contract/src/lib/contract/inspect.ts diff --git a/src/lib/contract/private-state-secret.ts b/packages/contract/src/lib/contract/private-state-secret.ts similarity index 100% rename from src/lib/contract/private-state-secret.ts rename to packages/contract/src/lib/contract/private-state-secret.ts diff --git a/src/lib/contract/private-state.ts b/packages/contract/src/lib/contract/private-state.ts similarity index 100% rename from src/lib/contract/private-state.ts rename to packages/contract/src/lib/contract/private-state.ts diff --git a/src/lib/contract/request.ts b/packages/contract/src/lib/contract/request.ts similarity index 100% rename from src/lib/contract/request.ts rename to packages/contract/src/lib/contract/request.ts diff --git a/src/lib/contract/runner.ts b/packages/contract/src/lib/contract/runner.ts similarity index 100% rename from src/lib/contract/runner.ts rename to packages/contract/src/lib/contract/runner.ts diff --git a/src/lib/contract/runtime-check.ts b/packages/contract/src/lib/contract/runtime-check.ts similarity index 100% rename from src/lib/contract/runtime-check.ts rename to packages/contract/src/lib/contract/runtime-check.ts diff --git a/src/lib/contract/served-wallet.ts b/packages/contract/src/lib/contract/served-wallet.ts similarity index 100% rename from src/lib/contract/served-wallet.ts rename to packages/contract/src/lib/contract/served-wallet.ts diff --git a/src/lib/contract/state.ts b/packages/contract/src/lib/contract/state.ts similarity index 100% rename from src/lib/contract/state.ts rename to packages/contract/src/lib/contract/state.ts diff --git a/src/lib/contract/validate.ts b/packages/contract/src/lib/contract/validate.ts similarity index 100% rename from src/lib/contract/validate.ts rename to packages/contract/src/lib/contract/validate.ts diff --git a/src/lib/contract/witness-discovery.ts b/packages/contract/src/lib/contract/witness-discovery.ts similarity index 100% rename from src/lib/contract/witness-discovery.ts rename to packages/contract/src/lib/contract/witness-discovery.ts diff --git a/packages/contract/tsconfig.build.json b/packages/contract/tsconfig.build.json new file mode 100644 index 00000000..70e97051 --- /dev/null +++ b/packages/contract/tsconfig.build.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node" + ] + }, + "include": [ + "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" + ] +} diff --git a/packages/dev/api-report.md b/packages/dev/api-report.md new file mode 100644 index 00000000..ca96dd38 --- /dev/null +++ b/packages/dev/api-report.md @@ -0,0 +1,35 @@ +# API report: @kuiralabs/midnight-dev + +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-dev` + +```ts +export declare function getComposePath(root: string): string; +export declare class LocalnetUnavailableError extends Error { + readonly code = "LOCALNET_UNAVAILABLE"; + constructor(); +} +export declare class PrepStepFailedError extends Error { + readonly code: string | undefined; + constructor(step: PrepStepId, cause: unknown); +} +``` + +## `@kuiralabs/midnight-dev/commands` + +```ts +export declare const devCodes: readonly [ + { + readonly code: "LOCALNET_UNAVAILABLE"; + readonly exitCode: 4; + readonly order: 160; + readonly summary: "`mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build."; + readonly recovery: "Ask the user to start their ledger-9 stack and point mn at it (endpoint config)."; + } +]; +export declare const devDefinition: CommandDefinition; +export declare const devGuidance: PackageGuidance; +export declare const localnetDefinition: CommandDefinition; +export declare const testDefinition: CommandDefinition; +``` diff --git a/packages/dev/package.json b/packages/dev/package.json new file mode 100644 index 00000000..bd81f5e7 --- /dev/null +++ b/packages/dev/package.json @@ -0,0 +1,44 @@ +{ + "name": "@kuiralabs/midnight-dev", + "version": "0.1.0-rc.1", + "type": "module", + "description": "Development for the Midnight CLI packages: mn dev (compile, deploy and test a dApp as its files change, on dev wallets), mn test (prepare, run and scaffold a dApp's test suites) and mn localnet (a local network in Docker)", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/dev" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-connect": "0.1.0-rc.1", + "@kuiralabs/midnight-contract": "0.1.0-rc.1", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + } +} diff --git a/src/__tests__/agent-report-no-failure.test.ts b/packages/dev/src/__tests__/agent-report-no-failure.test.ts similarity index 100% rename from src/__tests__/agent-report-no-failure.test.ts rename to packages/dev/src/__tests__/agent-report-no-failure.test.ts diff --git a/src/__tests__/ai-scaffold.test.ts b/packages/dev/src/__tests__/ai-scaffold.test.ts similarity index 99% rename from src/__tests__/ai-scaffold.test.ts rename to packages/dev/src/__tests__/ai-scaffold.test.ts index 88a1d42c..066e2741 100644 --- a/src/__tests__/ai-scaffold.test.ts +++ b/packages/dev/src/__tests__/ai-scaffold.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import { buildCliPrompt, buildUiPrompt, renderContractSummary, RESPONSE_FENCE } from '../lib/test/ai-prompts.ts'; import { generateCliScaffoldWithAI, generateUiScaffoldWithAI } from '../lib/test/ai-scaffold.ts'; -import type { CircuitInfo, ContractInfo } from '../lib/contract/inspect.ts'; +import type { CircuitInfo, ContractInfo } from '@kuiralabs/midnight-contract'; import type { ScreenCandidate } from '../lib/test/discover-screens.ts'; const counterContract: ContractInfo = { diff --git a/src/__tests__/browser-test-launch.test.ts b/packages/dev/src/__tests__/browser-test-launch.test.ts similarity index 100% rename from src/__tests__/browser-test-launch.test.ts rename to packages/dev/src/__tests__/browser-test-launch.test.ts diff --git a/src/__tests__/circuit-witness-deps.test.ts b/packages/dev/src/__tests__/circuit-witness-deps.test.ts similarity index 100% rename from src/__tests__/circuit-witness-deps.test.ts rename to packages/dev/src/__tests__/circuit-witness-deps.test.ts diff --git a/src/__tests__/dev-compile.test.ts b/packages/dev/src/__tests__/dev-compile.test.ts similarity index 100% rename from src/__tests__/dev-compile.test.ts rename to packages/dev/src/__tests__/dev-compile.test.ts diff --git a/src/__tests__/dev-detect-project.test.ts b/packages/dev/src/__tests__/dev-detect-project.test.ts similarity index 100% rename from src/__tests__/dev-detect-project.test.ts rename to packages/dev/src/__tests__/dev-detect-project.test.ts diff --git a/src/__tests__/dev-keys.test.ts b/packages/dev/src/__tests__/dev-keys.test.ts similarity index 100% rename from src/__tests__/dev-keys.test.ts rename to packages/dev/src/__tests__/dev-keys.test.ts diff --git a/src/__tests__/dev-test-runner.test.ts b/packages/dev/src/__tests__/dev-test-runner.test.ts similarity index 100% rename from src/__tests__/dev-test-runner.test.ts rename to packages/dev/src/__tests__/dev-test-runner.test.ts diff --git a/src/__tests__/dev-watch.test.ts b/packages/dev/src/__tests__/dev-watch.test.ts similarity index 100% rename from src/__tests__/dev-watch.test.ts rename to packages/dev/src/__tests__/dev-watch.test.ts diff --git a/src/__tests__/discover-screens.test.ts b/packages/dev/src/__tests__/discover-screens.test.ts similarity index 100% rename from src/__tests__/discover-screens.test.ts rename to packages/dev/src/__tests__/discover-screens.test.ts diff --git a/src/__tests__/localnet-cancellation.test.ts b/packages/dev/src/__tests__/localnet-cancellation.test.ts similarity index 87% rename from src/__tests__/localnet-cancellation.test.ts rename to packages/dev/src/__tests__/localnet-cancellation.test.ts index 51e6c724..5b43f264 100644 --- a/src/__tests__/localnet-cancellation.test.ts +++ b/packages/dev/src/__tests__/localnet-cancellation.test.ts @@ -4,7 +4,7 @@ // to, which kills the Docker client on cancel. No real Docker runs here: the // command and the start are given a stand-in runner, which answers as Docker // would, keeps each run's signal, and stops a run (its "kill") when the run's -// signal aborts, as lib/exec-program.ts's runner does (exec-program.test.ts +// signal aborts, as core's runner (lib/exec-program.ts) does (exec-program.test.ts // shows that one kills a real process). import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -13,10 +13,9 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { runLocalnet } from '../commands/localnet.ts'; import { startLocalnet, type DockerCall } from '../lib/localnet.ts'; -import { CancelledError, type ExecRun, type ExecRunner, parseArgs } from '@kuiralabs/midnight-cli-core'; -import { captureCommand } from '../lib/run-command.ts'; -import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; -import { ownCall } from './helpers/own-call.ts'; +import { CancelledError, type CallOutput, createCallContext, type ExecRun, type ExecRunner, parseArgs, runHandler } from '@kuiralabs/midnight-cli-core'; +import { captureOutput, type CapturedOutput } from '../../../../test-support/capture-output.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; /** One run the stand-in was given. */ interface Run { @@ -76,9 +75,23 @@ afterEach(() => { rmSync(home, { recursive: true, force: true }); }); -/** Runs `mn localnet --json` as the MCP server does, with the stand-in runner and the call's signal. */ -function localnet(subcommand: string, exec: ExecRunner, signal: AbortSignal): Promise> { - return captureCommand((args, ctx) => runLocalnet(args, ctx, exec), parseArgs(['localnet', subcommand, '--json']), ownCall({ signal })); +/** + * Runs `mn localnet --json` with the stand-in runner and the + * call's signal, as the MCP server runs a command: a call of its own on a test + * host, with its own SDK warnings, its result kept and its text for the person + * on stderr. + */ +async function localnet(subcommand: string, exec: ExecRunner, signal: AbortSignal): Promise> { + const args = parseArgs(['localnet', subcommand, '--json']); + const host = testHost(); + let result: Record = {}; + const output: CallOutput = { + result: (data) => { result = JSON.parse(JSON.stringify(data)) as Record; }, + stdout: (text) => { process.stderr.write(text); }, + stderr: (text) => { process.stderr.write(text); }, + }; + await host.sdkWarnings.run((warnings) => runHandler((callArgs, ctx) => runLocalnet(callArgs, ctx, exec), args, createCallContext({ host, args, signal, output, sdkWarnings: warnings }))); + return result; } describe('localnet commands, cancelled while Docker runs', () => { diff --git a/src/__tests__/localnet-docker-probe.test.ts b/packages/dev/src/__tests__/localnet-docker-probe.test.ts similarity index 97% rename from src/__tests__/localnet-docker-probe.test.ts rename to packages/dev/src/__tests__/localnet-docker-probe.test.ts index 28105e35..1210214d 100644 --- a/src/__tests__/localnet-docker-probe.test.ts +++ b/packages/dev/src/__tests__/localnet-docker-probe.test.ts @@ -13,7 +13,7 @@ import { pathToFileURL } from 'node:url'; // has no docker in it. const localnet = pathToFileURL(resolve(import.meta.dirname, '../lib/localnet.ts')).href; -const execProgram = pathToFileURL(resolve(import.meta.dirname, '../../packages/cli-core/src/lib/exec-program.ts')).href; +const execProgram = pathToFileURL(resolve(import.meta.dirname, '../../../cli-core/src/lib/exec-program.ts')).href; const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href; describe('checkDockerAvailable on a machine without Docker', () => { diff --git a/packages/dev/src/__tests__/localnet.test.ts b/packages/dev/src/__tests__/localnet.test.ts new file mode 100644 index 00000000..e11300f9 --- /dev/null +++ b/packages/dev/src/__tests__/localnet.test.ts @@ -0,0 +1,186 @@ +// The localnet library: the compose file it writes (its services, ports, +// health checks and restart policies) and its version, the refusal every start +// path meets on this ledger-9 build, which containers a clean removes, and how +// docker compose's status lines are read. The localnet command's arguments, +// help and its refused up are the shell's tests (src/__tests__/localnet-command.test.ts). + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'; +import { join } from 'path'; +import { tmpdir } from 'os'; +import { + COMPOSE_YAML, + COMPOSE_VERSION, + ensureComposeFile, + getComposePath, + LocalnetUnavailableError, + parseServiceStatus, +} from '../lib/localnet.ts'; + +describe('COMPOSE_YAML content', () => { + it('contains the node service with correct image', () => { + expect(COMPOSE_YAML).toContain('midnight-node:'); + }); + + it('contains the indexer service with correct image', () => { + expect(COMPOSE_YAML).toContain('indexer-standalone:'); + }); + + it('contains the proof-server service with correct image', () => { + expect(COMPOSE_YAML).toContain('proof-server:'); + }); + + it('exposes node port 9944', () => { + expect(COMPOSE_YAML).toContain('"9944:9944"'); + }); + + it('exposes indexer port 8088', () => { + expect(COMPOSE_YAML).toContain("'8088:8088'"); + }); + + it('exposes proof-server port 6300', () => { + expect(COMPOSE_YAML).toContain('"6300:6300"'); + }); + + it('includes healthcheck for node', () => { + expect(COMPOSE_YAML).toContain('http://localhost:9944/health'); + }); + + it('includes healthcheck for indexer', () => { + expect(COMPOSE_YAML).toContain('cat /var/run/indexer-standalone/running'); + }); + + it('has indexer depending on node', () => { + expect(COMPOSE_YAML).toContain('depends_on'); + expect(COMPOSE_YAML).toContain('condition: service_started'); + }); + + it('sets CFG_PRESET=dev for the node', () => { + expect(COMPOSE_YAML).toContain('CFG_PRESET: "dev"'); + }); + + it('starts with services: key (valid compose format)', () => { + expect(COMPOSE_YAML.trimStart()).toMatch(/^services:/); + }); + + // Regression: node + proof-server used to have no restart policy while only the + // indexer did. A Docker Desktop restart or any transient stop then left a + // half-dead localnet (indexer up, node gone) — surfacing as ws "Normal Closure" + // churn and a wedged dust sync. Every service must self-heal. + it('gives every service a restart policy so the localnet self-heals', () => { + const serviceBlock = (svc: string): string => { + const start = COMPOSE_YAML.indexOf(`\n ${svc}:`); + if (start < 0) return ''; + const rest = COMPOSE_YAML.slice(start + 1); + const next = rest.search(/\n {2}\S/); // next top-level (2-space) service key + return next < 0 ? rest : rest.slice(0, next + 1); + }; + for (const svc of ['proof-server', 'indexer', 'node']) { + const block = serviceBlock(svc); + expect(block, `service ${svc} present in compose`).not.toBe(''); + expect(block, `service ${svc} has a restart policy`).toMatch(/^\s+restart:/m); + } + }); +}); + +describe('COMPOSE_VERSION', () => { + it('is a semver-like string', () => { + expect(COMPOSE_VERSION).toMatch(/^\d+\.\d+\.\d+$/); + }); +}); + +describe('ledger-9 build: mn localnet cannot start a network', () => { + // The compose stack is ledger 8, which wallet-sdk 2.0 can't sync with, and + // no published indexer image runs ledger 9 yet. Every start path goes + // through ensureComposeFile, so it refuses there, before writing anything. + // A state root of the test's own, which nothing creates. + const root = join(tmpdir(), `midnight-localnet-ledger9-${process.pid}`); + const composeFingerprint = () => { + const path = getComposePath(root); + return existsSync(path) ? `${statSync(path).mtimeMs}:${readFileSync(path, 'utf-8').length}` : 'absent'; + }; + + it('ensureComposeFile refuses, says what to run instead, and writes nothing', () => { + const before = composeFingerprint(); + let err: unknown; + try { ensureComposeFile(root); } catch (e) { err = e; } + expect(err).toBeInstanceOf(LocalnetUnavailableError); + const msg = (err as Error).message; + expect(msg).toContain('ledger 9'); + expect(msg).toContain('--node'); + expect(msg).toContain('--indexer-ws'); + expect(msg).toContain('--proof-server'); + expect(msg).toContain('midnight config set'); + expect(composeFingerprint()).toBe(before); + }); +}); + +describe('ensureComposeFile', () => { + // Use a temp directory to test file writing logic without touching real ~/.midnight + const TEST_DIR = join(tmpdir(), `midnight-localnet-test-${process.pid}`); + const TEST_COMPOSE_PATH = join(TEST_DIR, 'compose.yml'); + const TEST_VERSION_PATH = join(TEST_DIR, '.version'); + + beforeEach(() => { + rmSync(TEST_DIR, { recursive: true, force: true }); + }); + + afterEach(() => { + rmSync(TEST_DIR, { recursive: true, force: true }); + }); + + it('compose YAML can be written and read back', () => { + mkdirSync(TEST_DIR, { recursive: true }); + writeFileSync(TEST_COMPOSE_PATH, COMPOSE_YAML, 'utf-8'); + writeFileSync(TEST_VERSION_PATH, COMPOSE_VERSION, 'utf-8'); + + const content = readFileSync(TEST_COMPOSE_PATH, 'utf-8'); + expect(content).toBe(COMPOSE_YAML); + + const version = readFileSync(TEST_VERSION_PATH, 'utf-8'); + expect(version).toBe(COMPOSE_VERSION); + }); + + it('version file can detect stale compose file', () => { + mkdirSync(TEST_DIR, { recursive: true }); + writeFileSync(TEST_COMPOSE_PATH, COMPOSE_YAML, 'utf-8'); + writeFileSync(TEST_VERSION_PATH, '0.0.1', 'utf-8'); + + const version = readFileSync(TEST_VERSION_PATH, 'utf-8').trim(); + expect(version).not.toBe(COMPOSE_VERSION); + }); +}); + +describe('localnet clean: which containers are mn\'s', () => { + it('removes only containers from mn\'s compose project, keeping any other with the same generic name', async () => { + const { partitionLocalnetContainers, LOCALNET_PROJECT } = await import('../lib/localnet.ts'); + expect(LOCALNET_PROJECT).toBe('localnet'); + expect(partitionLocalnetContainers([ + { name: 'node', project: 'localnet' }, // mn's (also an older mn's ledger-8 localnet) + { name: 'indexer', project: 'my-app' }, // someone else's compose service + { name: 'proof-server', project: '' }, // a plain docker run + ])).toEqual({ + remove: ['node'], + keep: [{ name: 'indexer', project: 'my-app' }, { name: 'proof-server', project: '' }], + }); + }); +}); + +describe('parseServiceStatus', () => { + it('reads one service per line, stopped ones included', () => { + const output = [ + JSON.stringify({ Service: 'node', State: 'running', Health: 'healthy', Image: 'midnightntwrk/midnight-node:1.0.0' }), + JSON.stringify({ Service: 'indexer', State: 'exited', Health: '', Image: 'midnightntwrk/indexer-standalone:4.3.3' }), + '', + ].join('\n'); + expect(parseServiceStatus(output)).toEqual([ + { name: 'node', state: 'running', health: 'healthy', port: '9944', image: 'midnightntwrk/midnight-node:1.0.0' }, + { name: 'indexer', state: 'exited', health: '', port: '8088', image: 'midnightntwrk/indexer-standalone:4.3.3' }, + ]); + }); + + it('skips a line that is not JSON and is empty for no output', () => { + expect(parseServiceStatus('time="..." level=warning msg="something"\n')).toEqual([]); + expect(parseServiceStatus('')).toEqual([]); + }); +}); diff --git a/packages/dev/src/__tests__/prep-runner-cancellation.test.ts b/packages/dev/src/__tests__/prep-runner-cancellation.test.ts new file mode 100644 index 00000000..1f18828c --- /dev/null +++ b/packages/dev/src/__tests__/prep-runner-cancellation.test.ts @@ -0,0 +1,47 @@ +// A cancelled `mn test run` starts no further prep step. The steps here need +// no chain: a cancel stops the run before the step would reach one. + +import { afterAll, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { runPrepSteps } from '../lib/test/prep-runner.ts'; +import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; +import { createSdkWarningRouter, CancelledError, classifyError, createHost } from '@kuiralabs/midnight-cli-core'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; +import { devCodes } from '../commands/dev.codes.ts'; +import { codeRegistry } from '../../../../test-support/core-codes.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; + +// The host the tests' calls run in: nobody to ask, notices dropped. +const host = createHost(); + +const config = { network: 'undeployed', prep: ['dust', 'mn-serve'] } as unknown as DappTestConfig; + +describe('runPrepSteps', () => { + it('starts no step once the run is cancelled', async () => { + const controller = new AbortController(); + controller.abort(); + const started: string[] = []; + await expect(runPrepSteps(config, '/nonexistent', createPrepContext('/nonexistent/.midnight', host, createSdkWarningRouter().openCall().warnings, controller.signal), { + onStepStart: (step) => started.push(step), + onStepComplete: () => {}, + onMessage: () => {}, + })).rejects.toBeInstanceOf(CancelledError); + expect(started).toEqual([]); + }); +}); + +// The error-code parity table's row for a prep step (src/__tests__/error-code-parity.test.ts +// lists every typed error where mn throws it; this one is the test runner's own). +describe('a prep step that failed with no code, in the error-code parity table', () => { + // A state root of the test's own, never ~/.midnight, with the engines mn ships. + const root = mkdtempSync(join(tmpdir(), 'mn-prep-parity-')); + afterAll(() => rmSync(root, { recursive: true, force: true })); + + it('reports UNKNOWN, exit 1, as before codes were owned per package', async () => { + const err = await runPrepSteps({ network: 'undeployed', prep: ['no-such-step'] } as unknown as DappTestConfig, root, createPrepContext(root, createHost({ paths: { stateRoot: root, home: root }, engineLoader: loadInstalledEngine }), createSdkWarningRouter().openCall().warnings, new AbortController().signal), { onStepStart: () => {}, onStepComplete: () => {}, onMessage: () => {} }) + .then(() => { throw new Error('expected the prep step to fail'); }, (e: Error) => e); + expect(classifyError(err, codeRegistry(coreCodes, devCodes))).toStrictEqual({ errorCode: 'UNKNOWN', exitCode: 1 }); + }); +}); diff --git a/src/__tests__/provision-wallets.test.ts b/packages/dev/src/__tests__/provision-wallets.test.ts similarity index 98% rename from src/__tests__/provision-wallets.test.ts rename to packages/dev/src/__tests__/provision-wallets.test.ts index d1f9d627..e340239f 100644 --- a/src/__tests__/provision-wallets.test.ts +++ b/packages/dev/src/__tests__/provision-wallets.test.ts @@ -8,7 +8,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { provisionDevWallets, type ProvisionSteps } from '../lib/dev/provision-wallets.ts'; -import { stateRootIn } from '../../test-support/state-root-in.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; let home: string; let originalHome: string | undefined; diff --git a/src/__tests__/test-assertions.test.ts b/packages/dev/src/__tests__/test-assertions.test.ts similarity index 100% rename from src/__tests__/test-assertions.test.ts rename to packages/dev/src/__tests__/test-assertions.test.ts diff --git a/src/__tests__/test-contract-cache.test.ts b/packages/dev/src/__tests__/test-contract-cache.test.ts similarity index 100% rename from src/__tests__/test-contract-cache.test.ts rename to packages/dev/src/__tests__/test-contract-cache.test.ts diff --git a/src/__tests__/test-create.test.ts b/packages/dev/src/__tests__/test-create.test.ts similarity index 99% rename from src/__tests__/test-create.test.ts rename to packages/dev/src/__tests__/test-create.test.ts index a4410956..2bf900ce 100644 --- a/src/__tests__/test-create.test.ts +++ b/packages/dev/src/__tests__/test-create.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'; import { placeholderArg, placeholderArgsFor, buildScaffold } from '../lib/test/create.ts'; import { writeScaffold } from '../lib/test/create-writer.ts'; -import type { CircuitInfo, CompactType } from '../lib/contract/inspect.ts'; +import type { CircuitInfo, CompactType } from '@kuiralabs/midnight-contract'; const tmpBase = join(tmpdir(), 'mn-test-create-' + Date.now()); diff --git a/src/__tests__/test-discovery.test.ts b/packages/dev/src/__tests__/test-discovery.test.ts similarity index 100% rename from src/__tests__/test-discovery.test.ts rename to packages/dev/src/__tests__/test-discovery.test.ts diff --git a/src/__tests__/test-results.test.ts b/packages/dev/src/__tests__/test-results.test.ts similarity index 100% rename from src/__tests__/test-results.test.ts rename to packages/dev/src/__tests__/test-results.test.ts diff --git a/packages/dev/src/commands.ts b/packages/dev/src/commands.ts new file mode 100644 index 00000000..36eea2a7 --- /dev/null +++ b/packages/dev/src/commands.ts @@ -0,0 +1,8 @@ +// @kuiralabs/midnight-dev/commands: the dev, test and localnet commands, dev's +// codes and its agent guidance, for the shell that installs them. + +export { devCodes } from './commands/dev.codes.ts'; +export { devDefinition } from './commands/dev.definition.ts'; +export { devGuidance } from './commands/dev.guidance.ts'; +export { localnetDefinition } from './commands/localnet.definition.ts'; +export { testDefinition } from './commands/test.definition.ts'; diff --git a/src/commands/dev.codes.ts b/packages/dev/src/commands/dev.codes.ts similarity index 100% rename from src/commands/dev.codes.ts rename to packages/dev/src/commands/dev.codes.ts diff --git a/src/commands/dev.definition.ts b/packages/dev/src/commands/dev.definition.ts similarity index 100% rename from src/commands/dev.definition.ts rename to packages/dev/src/commands/dev.definition.ts diff --git a/src/commands/dev.guidance.ts b/packages/dev/src/commands/dev.guidance.ts similarity index 100% rename from src/commands/dev.guidance.ts rename to packages/dev/src/commands/dev.guidance.ts diff --git a/src/commands/dev.ts b/packages/dev/src/commands/dev.ts similarity index 98% rename from src/commands/dev.ts rename to packages/dev/src/commands/dev.ts index fd3a4eb7..3ed9a4cb 100644 --- a/src/commands/dev.ts +++ b/packages/dev/src/commands/dev.ts @@ -17,7 +17,7 @@ import { DEFAULT_DEV_AIRDROP_AMOUNT, } from '../lib/dev/provision-wallets.ts'; import { startKeyDispatcher } from '../ui/dev-keys.ts'; -import { findWitnessFile, buildMissingWitnessError } from '../lib/contract/witness-discovery.ts'; +import { findWitnessFile, buildMissingWitnessError } from '@kuiralabs/midnight-contract'; /** Wallet used when `d` deploys. Must be one of the provisioned dev-* names. */ @@ -278,7 +278,7 @@ async function runProjectTests(output: CallOutput, project: ProjectInfo, signal? */ async function readDeclaredWitnesses(projectRoot: string): Promise { try { - const { findContractInfo } = await import('../lib/contract/inspect.ts'); + const { findContractInfo } = await import('@kuiralabs/midnight-contract'); const { info } = findContractInfo(projectRoot); return info.witnesses.map((w) => w.name); } catch { diff --git a/src/commands/localnet.definition.ts b/packages/dev/src/commands/localnet.definition.ts similarity index 100% rename from src/commands/localnet.definition.ts rename to packages/dev/src/commands/localnet.definition.ts diff --git a/src/commands/localnet.ts b/packages/dev/src/commands/localnet.ts similarity index 99% rename from src/commands/localnet.ts rename to packages/dev/src/commands/localnet.ts index 5129beb2..bc38cf86 100644 --- a/src/commands/localnet.ts +++ b/packages/dev/src/commands/localnet.ts @@ -169,7 +169,7 @@ async function handleDown(jsonMode: boolean, ctx: CallContext, docker: DockerCal // after the chain reset, causing "NotOpenError: Database failed to open" // (corruption) on the next `mn contract deploy/call`. Best-effort: only // touches the store in the cwd, never scans the filesystem. - const { PRIVATE_STATE_DATABASE, clearDappPrivateState } = await import('../lib/contract/private-state.ts'); + const { PRIVATE_STATE_DATABASE, clearDappPrivateState } = await import('@kuiralabs/midnight-contract'); const leveldbWiped = clearDappPrivateState(process.cwd()); spinner.stop('Local network removed (containers, networks, volumes, caches)'); diff --git a/src/commands/test.definition.ts b/packages/dev/src/commands/test.definition.ts similarity index 100% rename from src/commands/test.definition.ts rename to packages/dev/src/commands/test.definition.ts diff --git a/src/commands/test.ts b/packages/dev/src/commands/test.ts similarity index 99% rename from src/commands/test.ts rename to packages/dev/src/commands/test.ts index 25cd8ed6..0c81f269 100644 --- a/src/commands/test.ts +++ b/packages/dev/src/commands/test.ts @@ -120,7 +120,7 @@ function browserOptionsFromFlags(prefilled: Partial): BrowserOpt async function handleCreate(args: ParsedArgs, jsonMode: boolean, ctx: CallContext): Promise { const { resolve } = await import('node:path'); - const { findContractInfo } = await import('../lib/contract/inspect.ts'); + const { findContractInfo } = await import('@kuiralabs/midnight-contract'); const { buildScaffold } = await import('../lib/test/create.ts'); const { writeScaffold } = await import('../lib/test/create-writer.ts'); const promptHelpers = await import('../ui/test-create-prompt.ts'); @@ -238,7 +238,7 @@ async function handleCreate(args: ParsedArgs, jsonMode: boolean, ctx: CallContex */ type AiScaffoldDeps = { strategy: CreateStrategy; - info: import('../lib/contract/inspect.ts').ContractInfo; + info: import('@kuiralabs/midnight-contract').ContractInfo; dappDir: string; browser: BrowserOptions | undefined; network: ReturnType; diff --git a/packages/dev/src/index.ts b/packages/dev/src/index.ts new file mode 100644 index 00000000..afba7411 --- /dev/null +++ b/packages/dev/src/index.ts @@ -0,0 +1,9 @@ +// @kuiralabs/midnight-dev: what mn's development commands leave for a program +// and the packages above. The errors a caller classifies them by (localnet +// refused on this build, a test run's failed prep step), and where a state +// root keeps the localnet's compose file. Each name is listed, so the API is +// what this file says. The dev, test and localnet commands, dev's codes and +// guidance are "./commands". + +export { getComposePath, LocalnetUnavailableError } from './lib/localnet.ts'; +export { PrepStepFailedError } from './lib/test/prep-runner.ts'; diff --git a/src/lib/dev/compile.ts b/packages/dev/src/lib/dev/compile.ts similarity index 100% rename from src/lib/dev/compile.ts rename to packages/dev/src/lib/dev/compile.ts diff --git a/src/lib/dev/deploy.ts b/packages/dev/src/lib/dev/deploy.ts similarity index 90% rename from src/lib/dev/deploy.ts rename to packages/dev/src/lib/dev/deploy.ts index a0d2cdf0..e027bc84 100644 --- a/src/lib/dev/deploy.ts +++ b/packages/dev/src/lib/dev/deploy.ts @@ -3,8 +3,7 @@ // wallets on the local network. What its steps say goes to `progress`; the // SDK's warnings go to the deploying call's `sdkWarnings`. -import { deployContract, type DeployedContract } from '../contract/deploy.ts'; -import { contractDeployRequest } from '../contract/request.ts'; +import { deployContract, type DeployedContract, contractDeployRequest } from '@kuiralabs/midnight-contract'; import type { Payer, Host, NetworkName, CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; diff --git a/src/lib/dev/detect-project.ts b/packages/dev/src/lib/dev/detect-project.ts similarity index 100% rename from src/lib/dev/detect-project.ts rename to packages/dev/src/lib/dev/detect-project.ts diff --git a/src/lib/dev/localnet-ready.ts b/packages/dev/src/lib/dev/localnet-ready.ts similarity index 100% rename from src/lib/dev/localnet-ready.ts rename to packages/dev/src/lib/dev/localnet-ready.ts diff --git a/src/lib/dev/provision-wallets.ts b/packages/dev/src/lib/dev/provision-wallets.ts similarity index 100% rename from src/lib/dev/provision-wallets.ts rename to packages/dev/src/lib/dev/provision-wallets.ts diff --git a/src/lib/dev/test.ts b/packages/dev/src/lib/dev/test.ts similarity index 100% rename from src/lib/dev/test.ts rename to packages/dev/src/lib/dev/test.ts diff --git a/src/lib/dev/watch.ts b/packages/dev/src/lib/dev/watch.ts similarity index 100% rename from src/lib/dev/watch.ts rename to packages/dev/src/lib/dev/watch.ts diff --git a/src/lib/localnet.ts b/packages/dev/src/lib/localnet.ts similarity index 100% rename from src/lib/localnet.ts rename to packages/dev/src/lib/localnet.ts diff --git a/src/lib/test/actions-runner.ts b/packages/dev/src/lib/test/actions-runner.ts similarity index 98% rename from src/lib/test/actions-runner.ts rename to packages/dev/src/lib/test/actions-runner.ts index 8acfe9b8..5efc7456 100644 --- a/src/lib/test/actions-runner.ts +++ b/packages/dev/src/lib/test/actions-runner.ts @@ -4,11 +4,9 @@ import { existsSync, readFileSync } from 'node:fs'; import type { TestAction, DappTestConfig } from './types.ts'; import type { NetworkConfig, NetworkName, HostEngines } from '@kuiralabs/midnight-cli-core'; -import { runDeploy, runCall, runState, type StateResult } from '../contract/runner.ts'; -import { findContractInfo, type ContractInfo } from '../contract/inspect.ts'; +import { runDeploy, runCall, runState, type StateResult, findContractInfo, type ContractInfo, contractExists } from '@kuiralabs/midnight-contract'; import { analyzeWitnessDependencies } from './circuit-witness-deps.ts'; import { findContractSourcePath } from './ai-scaffold.ts'; -import { contractExists } from '../contract/exists.ts'; import { loadContractCache, saveContractCache } from './contract-cache.ts'; export interface ActionResult { diff --git a/src/lib/test/ai-prompts.ts b/packages/dev/src/lib/test/ai-prompts.ts similarity index 99% rename from src/lib/test/ai-prompts.ts rename to packages/dev/src/lib/test/ai-prompts.ts index 0e2d19e7..833567b4 100644 --- a/src/lib/test/ai-prompts.ts +++ b/packages/dev/src/lib/test/ai-prompts.ts @@ -7,7 +7,7 @@ // against our schemas; a malformed response triggers fallback to the // deterministic scaffolder. -import type { CircuitInfo } from '../contract/inspect.ts'; +import type { CircuitInfo } from '@kuiralabs/midnight-contract'; // ── Shared ───────────────────────────────────────────────────────── diff --git a/src/lib/test/ai-scaffold.ts b/packages/dev/src/lib/test/ai-scaffold.ts similarity index 99% rename from src/lib/test/ai-scaffold.ts rename to packages/dev/src/lib/test/ai-scaffold.ts index ee5d8d98..99a9b1ad 100644 --- a/src/lib/test/ai-scaffold.ts +++ b/packages/dev/src/lib/test/ai-scaffold.ts @@ -11,7 +11,7 @@ import { CancelledError } from '@kuiralabs/midnight-cli-core'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; -import type { CircuitInfo, ContractInfo } from '../contract/inspect.ts'; +import type { CircuitInfo, ContractInfo } from '@kuiralabs/midnight-contract'; import type { BrowserMode, DappTestConfig, NetworkName, TestAction, TestActions, TestAssertions, TestSuite, PrepStepId } from './types.ts'; import type { ScaffoldOutput } from './create.ts'; import { buildCliPrompt, buildUiPrompt, RESPONSE_FENCE, renderContractSummary } from './ai-prompts.ts'; diff --git a/src/lib/test/assertions.ts b/packages/dev/src/lib/test/assertions.ts similarity index 100% rename from src/lib/test/assertions.ts rename to packages/dev/src/lib/test/assertions.ts diff --git a/src/lib/test/browser-test.ts b/packages/dev/src/lib/test/browser-test.ts similarity index 100% rename from src/lib/test/browser-test.ts rename to packages/dev/src/lib/test/browser-test.ts diff --git a/src/lib/test/build-manager.ts b/packages/dev/src/lib/test/build-manager.ts similarity index 100% rename from src/lib/test/build-manager.ts rename to packages/dev/src/lib/test/build-manager.ts diff --git a/src/lib/test/circuit-witness-deps.ts b/packages/dev/src/lib/test/circuit-witness-deps.ts similarity index 100% rename from src/lib/test/circuit-witness-deps.ts rename to packages/dev/src/lib/test/circuit-witness-deps.ts diff --git a/src/lib/test/contract-cache.ts b/packages/dev/src/lib/test/contract-cache.ts similarity index 100% rename from src/lib/test/contract-cache.ts rename to packages/dev/src/lib/test/contract-cache.ts diff --git a/src/lib/test/create-writer.ts b/packages/dev/src/lib/test/create-writer.ts similarity index 100% rename from src/lib/test/create-writer.ts rename to packages/dev/src/lib/test/create-writer.ts diff --git a/src/lib/test/create.ts b/packages/dev/src/lib/test/create.ts similarity index 99% rename from src/lib/test/create.ts rename to packages/dev/src/lib/test/create.ts index c8516d90..197ae8f3 100644 --- a/src/lib/test/create.ts +++ b/packages/dev/src/lib/test/create.ts @@ -6,7 +6,7 @@ // defaults so the user can `mn test create && mn test run` and see a passing // suite immediately, then edit args / add assertions to taste. -import type { CircuitInfo, CompactType } from '../contract/inspect.ts'; +import type { CircuitInfo, CompactType } from '@kuiralabs/midnight-contract'; import type { BrowserMode, DappTestConfig, diff --git a/src/lib/test/discover-screens.ts b/packages/dev/src/lib/test/discover-screens.ts similarity index 100% rename from src/lib/test/discover-screens.ts rename to packages/dev/src/lib/test/discover-screens.ts diff --git a/src/lib/test/discovery.ts b/packages/dev/src/lib/test/discovery.ts similarity index 100% rename from src/lib/test/discovery.ts rename to packages/dev/src/lib/test/discovery.ts diff --git a/src/lib/test/prep-runner.ts b/packages/dev/src/lib/test/prep-runner.ts similarity index 99% rename from src/lib/test/prep-runner.ts rename to packages/dev/src/lib/test/prep-runner.ts index cc9faca4..a551085a 100644 --- a/src/lib/test/prep-runner.ts +++ b/packages/dev/src/lib/test/prep-runner.ts @@ -7,7 +7,7 @@ import { resolveWalletPath, unlockWallet } from '@kuiralabs/midnight-wallet'; import { assertLedger9StackReachable, assertLedgerSupported } from '@kuiralabs/midnight-chain'; import type { DappTestConfig, PrepStepId, PrepStepResult, PrepContext, PrepCallbacks } from './types.ts'; -import { startServeOrReuse } from '../serve-manager.ts'; +import { startServeOrReuse } from '@kuiralabs/midnight-connect'; import { startBuild } from './build-manager.ts'; /** A prep step failed: the step's own error is its cause, and its code (DUST_REQUIRED, …) is this one's. */ diff --git a/src/lib/test/results.ts b/packages/dev/src/lib/test/results.ts similarity index 100% rename from src/lib/test/results.ts rename to packages/dev/src/lib/test/results.ts diff --git a/src/lib/test/teardown.ts b/packages/dev/src/lib/test/teardown.ts similarity index 100% rename from src/lib/test/teardown.ts rename to packages/dev/src/lib/test/teardown.ts diff --git a/src/lib/test/types.ts b/packages/dev/src/lib/test/types.ts similarity index 98% rename from src/lib/test/types.ts rename to packages/dev/src/lib/test/types.ts index 32ad17d0..80801a85 100644 --- a/src/lib/test/types.ts +++ b/packages/dev/src/lib/test/types.ts @@ -1,6 +1,6 @@ // Test framework types — schemas for dapp.test.json, suite configs, assertions, and results. -import type { ServeHandle } from '../serve-manager.ts'; +import type { ServeHandle } from '@kuiralabs/midnight-connect'; import type { UnlockHost } from '@kuiralabs/midnight-wallet'; import type { CallSdkWarnings, NetworkName } from '@kuiralabs/midnight-cli-core'; diff --git a/src/ui/dev-keys.ts b/packages/dev/src/ui/dev-keys.ts similarity index 100% rename from src/ui/dev-keys.ts rename to packages/dev/src/ui/dev-keys.ts diff --git a/src/ui/test-create-prompt.ts b/packages/dev/src/ui/test-create-prompt.ts similarity index 99% rename from src/ui/test-create-prompt.ts rename to packages/dev/src/ui/test-create-prompt.ts index 3d561a50..2e9e2d68 100644 --- a/src/ui/test-create-prompt.ts +++ b/packages/dev/src/ui/test-create-prompt.ts @@ -6,7 +6,7 @@ import { existsSync, statSync } from 'node:fs'; import * as readline from 'node:readline'; import { teal, dim, yellow } from '@kuiralabs/midnight-cli-core/ui'; import type { CreateStrategy, BrowserOptions } from '../lib/test/create.ts'; -import type { CircuitInfo } from '../lib/contract/inspect.ts'; +import type { CircuitInfo } from '@kuiralabs/midnight-contract'; import type { BrowserMode } from '../lib/test/types.ts'; import { discoverScreens, discoverScreensInDir, type ScreenCandidate } from '../lib/test/discover-screens.ts'; diff --git a/packages/dev/tsconfig.build.json b/packages/dev/tsconfig.build.json new file mode 100644 index 00000000..70e97051 --- /dev/null +++ b/packages/dev/tsconfig.build.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node" + ] + }, + "include": [ + "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" + ] +} diff --git a/scripts/api-report.mjs b/scripts/api-report.mjs index 0e2af99c..b54129ad 100644 --- a/scripts/api-report.mjs +++ b/scripts/api-report.mjs @@ -21,7 +21,7 @@ import { barrelExports } from './check-layering.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); /** The public packages, by folder under packages/. */ -export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta', 'wallet']; +export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta', 'wallet', 'contract', 'connect', 'dev']; /** The report's path for the package in `dir` (a folder under packages/). */ export function reportPath(dir) { diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 6607c94d..cc192685 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -154,6 +154,9 @@ export const WORKSPACE_PACKAGES = [ { name: '@kuiralabs/midnight-cli-core', root: join(ROOT, 'packages', 'cli-core'), dir: join(ROOT, 'packages', 'cli-core', 'src'), home: 'core' }, { name: '@kuiralabs/midnight-chain', root: join(ROOT, 'packages', 'chain'), dir: join(ROOT, 'packages', 'chain', 'src'), home: 'chain' }, { name: '@kuiralabs/midnight-wallet', root: join(ROOT, 'packages', 'wallet'), dir: join(ROOT, 'packages', 'wallet', 'src'), home: 'wallet' }, + { name: '@kuiralabs/midnight-contract', root: join(ROOT, 'packages', 'contract'), dir: join(ROOT, 'packages', 'contract', 'src'), home: 'contract' }, + { name: '@kuiralabs/midnight-connect', root: join(ROOT, 'packages', 'connect'), dir: join(ROOT, 'packages', 'connect', 'src'), home: 'connect' }, + { name: '@kuiralabs/midnight-dev', root: join(ROOT, 'packages', 'dev'), dir: join(ROOT, 'packages', 'dev', 'src'), home: 'dev' }, // The rc engine: its files read as engine/rc/, its index the package itself. { name: '@kuiralabs/midnight-engine-rc', root: join(ROOT, 'packages', 'engine-rc'), dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/', home: 'engine' }, { name: '@kuiralabs/midnight-engine-beta', root: join(ROOT, 'packages', 'engine-beta'), dir: join(ROOT, 'packages', 'engine-beta', 'src'), prefix: 'engine/beta/', home: 'engine' }, diff --git a/scripts/code-reach.mjs b/scripts/code-reach.mjs index e705b8ca..4b48d6c1 100644 --- a/scripts/code-reach.mjs +++ b/scripts/code-reach.mjs @@ -135,7 +135,7 @@ export const CUT_IMPORTS = ENGINE_SETS.flatMap((set) => [...new Set(Object.value /** What the shell gives a command whose definition's `shell` asks for it, and the module it loads. */ export const SHELL_PROVISIONS = { - payer: 'src/lib/serve-payer.ts', + payer: 'packages/connect/src/lib/serve-payer.ts', protectors: 'src/lib/grant/account-protector.ts', }; diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 72daca8a..dcc3f39f 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -3,7 +3,8 @@ // packages, installs mn globally from it into an empty prefix, and checks the // tree the install holds still works: one copy of each WASM package per SDK // engine (the shrinkwrap mn ships keeps each engine's set apart), each engine -// loading, and the files the code reads at run time. +// loading, the packages a contract run's script imports, and the files the +// code reads at run time. // // The test suite runs on the lockfile's tree, which a consumer never sees. Two // features broke that way without a test noticing: a newer @scure/base refused @@ -188,6 +189,53 @@ try { check(`the ${network === 'stagenet' ? 'beta' : 'rc'} engine derives a ${network} address`, derived.startsWith(prefixOf), derived.slice(0, 40)); } + // A contract run from the install: the contract package's runner has the + // network's engine write the script, links the packages it imports into the + // dApp's folder from where the engine finds each by name (never by a path + // from the runner's own package), and runs it with Node. Each engine finds + // every package its scripts import; a state read of a compiled contract gets + // as far as asking the indexer (every import resolved, the dApp's contract + // module loaded), which refuses the connection, reported as NETWORK_ERROR + // from the script's marked line; and the dApp's folder is left as it was. + for (const [network, set] of [['undeployed', 'rc'], ['stagenet', 'beta']]) { + const dapp = join(work, `dapp-${set}`); + const ran = JSON.parse(run(process.execPath, ['--input-type=module', '-e', ` + import { mkdirSync, readdirSync, writeFileSync } from 'node:fs'; + import { join } from 'node:path'; + import { createHost, getNetworkConfig } from '@kuiralabs/midnight-cli-core'; + import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; + import { runState } from '@kuiralabs/midnight-contract'; + const [dapp, network, home] = process.argv.slice(1); + const host = createHost({ + paths: { stateRoot: join(home, '.midnight'), home }, + engineLoader: async (set, host) => set === 'beta' ? createBetaEngine(host) : createRcEngine(host), + }); + const { scripts } = (await host.engines.for(network)).contracts; + const missing = scripts.packages.filter((name) => scripts.packageFolder(name) === null); + const managedDir = join(dapp, 'managed', 'counter'); + mkdirSync(join(managedDir, 'compiler'), { recursive: true }); + mkdirSync(join(managedDir, 'contract'), { recursive: true }); + writeFileSync(join(dapp, 'package.json'), JSON.stringify({ name: 'dapp', private: true, type: 'module' })); + writeFileSync(join(managedDir, 'compiler', 'contract-info.json'), JSON.stringify({ 'compiler-version': '0.35.0', 'language-version': '0.27.0', 'runtime-version': scripts.compactRuntimeVersion, circuits: [], witnesses: [] })); + writeFileSync(join(managedDir, 'contract', 'index.js'), 'export function ledger() { return {}; }\\n'); + const before = readdirSync(dapp).sort(); + const said = []; + const networkConfig = { ...getNetworkConfig(network), indexer: 'http://127.0.0.1:9/api/v4/graphql', indexerWS: 'ws://127.0.0.1:9/api/v4/graphql/ws', node: 'ws://127.0.0.1:9', proofServer: 'http://127.0.0.1:9' }; + let failed; + try { + await runState({ dappDir: dapp, network, root: join(home, '.midnight'), engines: host.engines, networkConfig, managedDir, contractName: 'counter', contractAddress: 'ab'.repeat(32), onMessage: (message) => said.push(message) }); + } catch (error) { + failed = { name: error.name, code: error.code, message: error.message }; + } + console.log(JSON.stringify({ packages: scripts.packages.length, missing, said, failed, leftAsItWas: JSON.stringify(readdirSync(dapp).sort()) === JSON.stringify(before) })); + `, dapp, network, home], installed)); + check(`the ${set} engine finds the ${ran.packages} packages its contract scripts import`, ran.missing.length === 0, ran.missing.length > 0 ? `not found: ${ran.missing.join(', ')}` : ''); + const reached = ran.said.includes('Querying contract state...') && ran.failed?.name === 'ContractScriptError' && ran.failed?.code === 'NETWORK_ERROR'; + check(`a ${network} contract state read runs its script in a dApp, as far as the indexer`, reached, ran.failed === undefined ? 'it did not fail' : `${ran.failed.name} ${ran.failed.code ?? '(no code)'}: ${ran.failed.message.split('\n').pop()}`); + check(`the ${network} run leaves the dApp's folder as it was`, ran.leftAsItWas); + } + // mn grant drives the account package it installed: its owner records load // from the installed tree and answer that the new wallet has no account. // Asking that reaches no chain and opens no proving-artefact cache (the @@ -271,6 +319,9 @@ try { ['@kuiralabs/midnight-engine-rc', 'derive-address'], ['@kuiralabs/midnight-engine-beta', 'derive-address'], ['@kuiralabs/midnight-wallet', 'lib/passphrase'], + ['@kuiralabs/midnight-contract', 'lib/contract/runner'], + ['@kuiralabs/midnight-connect', 'lib/ws-rpc'], + ['@kuiralabs/midnight-dev', 'lib/localnet'], ]) { check(`a program outside mn finds ${name}'s ${deepPath} built`, existsSync(join(outside, 'node_modules', name, 'dist', `${deepPath}.js`))); const deep = run(process.execPath, ['entry.mjs', `${name}/${deepPath}`], outside).trim(); diff --git a/src/__tests__/chain-reset-clearing.test.ts b/src/__tests__/chain-reset-clearing.test.ts index 150ad55d..72332dea 100644 --- a/src/__tests__/chain-reset-clearing.test.ts +++ b/src/__tests__/chain-reset-clearing.test.ts @@ -8,7 +8,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { clearChainCaches } from '@kuiralabs/midnight-wallet'; import { getCachePath, getDustCachePath, getShieldedCachePath } from '@kuiralabs/midnight-cli-core/engine'; -import { PRIVATE_STATE_DATABASE, clearDappPrivateState } from '../lib/contract/private-state.ts'; +import { PRIVATE_STATE_DATABASE, clearDappPrivateState } from '@kuiralabs/midnight-contract'; let dir: string; diff --git a/src/__tests__/command-cancellation.test.ts b/src/__tests__/command-cancellation.test.ts index 21e7bf2b..b89fc1e9 100644 --- a/src/__tests__/command-cancellation.test.ts +++ b/src/__tests__/command-cancellation.test.ts @@ -19,10 +19,10 @@ import { getCachePath } from '@kuiralabs/midnight-cli-core/engine'; import { installedCommands } from '../lib/installed-commands.ts'; import { establishPassphrase, isPassphraseSet, loadWalletConfig, protectAllWallets, createWallet, walletSecretFrom, type WalletProtector } from '@kuiralabs/midnight-wallet'; import { rcKeys } from '../../test-support/rc-engine.ts'; -import inspectCostCommand from '../commands/inspect-cost.ts'; +import { inspectCostDefinition } from '@kuiralabs/midnight-contract/commands'; import { statusDefinition } from '@kuiralabs/midnight-chain/commands'; import { balanceDefinition, generateDefinition, walletDefinition, cacheDefinition } from '@kuiralabs/midnight-wallet/commands'; -import testCommand from '../commands/test.ts'; +import { testDefinition } from '@kuiralabs/midnight-dev/commands'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; @@ -32,6 +32,8 @@ import { stateRootIn } from '../../test-support/state-root-in.ts'; import { startRefusingEndpoint, startStandInIndexer, type StandInIndexer } from '../../test-support/stand-in-indexer.ts'; // The handlers, as the shell loads them. +const { default: inspectCostCommand } = await inspectCostDefinition.load(); +const { default: testCommand } = await testDefinition.load(); const { default: balanceCommand } = await balanceDefinition.load(); const { default: generateCommand } = await generateDefinition.load(); const { default: walletCommand } = await walletDefinition.load(); diff --git a/src/__tests__/contract-deploy.test.ts b/src/__tests__/contract-deploy.test.ts index 5deca6a4..aca9b44d 100644 --- a/src/__tests__/contract-deploy.test.ts +++ b/src/__tests__/contract-deploy.test.ts @@ -6,9 +6,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { contractDeployRequest } from '../lib/contract/request.ts'; -import { deployContract } from '../lib/contract/deploy.ts'; -import { servePayerAt } from '../lib/serve-payer.ts'; +import { contractDeployRequest, deployContract } from '@kuiralabs/midnight-contract'; +import { servePayerAt } from '@kuiralabs/midnight-connect'; import { createSdkWarningRouter, CancelledError, createHost, type Host } from '@kuiralabs/midnight-cli-core'; import { stateRootIn } from '../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; diff --git a/src/__tests__/declared-codes.test.ts b/src/__tests__/declared-codes.test.ts index fe100d29..acc5eb3a 100644 --- a/src/__tests__/declared-codes.test.ts +++ b/src/__tests__/declared-codes.test.ts @@ -21,8 +21,8 @@ import { importTarget, importedModules, importsOf } from '../../scripts/check-la import { declaredCodes, type CommandDefinition, CancelledError, CommandFailedError, DustRequiredError, TransactionRefusedError, withTransportCode } from '@kuiralabs/midnight-cli-core'; import { EVERY_COMMAND, READS_OFFERS } from '@kuiralabs/midnight-cli-core/commands'; import { refusalCodeOf, toEngineError } from '@kuiralabs/midnight-cli-core/engine'; -import { ContractScriptError, SCRIPT_ERROR_MARKER, scriptFailureOf } from '../lib/contract/runner.ts'; -import { PrepStepFailedError } from '../lib/test/prep-runner.ts'; +import { ContractScriptError } from '@kuiralabs/midnight-contract'; +import { PrepStepFailedError } from '@kuiralabs/midnight-dev'; import { installedCommands } from '../lib/installed-commands.ts'; import { WalletNotFoundError } from '@kuiralabs/midnight-wallet'; import { expectDeclared, expectDeclaredToolResult } from './helpers/expect-declared.ts'; @@ -120,7 +120,8 @@ describe("the scan's tables", () => { expect(DYNAMIC_CLASSES.EngineError!.codes).toStrictEqual(sdkErrors.codes); // A script reports the code its failure carried: mn serve's (withEngineCode marks it with the same codes), or NETWORK_ERROR. expect(DYNAMIC_CLASSES.ContractScriptError!.codes).toStrictEqual(sdkErrors.codes); - expect(new ContractScriptError(scriptFailureOf(`${SCRIPT_ERROR_MARKER} {"message":"refused","code":"PROOF_FAILURE"}\n`, 1)).code).toBe('PROOF_FAILURE'); + // The code a script's marked line carries becomes the error's (the contract package's contract-script-errors.test.ts reads one). + expect(new ContractScriptError({ message: 'refused', code: 'PROOF_FAILURE' }).code).toBe('PROOF_FAILURE'); }); it("give a node's refusal its three codes, a transport failure NETWORK_ERROR, and a prep step its cause's code", () => { diff --git a/src/__tests__/entry-points.test.ts b/src/__tests__/entry-points.test.ts index 2ad75384..c4bedfc7 100644 --- a/src/__tests__/entry-points.test.ts +++ b/src/__tests__/entry-points.test.ts @@ -17,6 +17,9 @@ const ENTRY_POINTS: Record = { 'engine-rc': ['.'], 'engine-beta': ['.'], wallet: ['.', './commands'], + contract: ['.', './commands'], + connect: ['.', './commands'], + dev: ['.', './commands'], }; describe('the public entry points', () => { diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index 9a45db0f..bcea5e03 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -16,19 +16,15 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { classifyError, CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, SyncTimeoutError, TransactionRefusedError, UsageError, createApiError, OPERATOR_REJECTED_MESSAGE, withTransportCode, parseArgs, requireFlag, dustShortError, ProgramTimedOutError, NATIVE_TOKEN_TYPE, type NetworkConfig, type CommandHandler, createHost, payerFor, openSecret, sealSecret, checkTerms, assertOfferUnexpired, OfferCoinsInUseError, AmbiguousLocalStacksError, BlockfrostLimitError, BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, OtherSdkSetError, createSdkWarningRouter } from '@kuiralabs/midnight-cli-core'; +import { classifyError, CancelledError, CommandFailedError, DustRequiredError, InsufficientBalanceError, SyncTimeoutError, TransactionRefusedError, UsageError, withTransportCode, parseArgs, requireFlag, dustShortError, ProgramTimedOutError, NATIVE_TOKEN_TYPE, type NetworkConfig, type CommandHandler, createHost, payerFor, openSecret, sealSecret, checkTerms, assertOfferUnexpired, OfferCoinsInUseError, AmbiguousLocalStacksError, BlockfrostLimitError, BlockfrostProjectIdRejectedError, BlockfrostProjectIdRequiredError, EndpointShutDownError, OtherSdkSetError } from '@kuiralabs/midnight-cli-core'; import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; -import { ProofTimeoutError, withEngineCode, NotAnOfferError, MixedSdkLayoutError, DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/engine'; +import { ProofTimeoutError, NotAnOfferError, MixedSdkLayoutError, DustFeeNotGeneratedError, planRegistration } from '@kuiralabs/midnight-cli-core/engine'; import { Effect } from 'effect'; import { SubmissionError } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { ProvingError } from '@midnightntwrk/wallet-sdk/capabilities/proving'; import { InsufficientFundsError as NoCoinsCoverIt } from '@midnightntwrk/wallet-sdk/capabilities'; import { WalletError } from '@midnightntwrk/wallet-sdk/dust/v2'; -import { scriptFailureAtServe } from './helpers/serve-script-failure.ts'; import { closedPort } from '../../test-support/closed-port.ts'; -import { SCRIPT_PRELUDE, executeScript, rpcClientCode } from '../lib/contract/runner.ts'; -import { createRequire } from 'node:module'; -import { pathToFileURL } from 'node:url'; import { WebSocket } from 'ws'; import { LocalStackUnreachableError, UnsupportedLedgerError, ChainClockBehindError, waitForFirstBlock, waitForAddressFunded, waitForProofServerReady, callNodeRpc, subscribeGraphqlWs, checkBalance, queryIndexer } from '@kuiralabs/midnight-chain'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; @@ -36,14 +32,11 @@ import { rcKeys } from '../../test-support/rc-engine.ts'; import * as ledger from '@midnightntwrk/ledger-v9'; import { readPassphrase, assertWalletFileExists, assertWalletRemovable, setActiveWallet, walletSecretFrom, assertWalletCanPay, NoSuchOfferError } from '@kuiralabs/midnight-wallet'; import { walletDefinition, generateDefinition, addressDefinition, airdropDefinition, balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; -import { PrepStepFailedError, runPrepSteps } from '../lib/test/prep-runner.ts'; -import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; +import { LocalnetUnavailableError, PrepStepFailedError } from '@kuiralabs/midnight-dev'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { cliCall } from './helpers/cli-call.ts'; import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; import { UnsupportedNodeError } from '../lib/node-version.ts'; -import { LocalnetUnavailableError } from '../lib/localnet.ts'; -import { scriptRuntime } from '../lib/contract/runner.ts'; import { NoAccountError } from '../lib/grant/prepare.ts'; import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; import { installedCommands } from '../lib/installed-commands.ts'; @@ -102,30 +95,12 @@ const nodeRefusal = (reason: string) => () => sdkRejection(new SubmissionError({ const throughRcEngine = (failure: () => Promise) => () => createRcEngine(createHost({ paths: { stateRoot: root, home: root } }), { repository: { fetchUnshielded: failure, fetchTip: async () => 'tip-1' }, }).wallet.unshieldedBalance(ADDRESSES.undeployed, STAND_IN, { forceFresh: true }); -/** The connector's answer to a submission the node refused with `reason`: its own words over the SDK's error, marked with mn's code. */ -const connectorRefusal = async (reason: string) => { - const thrown = await nodeRefusal(reason)().catch((e: Error) => e); - return withEngineCode(new Error(`Transaction submission failed: [SubmissionError] Transaction submission error → ${reason}`, { cause: thrown })); -}; /** A socket's refusal: what a WebSocket to a closed port fails with (ECONNREFUSED its code). */ async function refusedSocket(): Promise { const port = await closedPort(); return new Promise((resolve) => { new WebSocket(`ws://127.0.0.1:${port}`).on('error', resolve); }); } -/** What the runner rejects with when a generated script, its prelude first, runs `body` and fails. */ -async function scriptFailing(body: (port: number) => string): Promise { - const dir = mkdtempSync(join(tmpdir(), 'mn-code-parity-script-')); - try { - const wsModule = pathToFileURL(createRequire(import.meta.url).resolve('ws')).href; - const port = await closedPort(); - await executeScript({ dir, script: SCRIPT_PRELUDE + rpcClientCode(port, wsModule) + body(port), overlaySdk: false, packages: { packages: [], packageFolder: () => null, set: 'rc' } }); - throw new Error('expected the script to fail'); - } finally { - rmSync(dir, { recursive: true, force: true }); - } -} - /** What the function throws; fails the test when it throws nothing. */ async function thrownBy(run: () => unknown): Promise { try { @@ -194,11 +169,9 @@ const ROWS: Row[] = [ ['an indexer subscription refused', () => subscribeGraphqlWs(CLOSED_WS, { query: 'subscription { x }', variables: {}, timeoutMs: 5_000, idleMs: 1_000, onNext: () => true, buildResult: () => undefined }), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], ['a balance read refused', () => checkBalance(ADDRESSES.undeployed, CLOSED_WS), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], ['an indexer query refused (approved: was UNKNOWN)', () => queryIndexer(`${CLOSED_HTTP}/`, '{ x }', undefined, 5_000), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], - // Connections the SDK, a contract script or the account package could not make, named where they are met. + // Connections the SDK or the account package could not make, named where they are met. ["a socket's refusal, through the engine", throughRcEngine(async () => { throw await refusedSocket(); }), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], ['fetch failing, through the engine (approved Y53: was UNKNOWN)', throughRcEngine(async () => { await fetch(`http://127.0.0.1:${await closedPort()}/`); throw new Error('expected fetch to fail'); }), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], - ['a contract script that cannot reach mn serve', () => scriptFailing(() => 'await rpcConnect();\n'), as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], - ["a contract script's fetch failing (approved Y53: was UNKNOWN)", () => scriptFailing((port) => `await fetch('http://127.0.0.1:${port}/');\n`), as('UNKNOWN', 1), as('NETWORK_ERROR', 4)], ["the account package's refused connection, at grant's boundary", async () => { throw withTransportCode(await refusedSocket()); }, as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], // Approved: a program that ran past its limit keeps NETWORK_ERROR, which its message (ETIMEDOUT) gave it. ['a program past its time limit', () => { throw new ProgramTimedOutError('docker compose ps', 10_000); }, as('NETWORK_ERROR', 4), as('NETWORK_ERROR', 4)], @@ -211,7 +184,6 @@ const ROWS: Row[] = [ // A test run's Dust step, and an engine's shielded transfer, need a chain: their errors as those sites throw them. ['the SDK short of Dust, through the engine', throughRcEngine(() => sdkRejection(new WalletError.InsufficientFundsError({ message: new NoCoinsCoverIt('dust').message, tokenType: 'dust' }))), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], ['the SDK short of NIGHT, through the engine', throughRcEngine(() => sdkRejection(new WalletError.InsufficientFundsError({ message: new NoCoinsCoverIt(NATIVE_TOKEN_TYPE).message, tokenType: NATIVE_TOKEN_TYPE }))), as('INSUFFICIENT_BALANCE', 5), as('INSUFFICIENT_BALANCE', 5)], - ['a contract run short of Dust at mn serve', () => scriptFailureAtServe(() => createApiError('InternalError', "Not enough Dust available for this transaction's fee: the wallet has 0.35 DUST and the fee takes 2.00.", 'DUST_REQUIRED')).then((err) => { throw err; }), as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], ["a test run's Dust not available", () => { throw new DustRequiredError('Dust not available after 90s. The chain may be slow — try again.'); }, as('DUST_REQUIRED', 5), as('DUST_REQUIRED', 5)], ["a test run's wallet with no NIGHT (approved: was UNKNOWN)", () => { throw new InsufficientBalanceError('Wallet has 0 NIGHT on preprod. Fund your wallet before running tests:\n mn airdrop 100 (if faucet available)\n Or transfer NIGHT from another wallet.'); }, as('UNKNOWN', 1), as('INSUFFICIENT_BALANCE', 5)], // A failed prep step reports its step's code. @@ -230,11 +202,7 @@ const ROWS: Row[] = [ ['a wallet sync past its deadline, in the engine', () => { throw new SyncTimeoutError('Wallet sync timed out'); }, as('SYNC_TIMEOUT', 4), as('SYNC_TIMEOUT', 4)], ['a ZK proof that timed out, in the engine (approved Y54: was UNKNOWN)', () => { throw new ProofTimeoutError(); }, as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], // A program's wallet session (the connector in this process) and an escaped stale cache are the engines' own errors: their rows are in each engine's tests (wallet-session.test.ts, stale-cache.test.ts). - // A contract run: the connector at mn serve, the wire, and the script's process. - ['a contract run the node refused at mn serve (approved Y54: was UNKNOWN)', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 199'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('UNKNOWN', 1), as('TX_REJECTED', 6)], - ['a contract run refused a spent coin at mn serve', async () => { const refusal = await connectorRefusal('1010: Invalid Transaction: Custom error: 115'); return scriptFailureAtServe(() => refusal).then((err) => { throw err; }); }, as('STALE_UTXO', 6), as('STALE_UTXO', 6)], - ['a contract run whose proof timed out at mn serve (approved Y54: was UNKNOWN)', () => scriptFailureAtServe(() => new ProofTimeoutError()).then((err) => { throw err; }), as('UNKNOWN', 1), as('PROOF_TIMEOUT', 6)], - ['a contract run the operator refused at mn serve', () => scriptFailureAtServe(() => createApiError('Rejected', OPERATOR_REJECTED_MESSAGE, 'TX_REJECTED')).then((err) => { throw err; }), as('TX_REJECTED', 6), as('TX_REJECTED', 6)], + // A contract script's failures (a connection it could not make, no Node.js to run it) and a contract run's at mn serve (the connector, the wire, the script's process) are the contract runner's: their rows are in the contract package's tests (contract-script-errors.test.ts). // Cancelled: exit 7. ['a cancelled call', () => { throw new CancelledError(); }, as('CANCELLED', 7), as('CANCELLED', 7)], @@ -247,11 +215,10 @@ const ROWS: Row[] = [ ['no account', () => { throw new NoAccountError('alice', 'undeployed'); }, as('NO_ACCOUNT', 1), as('NO_ACCOUNT', 1)], ['no state root (approved: was UNKNOWN)', () => createHost().paths(), as('UNKNOWN', 1), as('NO_STATE_ROOT', 1)], ['no payer (approved: was UNKNOWN)', () => payerFor('transfer', undefined), as('UNKNOWN', 1), as('NO_PAYER', 1)], - ['no Node.js for a contract script (approved: was UNKNOWN)', () => scriptRuntime({ execPath: '/opt/bun/bin/bun', isNode: false }, ''), as('UNKNOWN', 1), as('NO_NODE_RUNTIME', 1)], // Without the registry its code came from its result's text: here, words that read as a network error. ['a failed command (approved: was by its text)', () => { throw new CommandFailedError('test run', 1, { overall: 'fail', error: 'network error' }); }, as('NETWORK_ERROR', 4), as('COMMAND_FAILED', 1)], ['an error no rule knows', () => { throw new Error('Something unexpected happened'); }, as('UNKNOWN', 1), as('UNKNOWN', 1)], - ['a prep step that failed with no code', () => runPrepSteps({ network: 'undeployed', prep: ['no-such-step'] } as unknown as DappTestConfig, root, createPrepContext(root, hostOnRoot(), createSdkWarningRouter().openCall().warnings, new AbortController().signal), { onStepStart: () => {}, onStepComplete: () => {}, onMessage: () => {} }), as('UNKNOWN', 1), as('UNKNOWN', 1)], + // A prep step that failed with no code is the test runner's: its row is in the dev package's tests (prep-runner-cancellation.test.ts). ]; describe('the code and exit code of each typed error', () => { diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 750efb5e..84060b65 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -55,7 +55,7 @@ describe('classifyError: typed setup errors keep their own code', () => { it.each([ ['UNSUPPORTED_LEDGER', async () => new (await import('@kuiralabs/midnight-chain')).UnsupportedLedgerError('preview', 1000300n)], ['LOCAL_STACK_UNREACHABLE', async () => new (await import('@kuiralabs/midnight-chain')).LocalStackUnreachableError('indexer', 'http://localhost:8088/api/v4/graphql')], - ['LOCALNET_UNAVAILABLE', async () => new (await import('../lib/localnet.ts')).LocalnetUnavailableError()], + ['LOCALNET_UNAVAILABLE', async () => new (await import('@kuiralabs/midnight-dev')).LocalnetUnavailableError()], ['AMBIGUOUS_LOCAL_STACKS', async () => new (await import('@kuiralabs/midnight-cli-core')).AmbiguousLocalStacksError({ node: [9944, 29944], indexer: [8088, 28088], proofServer: [6300] })], ])('%s', async (code, make) => { const result = classifyError(await make(), installedCommands); diff --git a/src/__tests__/handler-library-calls.test.ts b/src/__tests__/handler-library-calls.test.ts index f33cf040..71134b12 100644 --- a/src/__tests__/handler-library-calls.test.ts +++ b/src/__tests__/handler-library-calls.test.ts @@ -19,7 +19,7 @@ const HANDLERS: Record = { 'packages/wallet/src/commands/transfer.ts': ['transferNight'], 'packages/wallet/src/commands/airdrop.ts': ['airdropNight'], 'packages/wallet/src/commands/dust.ts': ['readDustStatus', 'registerDust', 'exportDustSnapshot'], - 'src/commands/contract.ts': ['deployContract', 'callContract', 'readContractState'], + 'packages/contract/src/commands/contract.ts': ['deployContract', 'callContract', 'readContractState'], 'packages/wallet/src/commands/swap.ts': ['makeSwapOffer', 'inspectSwapOffer', 'takeSwapOffer', 'cancelSwapOffer', 'listSwapOffers'], 'packages/chain/src/commands/tx.ts': ['transactionStatus'], }; diff --git a/src/__tests__/host-slots.test.ts b/src/__tests__/host-slots.test.ts index 10c2e527..46e56836 100644 --- a/src/__tests__/host-slots.test.ts +++ b/src/__tests__/host-slots.test.ts @@ -13,7 +13,7 @@ import { createHost, type Host, type Prompter, PASSPHRASE_ENV } from '@kuiralabs import { promptApproval } from '@kuiralabs/midnight-cli-core/engine'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { NoPassphraseError, establishPassphrase, unlockPassphrase, unlockWallet } from '@kuiralabs/midnight-wallet'; -import { createRpcServer, type RpcServer } from '../lib/ws-rpc.ts'; +import { createRpcServer, type RpcServer } from '@kuiralabs/midnight-connect'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; import { stateRootIn } from '../../test-support/state-root-in.ts'; diff --git a/src/__tests__/inspect-cost-command.test.ts b/src/__tests__/inspect-cost-command.test.ts index f492cf44..78e86085 100644 --- a/src/__tests__/inspect-cost-command.test.ts +++ b/src/__tests__/inspect-cost-command.test.ts @@ -4,13 +4,16 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as ledger from '@midnightntwrk/ledger-v9'; -import inspectCostCommand from '../commands/inspect-cost.ts'; +import { inspectCostDefinition } from '@kuiralabs/midnight-contract/commands'; import { parseArgs } from '@kuiralabs/midnight-cli-core'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { startLocalIndexer, type LocalIndexer } from '../../test-support/local-indexer.ts'; import { LEDGER9_PARAMETERS_HEX } from '../../test-support/fixtures/ledger9-parameters.ts'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: inspectCostCommand } = await inspectCostDefinition.load(); + let io: CapturedOutput; let indexer: LocalIndexer | undefined; diff --git a/src/__tests__/json-output.test.ts b/src/__tests__/json-output.test.ts index a363a49e..7fe6f861 100644 --- a/src/__tests__/json-output.test.ts +++ b/src/__tests__/json-output.test.ts @@ -8,7 +8,7 @@ import * as path from 'path'; import * as os from 'os'; // Commands that can be tested without network/Docker -import inspectCostCommand from '../commands/inspect-cost.ts'; +import { inspectCostDefinition } from '@kuiralabs/midnight-contract/commands'; import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { generateDefinition, infoDefinition, addressDefinition, genesisAddressDefinition } from '@kuiralabs/midnight-wallet/commands'; import helpCommand from '../commands/help.ts'; @@ -19,6 +19,7 @@ import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from '../../test-support/state-root-in.ts'; // The handlers, as the shell loads them. +const { default: inspectCostCommand } = await inspectCostDefinition.load(); const { default: generateCommand } = await generateDefinition.load(); const { default: infoCommand } = await infoDefinition.load(); const { default: addressCommand } = await addressDefinition.load(); diff --git a/src/__tests__/localnet-command.test.ts b/src/__tests__/localnet-command.test.ts index 47599bfb..8d0dec98 100644 --- a/src/__tests__/localnet-command.test.ts +++ b/src/__tests__/localnet-command.test.ts @@ -1,23 +1,18 @@ +// The localnet command as the shell runs it: its arguments, its help and +// intro, and up refused on this ledger-9 build. The localnet library's own +// tests are the dev package's (packages/dev/src/__tests__/localnet.test.ts). + import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; -import { join } from 'path'; -import { tmpdir } from 'os'; -import localnetCommand from '../commands/localnet.ts'; import { parseArgs, commandHelpSpecs, introBriefs } from '@kuiralabs/midnight-cli-core'; +import { localnetDefinition } from '@kuiralabs/midnight-dev/commands'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; -import { existsSync, statSync } from 'fs'; -import { - COMPOSE_YAML, - COMPOSE_VERSION, - ensureComposeFile, - getComposePath, - LocalnetUnavailableError, - parseServiceStatus, -} from '../lib/localnet.ts'; import helpCommand from '../commands/help.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: localnetCommand } = await localnetDefinition.load(); + let io: CapturedOutput; beforeEach(() => { @@ -63,140 +58,6 @@ describe('localnet command — argument validation', () => { }); }); -describe('COMPOSE_YAML content', () => { - it('contains the node service with correct image', () => { - expect(COMPOSE_YAML).toContain('midnight-node:'); - }); - - it('contains the indexer service with correct image', () => { - expect(COMPOSE_YAML).toContain('indexer-standalone:'); - }); - - it('contains the proof-server service with correct image', () => { - expect(COMPOSE_YAML).toContain('proof-server:'); - }); - - it('exposes node port 9944', () => { - expect(COMPOSE_YAML).toContain('"9944:9944"'); - }); - - it('exposes indexer port 8088', () => { - expect(COMPOSE_YAML).toContain("'8088:8088'"); - }); - - it('exposes proof-server port 6300', () => { - expect(COMPOSE_YAML).toContain('"6300:6300"'); - }); - - it('includes healthcheck for node', () => { - expect(COMPOSE_YAML).toContain('http://localhost:9944/health'); - }); - - it('includes healthcheck for indexer', () => { - expect(COMPOSE_YAML).toContain('cat /var/run/indexer-standalone/running'); - }); - - it('has indexer depending on node', () => { - expect(COMPOSE_YAML).toContain('depends_on'); - expect(COMPOSE_YAML).toContain('condition: service_started'); - }); - - it('sets CFG_PRESET=dev for the node', () => { - expect(COMPOSE_YAML).toContain('CFG_PRESET: "dev"'); - }); - - it('starts with services: key (valid compose format)', () => { - expect(COMPOSE_YAML.trimStart()).toMatch(/^services:/); - }); - - // Regression: node + proof-server used to have no restart policy while only the - // indexer did. A Docker Desktop restart or any transient stop then left a - // half-dead localnet (indexer up, node gone) — surfacing as ws "Normal Closure" - // churn and a wedged dust sync. Every service must self-heal. - it('gives every service a restart policy so the localnet self-heals', () => { - const serviceBlock = (svc: string): string => { - const start = COMPOSE_YAML.indexOf(`\n ${svc}:`); - if (start < 0) return ''; - const rest = COMPOSE_YAML.slice(start + 1); - const next = rest.search(/\n {2}\S/); // next top-level (2-space) service key - return next < 0 ? rest : rest.slice(0, next + 1); - }; - for (const svc of ['proof-server', 'indexer', 'node']) { - const block = serviceBlock(svc); - expect(block, `service ${svc} present in compose`).not.toBe(''); - expect(block, `service ${svc} has a restart policy`).toMatch(/^\s+restart:/m); - } - }); -}); - -describe('COMPOSE_VERSION', () => { - it('is a semver-like string', () => { - expect(COMPOSE_VERSION).toMatch(/^\d+\.\d+\.\d+$/); - }); -}); - -describe('ledger-9 build: mn localnet cannot start a network', () => { - // The compose stack is ledger 8, which wallet-sdk 2.0 can't sync with, and - // no published indexer image runs ledger 9 yet. Every start path goes - // through ensureComposeFile, so it refuses there, before writing anything. - // A state root of the test's own, which nothing creates. - const root = join(tmpdir(), `midnight-localnet-ledger9-${process.pid}`); - const composeFingerprint = () => { - const path = getComposePath(root); - return existsSync(path) ? `${statSync(path).mtimeMs}:${readFileSync(path, 'utf-8').length}` : 'absent'; - }; - - it('ensureComposeFile refuses, says what to run instead, and writes nothing', () => { - const before = composeFingerprint(); - let err: unknown; - try { ensureComposeFile(root); } catch (e) { err = e; } - expect(err).toBeInstanceOf(LocalnetUnavailableError); - const msg = (err as Error).message; - expect(msg).toContain('ledger 9'); - expect(msg).toContain('--node'); - expect(msg).toContain('--indexer-ws'); - expect(msg).toContain('--proof-server'); - expect(msg).toContain('midnight config set'); - expect(composeFingerprint()).toBe(before); - }); -}); - -describe('ensureComposeFile', () => { - // Use a temp directory to test file writing logic without touching real ~/.midnight - const TEST_DIR = join(tmpdir(), `midnight-localnet-test-${process.pid}`); - const TEST_COMPOSE_PATH = join(TEST_DIR, 'compose.yml'); - const TEST_VERSION_PATH = join(TEST_DIR, '.version'); - - beforeEach(() => { - rmSync(TEST_DIR, { recursive: true, force: true }); - }); - - afterEach(() => { - rmSync(TEST_DIR, { recursive: true, force: true }); - }); - - it('compose YAML can be written and read back', () => { - mkdirSync(TEST_DIR, { recursive: true }); - writeFileSync(TEST_COMPOSE_PATH, COMPOSE_YAML, 'utf-8'); - writeFileSync(TEST_VERSION_PATH, COMPOSE_VERSION, 'utf-8'); - - const content = readFileSync(TEST_COMPOSE_PATH, 'utf-8'); - expect(content).toBe(COMPOSE_YAML); - - const version = readFileSync(TEST_VERSION_PATH, 'utf-8'); - expect(version).toBe(COMPOSE_VERSION); - }); - - it('version file can detect stale compose file', () => { - mkdirSync(TEST_DIR, { recursive: true }); - writeFileSync(TEST_COMPOSE_PATH, COMPOSE_YAML, 'utf-8'); - writeFileSync(TEST_VERSION_PATH, '0.0.1', 'utf-8'); - - const version = readFileSync(TEST_VERSION_PATH, 'utf-8').trim(); - expect(version).not.toBe(COMPOSE_VERSION); - }); -}); - describe('help integration', () => { it('help lists localnet', () => { const localnetSpec = commandHelpSpecs(installedCommands).find(s => s.name === 'localnet'); @@ -241,37 +102,3 @@ describe('localnet up on this ledger-9 build', () => { } }); }); - -describe('localnet clean: which containers are mn\'s', () => { - it('removes only containers from mn\'s compose project, keeping any other with the same generic name', async () => { - const { partitionLocalnetContainers, LOCALNET_PROJECT } = await import('../lib/localnet.ts'); - expect(LOCALNET_PROJECT).toBe('localnet'); - expect(partitionLocalnetContainers([ - { name: 'node', project: 'localnet' }, // mn's (also an older mn's ledger-8 localnet) - { name: 'indexer', project: 'my-app' }, // someone else's compose service - { name: 'proof-server', project: '' }, // a plain docker run - ])).toEqual({ - remove: ['node'], - keep: [{ name: 'indexer', project: 'my-app' }, { name: 'proof-server', project: '' }], - }); - }); -}); - -describe('parseServiceStatus', () => { - it('reads one service per line, stopped ones included', () => { - const output = [ - JSON.stringify({ Service: 'node', State: 'running', Health: 'healthy', Image: 'midnightntwrk/midnight-node:1.0.0' }), - JSON.stringify({ Service: 'indexer', State: 'exited', Health: '', Image: 'midnightntwrk/indexer-standalone:4.3.3' }), - '', - ].join('\n'); - expect(parseServiceStatus(output)).toEqual([ - { name: 'node', state: 'running', health: 'healthy', port: '9944', image: 'midnightntwrk/midnight-node:1.0.0' }, - { name: 'indexer', state: 'exited', health: '', port: '8088', image: 'midnightntwrk/indexer-standalone:4.3.3' }, - ]); - }); - - it('skips a line that is not JSON and is empty for no output', () => { - expect(parseServiceStatus('time="..." level=warning msg="something"\n')).toEqual([]); - expect(parseServiceStatus('')).toEqual([]); - }); -}); diff --git a/src/__tests__/network-cancellation.test.ts b/src/__tests__/network-cancellation.test.ts index 5c2cda79..57b52afc 100644 --- a/src/__tests__/network-cancellation.test.ts +++ b/src/__tests__/network-cancellation.test.ts @@ -14,7 +14,7 @@ import * as path from 'node:path'; import { parseArgs, type CommandHandler } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; import { establishPassphrase, createWallet, walletSecretFrom } from '@kuiralabs/midnight-wallet'; -import { servePayerAt } from '../lib/serve-payer.ts'; +import { servePayerAt } from '@kuiralabs/midnight-connect'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { cliCall } from './helpers/cli-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; diff --git a/src/__tests__/package-metadata.test.ts b/src/__tests__/package-metadata.test.ts index 231db02c..2ed72ba3 100644 --- a/src/__tests__/package-metadata.test.ts +++ b/src/__tests__/package-metadata.test.ts @@ -56,7 +56,7 @@ describe('the SDK in the manifests', () => { } }); - it('is no dependency of core, chain or wallet', () => { - for (const dir of ['cli-core', 'chain', 'wallet']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); + it('is no dependency of core, chain, wallet, contract, connect or dev', () => { + for (const dir of ['cli-core', 'chain', 'wallet', 'contract', 'connect', 'dev']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); }); }); diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index 344d306e..f9a2117b 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -10,14 +10,16 @@ import * as path from 'node:path'; import { parseArgs, saveCliConfig, NoPayerError, resolvePayingTarget, networkTargetOf, type NetworkName, createSdkWarningRouter, CancelledError, createHost } from '@kuiralabs/midnight-cli-core'; import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; import { NoAccountError } from '../lib/grant/prepare.ts'; -import { servePayerAt } from '../lib/serve-payer.ts'; -import { probeServeNetwork } from '../lib/serve-manager.ts'; +import { probeServeNetwork, servePayerAt } from '@kuiralabs/midnight-connect'; import { assertWalletCanPay } from '@kuiralabs/midnight-wallet'; -import contractCommand from '../commands/contract.ts'; +import { contractDefinition } from '@kuiralabs/midnight-contract/commands'; import grantCommand from '../commands/grant.ts'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from '../../test-support/state-root-in.ts'; +// The handler, as the shell loads it. +const { default: contractCommand } = await contractDefinition.load(); + // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/prep-runner-cancellation.test.ts b/src/__tests__/prep-runner-cancellation.test.ts deleted file mode 100644 index b146301e..00000000 --- a/src/__tests__/prep-runner-cancellation.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -// A cancelled `mn test run` starts no further prep step. The steps here need -// no chain: a cancel stops the run before the step would reach one. - -import { describe, expect, it } from 'vitest'; -import { runPrepSteps } from '../lib/test/prep-runner.ts'; -import { createPrepContext, type DappTestConfig } from '../lib/test/types.ts'; -import { createSdkWarningRouter, CancelledError, createHost } from '@kuiralabs/midnight-cli-core'; - -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); - -const config = { network: 'undeployed', prep: ['dust', 'mn-serve'] } as unknown as DappTestConfig; - -describe('runPrepSteps', () => { - it('starts no step once the run is cancelled', async () => { - const controller = new AbortController(); - controller.abort(); - const started: string[] = []; - await expect(runPrepSteps(config, '/nonexistent', createPrepContext('/nonexistent/.midnight', host, createSdkWarningRouter().openCall().warnings, controller.signal), { - onStepStart: (step) => started.push(step), - onStepComplete: () => {}, - onMessage: () => {}, - })).rejects.toBeInstanceOf(CancelledError); - expect(started).toEqual([]); - }); -}); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index 5e81e239..376d0b8c 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -9,13 +9,14 @@ import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; -import inspectCostCommand from '../commands/inspect-cost.ts'; +import { inspectCostDefinition } from '@kuiralabs/midnight-contract/commands'; import { saveWalletConfig, type PlainWalletConfig as WalletConfig } from '../../test-support/plain-wallet.ts'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { localIndexerFlags } from '../../test-support/local-indexer.ts'; import { ownCall } from './helpers/own-call.ts'; // The handlers, as the shell loads them. +const { default: inspectCostCommand } = await inspectCostDefinition.load(); const { default: generateCommand } = await generateDefinition.load(); const { default: infoCommand } = await infoDefinition.load(); const { default: addressCommand } = await addressDefinition.load(); diff --git a/src/__tests__/serve-command.test.ts b/src/__tests__/serve-command.test.ts index 53ef0a98..14a7cc7c 100644 --- a/src/__tests__/serve-command.test.ts +++ b/src/__tests__/serve-command.test.ts @@ -1,11 +1,14 @@ // Tests for the serve command's approval flags (argv only; nothing is loaded or synced). import { describe, it, expect } from 'vitest'; -import serveCommand from '../commands/serve.ts'; import { parseArgs, UsageError, findUnknownFlags } from '@kuiralabs/midnight-cli-core'; +import { serveDefinition } from '@kuiralabs/midnight-connect/commands'; import { installedCommands } from '../lib/installed-commands.ts'; import { cliCall } from './helpers/cli-call.ts'; +// The handler, as the shell loads it. +const { default: serveCommand } = await serveDefinition.load(); + describe('serve --approve-fees', () => { it('is a flag serve accepts', () => { expect(findUnknownFlags(parseArgs(['serve', '--approve-fees']), installedCommands)).toEqual([]); diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index dad92047..934a653a 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -16,7 +16,7 @@ import { cliCall } from './helpers/cli-call.ts'; import { passphraseForNewSecret, createWallet, walletSecretFrom } from '@kuiralabs/midnight-wallet'; import { accountRecordsDir } from '../lib/grant/account-records.ts'; import { accountArtifactsDir } from '../lib/grant/account.ts'; -import { getComposePath } from '../lib/localnet.ts'; +import { getComposePath } from '@kuiralabs/midnight-dev'; import before from './fixtures/state-layout-before-1g.json'; // The config handler, as the shell loads it. diff --git a/src/__tests__/two-hosts.test.ts b/src/__tests__/two-hosts.test.ts index d598fb21..cb8d4dad 100644 --- a/src/__tests__/two-hosts.test.ts +++ b/src/__tests__/two-hosts.test.ts @@ -94,7 +94,7 @@ async function run(host: Host, argv: string[]): Promise> signal: new AbortController().signal, output, host, - loadPayer: async () => (await import('../lib/serve-payer.ts')).servePayer, + loadPayer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, loadProtectors: async () => [(await import('../lib/grant/account-protector.ts')).accountProtector], }); if (result === undefined) throw new Error(`${argv.join(' ')} wrote no result`); diff --git a/src/lib/grant/account.ts b/src/lib/grant/account.ts index 018ac682..85285416 100644 --- a/src/lib/grant/account.ts +++ b/src/lib/grant/account.ts @@ -19,7 +19,7 @@ import { directoryDeviceKeys, directoryOwnerStore, } from '@kuiralabs/midnight-account-chain/owner'; -import { PRIVATE_STATE_DATABASE } from '../contract/private-state.ts'; +import { PRIVATE_STATE_DATABASE } from '@kuiralabs/midnight-contract'; import { type PassphraseSource, passphraseForNewSecret, unlockPassphrase, type UnlockHost } from '@kuiralabs/midnight-wallet'; import { AccountMigrationInterruptedError, diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index dbb01d08..69d8eb3b 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -9,22 +9,14 @@ import { getValidNetworkNames, createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core'; import { configDefinition, coreGuidance, coreCodes } from '@kuiralabs/midnight-cli-core/commands'; import { walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition, swapDefinition, walletGuidance, swapGuidance, walletCodes } from '@kuiralabs/midnight-wallet/commands'; -import { inspectCostDefinition } from '../commands/inspect-cost.definition.ts'; -import { serveDefinition } from '../commands/serve.definition.ts'; -import { testDefinition } from '../commands/test.definition.ts'; -import { devDefinition } from '../commands/dev.definition.ts'; -import { contractDefinition } from '../commands/contract.definition.ts'; +import { inspectCostDefinition, contractDefinition, contractGuidance, contractCodes } from '@kuiralabs/midnight-contract/commands'; +import { serveDefinition, connectGuidance } from '@kuiralabs/midnight-connect/commands'; +import { testDefinition, devDefinition, localnetDefinition, devGuidance, devCodes } from '@kuiralabs/midnight-dev/commands'; import { grantDefinition } from '../commands/grant.definition.ts'; -import { localnetDefinition } from '../commands/localnet.definition.ts'; import { statusDefinition, txDefinition, chainGuidance, chainCodes } from '@kuiralabs/midnight-chain/commands'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; -import { contractGuidance } from '../commands/contract.guidance.ts'; -import { connectGuidance } from '../commands/connect.guidance.ts'; -import { devGuidance } from '../commands/dev.guidance.ts'; import { grantGuidance } from '../commands/grant.guidance.ts'; -import { contractCodes } from '../commands/contract.codes.ts'; -import { devCodes } from '../commands/dev.codes.ts'; import { grantCodes } from '../commands/grant.codes.ts'; /** The shell answers these before any command runs: no tool passes them on. */ diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 38bb27b6..5fbff504 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -15,7 +15,7 @@ import { } from '@modelcontextprotocol/sdk/types.js'; import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; import type { CommandRun } from './lib/run-command.ts'; -import { servePayer } from './lib/serve-payer.ts'; +import { servePayer } from '@kuiralabs/midnight-connect'; import { classifyError, asReported, trimAgentMessage, needsConfirmation, type Host } from '@kuiralabs/midnight-cli-core'; import { withServerAdvice } from './lib/mcp/server-advice.ts'; import { PKG_VERSION } from './lib/pkg.ts'; diff --git a/src/wallet.ts b/src/wallet.ts index e9ddc124..9cb1616c 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -92,7 +92,7 @@ async function run(): Promise { signal, output: processOutput, host, - loadPayer: async () => (await import('./lib/serve-payer.ts')).servePayer, + loadPayer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, // wallet protect also seals grant's accounts, through the protector grant provides. loadProtectors: async () => [(await import('./lib/grant/account-protector.ts')).accountProtector], }); diff --git a/tsconfig.json b/tsconfig.json index ef425a85..3ffe7beb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts", "packages/wallet/src/**/*.ts"], + "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts", "packages/wallet/src/**/*.ts", "packages/contract/src/**/*.ts", "packages/connect/src/**/*.ts", "packages/dev/src/**/*.ts"], "exclude": ["node_modules"] } From 0d81ded1530ef7b3cb93f3e7a95e4a5a83b113de Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 20:45:49 -0800 Subject: [PATCH 73/88] The grant package; every package published and checked (3F, 9-10 of 10) @kuiralabs/midnight-grant holds grant and its accounts, with "." (the account protector, its errors and record paths) and "./commands". Its error classes sit in a module with no SDK, so wallet list, which loads grant's protector entry, still loads no SDK. Dependencies as approved (Y59): grant declares @kuiralabs/midnight-account and -account-chain (moved from mn's root, same versions) and ships its own shrinkwrap, which pins the rc engine's SDK copies; the lockfile keeps every other entry. Closing: the release job publishes every package in dependency order (core, chain, the engines, wallet, connect, contract, dev, grant, then mn); the clean-install check proves every public package installs, has no source paths, and refuses a deep import; the package metadata and API report tests cover all of them. Suite 2960, beta 184; snapshot unchanged; fresh install 111 checks; live gate from a fresh runner (fresh.sh): final pass 84/84, mn dev 8/8, stagenet pass 18/18, mn serve on stagenet (a transfer, bob 116 to 123 NIGHT). --- .github/workflows/release-sidecar.yml | 11 +-- package-lock.json | 26 +++++- package.json | 8 +- packages/grant/api-report.md | 38 ++++++++ packages/grant/package.json | 46 ++++++++++ .../src}/__tests__/account-backup.test.ts | 4 +- .../grant/src}/__tests__/device-code.test.ts | 0 .../src}/__tests__/grant-account.test.ts | 4 +- .../src}/__tests__/grant-deploy-cost.test.ts | 4 +- .../__tests__/grant-owner-commands.test.ts | 0 .../src}/__tests__/grant-prepare.test.ts | 4 +- .../src}/__tests__/grant-request.test.ts | 0 .../src}/__tests__/protect-account.test.ts | 4 +- .../__tests__/sealed-account.conformance.ts | 0 .../src}/__tests__/sealed-account.test.ts | 0 packages/grant/src/commands.ts | 6 ++ .../grant/src}/commands/grant.codes.ts | 0 .../grant/src}/commands/grant.definition.ts | 0 .../grant/src}/commands/grant.guidance.ts | 0 {src => packages/grant/src}/commands/grant.ts | 0 packages/grant/src/index.ts | 13 +++ .../grant/src}/lib/grant/account-backup.ts | 0 .../grant/src/lib/grant/account-errors.ts | 44 +++++++++ .../grant/src}/lib/grant/account-protector.ts | 0 .../grant/src}/lib/grant/account-records.ts | 10 ++- .../grant/src}/lib/grant/account.ts | 37 +------- .../grant/src}/lib/grant/deploy-cost.ts | 0 .../grant/src}/lib/grant/device-code.ts | 0 .../grant/src}/lib/grant/fee-wallet.ts | 0 .../grant/src}/lib/grant/owner-commands.ts | 0 .../grant/src}/lib/grant/prepare.ts | 12 +-- .../grant/src}/lib/grant/protect-account.ts | 0 .../grant/src}/lib/grant/request.ts | 0 .../grant/src}/lib/grant/sealed-account.ts | 0 packages/grant/tsconfig.build.json | 31 +++++++ scripts/api-report.mjs | 2 +- scripts/check-layering.mjs | 1 + scripts/code-reach.mjs | 2 +- scripts/fresh-install-check.mjs | 90 ++++++++++++++++--- scripts/make-shrinkwrap.mjs | 10 ++- scripts/pack-release.d.mts | 10 +++ scripts/pack-release.mjs | 17 ++-- src/__tests__/api-report.test.ts | 14 ++- src/__tests__/command-registry.test.ts | 2 +- src/__tests__/entry-points.test.ts | 1 + src/__tests__/error-code-parity.test.ts | 3 +- src/__tests__/exit-codes.test.ts | 3 +- src/__tests__/package-metadata.test.ts | 53 ++++++++++- src/__tests__/payer.test.ts | 7 +- src/__tests__/sdk-free-base.test.ts | 7 +- src/__tests__/state-root.test.ts | 3 +- src/__tests__/two-hosts.test.ts | 2 +- src/__tests__/wallet-protect.test.ts | 2 +- src/lib/installed-commands.ts | 4 +- src/wallet.ts | 2 +- tsconfig.json | 2 +- 56 files changed, 423 insertions(+), 116 deletions(-) create mode 100644 packages/grant/api-report.md create mode 100644 packages/grant/package.json rename {src => packages/grant/src}/__tests__/account-backup.test.ts (98%) rename {src => packages/grant/src}/__tests__/device-code.test.ts (100%) rename {src => packages/grant/src}/__tests__/grant-account.test.ts (95%) rename {src => packages/grant/src}/__tests__/grant-deploy-cost.test.ts (94%) rename {src => packages/grant/src}/__tests__/grant-owner-commands.test.ts (100%) rename {src => packages/grant/src}/__tests__/grant-prepare.test.ts (97%) rename {src => packages/grant/src}/__tests__/grant-request.test.ts (100%) rename {src => packages/grant/src}/__tests__/protect-account.test.ts (97%) rename {src => packages/grant/src}/__tests__/sealed-account.conformance.ts (100%) rename {src => packages/grant/src}/__tests__/sealed-account.test.ts (100%) create mode 100644 packages/grant/src/commands.ts rename {src => packages/grant/src}/commands/grant.codes.ts (100%) rename {src => packages/grant/src}/commands/grant.definition.ts (100%) rename {src => packages/grant/src}/commands/grant.guidance.ts (100%) rename {src => packages/grant/src}/commands/grant.ts (100%) create mode 100644 packages/grant/src/index.ts rename {src => packages/grant/src}/lib/grant/account-backup.ts (100%) create mode 100644 packages/grant/src/lib/grant/account-errors.ts rename {src => packages/grant/src}/lib/grant/account-protector.ts (100%) rename {src => packages/grant/src}/lib/grant/account-records.ts (73%) rename {src => packages/grant/src}/lib/grant/account.ts (81%) rename {src => packages/grant/src}/lib/grant/deploy-cost.ts (100%) rename {src => packages/grant/src}/lib/grant/device-code.ts (100%) rename {src => packages/grant/src}/lib/grant/fee-wallet.ts (100%) rename {src => packages/grant/src}/lib/grant/owner-commands.ts (100%) rename {src => packages/grant/src}/lib/grant/prepare.ts (90%) rename {src => packages/grant/src}/lib/grant/protect-account.ts (100%) rename {src => packages/grant/src}/lib/grant/request.ts (100%) rename {src => packages/grant/src}/lib/grant/sealed-account.ts (100%) create mode 100644 packages/grant/tsconfig.build.json create mode 100644 scripts/pack-release.d.mts diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index 4e2901fa..a9b9535b 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -159,8 +159,8 @@ jobs: fi done # mn depends on its workspace packages (core, chain, one engine per SDK - # set, wallet, contract, connect, dev) at exact versions: each publishes first, unless that version is - # on npm already, under the same dist-tag as mn. + # set, wallet, connect, contract, dev, grant) at exact versions: each publishes first, unless that version is + # on npm already, under the same dist-tag as mn, in dependency order (a package after those it declares). - run: npm run build - name: Publish the workspace packages mn depends on env: @@ -168,14 +168,15 @@ jobs: shell: bash run: | set -euo pipefail - for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta packages/wallet packages/contract packages/connect packages/dev; do + for dir in packages/cli-core packages/chain packages/engine-rc packages/engine-beta packages/wallet packages/connect packages/contract packages/dev packages/grant; do name="$(node -p "require('./$dir/package.json').name")" version="$(node -p "require('./$dir/package.json').version")" if npm view "$name@$version" version >/dev/null 2>&1; then echo "$name@$version is published already" else - # An engine ships the SDK set the tests ran on, for a program that installs it without mn. - case "$name" in @kuiralabs/midnight-engine-*) node scripts/make-shrinkwrap.mjs --package "$dir" ;; esac + # An engine ships the SDK set the tests ran on, for a program that installs it without mn; so does + # grant, whose account chain is built on the rc set. + case "$name" in @kuiralabs/midnight-engine-*|@kuiralabs/midnight-grant) node scripts/make-shrinkwrap.mjs --package "$dir" ;; esac # Packed with the manifest it is published with: no exports entry names a source file. tarball="$(node scripts/publish-manifest.mjs "$dir" "$RUNNER_TEMP/workspace-packs")" npm publish "$tarball" --access public ${{ env.PRERELEASE == 'true' && '--tag next' || '' }} diff --git a/package-lock.json b/package-lock.json index 593630f0..dff4d17d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,11 +17,10 @@ "packages/wallet", "packages/contract", "packages/connect", - "packages/dev" + "packages/dev", + "packages/grant" ], "dependencies": { - "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@kuiralabs/midnight-connect": "0.1.0-rc.1", @@ -29,6 +28,7 @@ "@kuiralabs/midnight-dev": "0.1.0-rc.1", "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", + "@kuiralabs/midnight-grant": "0.1.0-rc.1", "@kuiralabs/midnight-wallet": "0.1.0-rc.1", "@modelcontextprotocol/sdk": "^1.27.1" }, @@ -700,6 +700,10 @@ "resolved": "packages/engine-rc", "link": true }, + "node_modules/@kuiralabs/midnight-grant": { + "resolved": "packages/grant", + "link": true + }, "node_modules/@kuiralabs/midnight-wallet": { "resolved": "packages/wallet", "link": true @@ -6318,6 +6322,22 @@ "node": ">=22" } }, + "packages/grant": { + "name": "@kuiralabs/midnight-grant", + "version": "0.1.0-rc.1", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-contract": "0.1.0-rc.1", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + }, + "engines": { + "node": ">=22" + } + }, "packages/wallet": { "name": "@kuiralabs/midnight-wallet", "version": "0.1.0-rc.1", diff --git a/package.json b/package.json index 0be0469c..7a032e3c 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,8 @@ "packages/wallet", "packages/contract", "packages/connect", - "packages/dev" + "packages/dev", + "packages/grant" ], "bin": { "midnight": "dist/wallet.js", @@ -54,7 +55,7 @@ }, "scripts": { "wallet": "tsx --conditions=midnight-cli-source src/wallet.ts", - "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && npm run build -w @kuiralabs/midnight-wallet && npm run build -w @kuiralabs/midnight-contract && npm run build -w @kuiralabs/midnight-connect && npm run build -w @kuiralabs/midnight-dev && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", + "build": "npm run build -w @kuiralabs/midnight-cli-core && npm run build -w @kuiralabs/midnight-chain && npm run build -w @kuiralabs/midnight-engine-rc && npm run build -w @kuiralabs/midnight-engine-beta && npm run build -w @kuiralabs/midnight-wallet && npm run build -w @kuiralabs/midnight-contract && npm run build -w @kuiralabs/midnight-connect && npm run build -w @kuiralabs/midnight-dev && npm run build -w @kuiralabs/midnight-grant && node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && bun build src/wallet.ts src/mcp-server.ts --outdir dist --splitting --target node --format esm --packages external --minify --banner \"#!/usr/bin/env node\"", "mcp": "tsx --conditions=midnight-cli-source src/mcp-server.ts", "link": "bun link", "prepublishOnly": "npm run build && npm run test", @@ -69,8 +70,6 @@ "readme-commands": "tsx --conditions=midnight-cli-source scripts/write-readme-commands.ts" }, "dependencies": { - "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@kuiralabs/midnight-connect": "0.1.0-rc.1", @@ -78,6 +77,7 @@ "@kuiralabs/midnight-dev": "0.1.0-rc.1", "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", + "@kuiralabs/midnight-grant": "0.1.0-rc.1", "@kuiralabs/midnight-wallet": "0.1.0-rc.1", "@modelcontextprotocol/sdk": "^1.27.1" }, diff --git a/packages/grant/api-report.md b/packages/grant/api-report.md new file mode 100644 index 00000000..60c14031 --- /dev/null +++ b/packages/grant/api-report.md @@ -0,0 +1,38 @@ +# API report: @kuiralabs/midnight-grant + +Generated by `node scripts/api-report.mjs write` from the code: every entry point the exports map makes importable, with what it exports. Don't edit it by hand. + +## `@kuiralabs/midnight-grant` + +```ts +export declare const accountProtector: WalletProtector; +export declare class NoAccountError extends Error { + readonly code = "NO_ACCOUNT"; + constructor(walletName: string, network: string); +} +export declare class NodeTooOldForAccountError extends Error { + readonly code = "UNSUPPORTED_NODE"; + constructor(version: string); +} +export declare class UnreachableByAccountError extends UsageError { + constructor(networkId: string, sdkSet?: SdkSet); +} +export declare function accountArtifactsDir(root: string): string; +export declare function accountRecordsDir(network: string, walletName: string, root: string): string; +``` + +## `@kuiralabs/midnight-grant/commands` + +```ts +export declare const grantCodes: readonly [ + { + readonly code: "NO_ACCOUNT"; + readonly exitCode: 1; + readonly order: 210; + readonly summary: "A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network."; + readonly recovery: "Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow)."; + } +]; +export declare const grantDefinition: CommandDefinition; +export declare const grantGuidance: PackageGuidance; +``` diff --git a/packages/grant/package.json b/packages/grant/package.json new file mode 100644 index 00000000..f03ab936 --- /dev/null +++ b/packages/grant/package.json @@ -0,0 +1,46 @@ +{ + "name": "@kuiralabs/midnight-grant", + "version": "0.1.0-rc.1", + "type": "module", + "description": "Grants for the Midnight CLI packages: mn grant (the wallet owner's account and the grants that let an agent spend from it, its owner devices and backups) over @kuiralabs/midnight-account-chain, and the protector wallet protect seals the accounts' records with", + "license": "Apache-2.0", + "author": "nel349", + "repository": { + "type": "git", + "url": "git+https://github.com/kuiralabs/midnight-cli.git", + "directory": "packages/grant" + }, + "bugs": { + "url": "https://github.com/kuiralabs/midnight-cli/issues" + }, + "engines": { + "node": ">=22" + }, + "exports": { + ".": { + "midnight-cli-source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./commands": { + "midnight-cli-source": "./src/commands.ts", + "types": "./dist/commands.d.ts", + "default": "./dist/commands.js" + } + }, + "files": [ + "dist", + "npm-shrinkwrap.json" + ], + "scripts": { + "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" + }, + "dependencies": { + "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.1", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-contract": "0.1.0-rc.1", + "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + } +} diff --git a/src/__tests__/account-backup.test.ts b/packages/grant/src/__tests__/account-backup.test.ts similarity index 98% rename from src/__tests__/account-backup.test.ts rename to packages/grant/src/__tests__/account-backup.test.ts index b535a33d..154d8b25 100644 --- a/src/__tests__/account-backup.test.ts +++ b/packages/grant/src/__tests__/account-backup.test.ts @@ -20,8 +20,8 @@ import { exportAccount, importAccount } from '../lib/grant/account-backup.ts'; import { createPendingDevice, openAccountKey, ownDeviceCode, sealedDeviceList } from '../lib/grant/sealed-account.ts'; import { parseDeviceCode } from '../lib/grant/device-code.ts'; import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStatePassword } from '../lib/grant/sealed-account.ts'; -import { stateRootIn } from '../../test-support/state-root-in.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); diff --git a/src/__tests__/device-code.test.ts b/packages/grant/src/__tests__/device-code.test.ts similarity index 100% rename from src/__tests__/device-code.test.ts rename to packages/grant/src/__tests__/device-code.test.ts diff --git a/src/__tests__/grant-account.test.ts b/packages/grant/src/__tests__/grant-account.test.ts similarity index 95% rename from src/__tests__/grant-account.test.ts rename to packages/grant/src/__tests__/grant-account.test.ts index 3c0c4c23..b9a97395 100644 --- a/src/__tests__/grant-account.test.ts +++ b/packages/grant/src/__tests__/grant-account.test.ts @@ -12,8 +12,8 @@ import { WrongPassphraseError, getNetworkConfig, createHost, PASSPHRASE_ENV } fr import { establishPassphrase } from '@kuiralabs/midnight-wallet'; import { openGrantAccount } from '../lib/grant/account.ts'; import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; -import { stateRootIn } from '../../test-support/state-root-in.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = createHost({ engineLoader: loadInstalledEngine }); diff --git a/src/__tests__/grant-deploy-cost.test.ts b/packages/grant/src/__tests__/grant-deploy-cost.test.ts similarity index 94% rename from src/__tests__/grant-deploy-cost.test.ts rename to packages/grant/src/__tests__/grant-deploy-cost.test.ts index 40166caa..59067ab0 100644 --- a/src/__tests__/grant-deploy-cost.test.ts +++ b/packages/grant/src/__tests__/grant-deploy-cost.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import { ERROR_CODES, EXIT_INSUFFICIENT_BALANCE, classifyError, DustRequiredError } from '@kuiralabs/midnight-cli-core'; import { MEASURED_ACCOUNT_DEPLOY, deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; -import { installedCommands } from '../lib/installed-commands.ts'; +import { CORE_CODES } from '../../../../test-support/core-codes.ts'; describe('deployShortOfDustNote', () => { it('says what a deploy takes, what the wallet had, and that running again carries on', () => { @@ -32,7 +32,7 @@ describe('deployShortOfDustNote', () => { it('leaves the error it is added to a Dust shortage, with the same exit code', () => { const fromServe = 'The wallet has no Dust available that covers this transaction\'s fee (Insufficient Funds: could not balance dust), and no balanced transaction is holding any back on this server.'; // As grant deploy throws it: the shortage, with the note. - expect(classifyError(new DustRequiredError(`${fromServe}\n\n${deployShortOfDustNote(0n)}`), installedCommands)) + expect(classifyError(new DustRequiredError(`${fromServe}\n\n${deployShortOfDustNote(0n)}`), CORE_CODES)) .toEqual({ exitCode: EXIT_INSUFFICIENT_BALANCE, errorCode: ERROR_CODES.DUST_REQUIRED }); }); }); diff --git a/src/__tests__/grant-owner-commands.test.ts b/packages/grant/src/__tests__/grant-owner-commands.test.ts similarity index 100% rename from src/__tests__/grant-owner-commands.test.ts rename to packages/grant/src/__tests__/grant-owner-commands.test.ts diff --git a/src/__tests__/grant-prepare.test.ts b/packages/grant/src/__tests__/grant-prepare.test.ts similarity index 97% rename from src/__tests__/grant-prepare.test.ts rename to packages/grant/src/__tests__/grant-prepare.test.ts index 1efc4cfc..be448fc6 100644 --- a/src/__tests__/grant-prepare.test.ts +++ b/packages/grant/src/__tests__/grant-prepare.test.ts @@ -7,8 +7,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { parseArgs, UsageError, createHost } from '@kuiralabs/midnight-cli-core'; -import { UnreachableByAccountError } from '../lib/grant/account.ts'; -import { NoAccountError, prepareGrant } from '../lib/grant/prepare.ts'; +import { NoAccountError, UnreachableByAccountError } from '../lib/grant/account-errors.ts'; +import { prepareGrant } from '../lib/grant/prepare.ts'; import { createAccountKey, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; // The host the tests' calls run in: nobody to ask, notices dropped. diff --git a/src/__tests__/grant-request.test.ts b/packages/grant/src/__tests__/grant-request.test.ts similarity index 100% rename from src/__tests__/grant-request.test.ts rename to packages/grant/src/__tests__/grant-request.test.ts diff --git a/src/__tests__/protect-account.test.ts b/packages/grant/src/__tests__/protect-account.test.ts similarity index 97% rename from src/__tests__/protect-account.test.ts rename to packages/grant/src/__tests__/protect-account.test.ts index fc903e89..b272ca7f 100644 --- a/src/__tests__/protect-account.test.ts +++ b/packages/grant/src/__tests__/protect-account.test.ts @@ -17,8 +17,8 @@ import { getNetworkConfig, createHost, PASSPHRASE_ENV } from '@kuiralabs/midnigh import { LEGACY_STORE_PASSWORD, openGrantAccount, privateStateLocationOf } from '../lib/grant/account.ts'; import { AccountMigrationInterruptedError, protectAccount } from '../lib/grant/protect-account.ts'; import { isSealedAccount } from '../lib/grant/sealed-account.ts'; -import { stateRootIn } from '../../test-support/state-root-in.ts'; -import { loadInstalledEngine } from '../lib/installed-engines.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; // The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. const host = createHost({ engineLoader: loadInstalledEngine }); diff --git a/src/__tests__/sealed-account.conformance.ts b/packages/grant/src/__tests__/sealed-account.conformance.ts similarity index 100% rename from src/__tests__/sealed-account.conformance.ts rename to packages/grant/src/__tests__/sealed-account.conformance.ts diff --git a/src/__tests__/sealed-account.test.ts b/packages/grant/src/__tests__/sealed-account.test.ts similarity index 100% rename from src/__tests__/sealed-account.test.ts rename to packages/grant/src/__tests__/sealed-account.test.ts diff --git a/packages/grant/src/commands.ts b/packages/grant/src/commands.ts new file mode 100644 index 00000000..4b6049d6 --- /dev/null +++ b/packages/grant/src/commands.ts @@ -0,0 +1,6 @@ +// @kuiralabs/midnight-grant/commands: the grant command, its codes and its +// agent guidance, for the shell that installs them. + +export { grantCodes } from './commands/grant.codes.ts'; +export { grantDefinition } from './commands/grant.definition.ts'; +export { grantGuidance } from './commands/grant.guidance.ts'; diff --git a/src/commands/grant.codes.ts b/packages/grant/src/commands/grant.codes.ts similarity index 100% rename from src/commands/grant.codes.ts rename to packages/grant/src/commands/grant.codes.ts diff --git a/src/commands/grant.definition.ts b/packages/grant/src/commands/grant.definition.ts similarity index 100% rename from src/commands/grant.definition.ts rename to packages/grant/src/commands/grant.definition.ts diff --git a/src/commands/grant.guidance.ts b/packages/grant/src/commands/grant.guidance.ts similarity index 100% rename from src/commands/grant.guidance.ts rename to packages/grant/src/commands/grant.guidance.ts diff --git a/src/commands/grant.ts b/packages/grant/src/commands/grant.ts similarity index 100% rename from src/commands/grant.ts rename to packages/grant/src/commands/grant.ts diff --git a/packages/grant/src/index.ts b/packages/grant/src/index.ts new file mode 100644 index 00000000..afaad8d7 --- /dev/null +++ b/packages/grant/src/index.ts @@ -0,0 +1,13 @@ +// @kuiralabs/midnight-grant: what mn grant leaves for the shell, a program and +// the MCP server. The protector `wallet protect` runs to seal the accounts an +// earlier mn kept in plain text; the errors a caller classifies grant's +// refusals by (a network the account package can't act on, a Node.js too old +// for it, a wallet with no account); and where a state root keeps the +// accounts' records and the account package's proving artefacts. None of them +// loads the account package or its SDK set: the shell loads this entry point +// for every wallet command. Each name is listed, so the API is what this file +// says. The grant command, its codes and guidance are "./commands". + +export { accountProtector } from './lib/grant/account-protector.ts'; +export { NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from './lib/grant/account-errors.ts'; +export { accountArtifactsDir, accountRecordsDir } from './lib/grant/account-records.ts'; diff --git a/src/lib/grant/account-backup.ts b/packages/grant/src/lib/grant/account-backup.ts similarity index 100% rename from src/lib/grant/account-backup.ts rename to packages/grant/src/lib/grant/account-backup.ts diff --git a/packages/grant/src/lib/grant/account-errors.ts b/packages/grant/src/lib/grant/account-errors.ts new file mode 100644 index 00000000..d56d2861 --- /dev/null +++ b/packages/grant/src/lib/grant/account-errors.ts @@ -0,0 +1,44 @@ +// The errors mn grant refuses with before it reaches the account package: a +// network the package can't act on, a Node.js older than it needs, a wallet +// with no account yet. They import no account package, so a caller (the +// shell, the MCP server, a program classifying a failure) has them without +// loading the account chain and the SDK set it is built on. + +import { UsageError, type SdkSet } from '@kuiralabs/midnight-cli-core'; + +/** A network the account package can't reach yet. */ +export class UnreachableByAccountError extends UsageError { + constructor(networkId: string, sdkSet: SdkSet = 'rc') { + super(sdkSet === 'rc' + ? `mn grant runs on ledger 9, which only a local network (undeployed) runs so far; ${networkId} is not one.` + // The account package is built on the rc set: its contracts, proving files and providers. + : `mn grant runs on the rc SDK set, and ${networkId} runs on the ${sdkSet} set. The account package has no ${sdkSet} build yet (its contracts need recompiling and new proving files), so grant can't act on it for now.`); + this.name = 'UnreachableByAccountError'; + Object.setPrototypeOf(this, UnreachableByAccountError.prototype); + } +} + +/** The Node.js the account package needs: it declares 22.18 or newer. */ +export const MIN_NODE_FOR_ACCOUNT = '22.18.0'; + +/** This Node.js is older than the account package needs. */ +export class NodeTooOldForAccountError extends Error { + readonly code = 'UNSUPPORTED_NODE'; + + constructor(version: string) { + super(`mn grant runs the account package, which needs Node.js ${MIN_NODE_FOR_ACCOUNT} or newer; this is Node.js ${version}. Install a current Node.js (https://nodejs.org) and run the command again.`); + this.name = 'NodeTooOldForAccountError'; + Object.setPrototypeOf(this, NodeTooOldForAccountError.prototype); + } +} + +/** The wallet has no account to run an owner command on. */ +export class NoAccountError extends Error { + readonly code = 'NO_ACCOUNT'; + + constructor(walletName: string, network: string) { + super(`Wallet "${walletName}" has no account on ${network} yet.\nDeploy one: midnight grant deploy`); + this.name = 'NoAccountError'; + Object.setPrototypeOf(this, NoAccountError.prototype); + } +} diff --git a/src/lib/grant/account-protector.ts b/packages/grant/src/lib/grant/account-protector.ts similarity index 100% rename from src/lib/grant/account-protector.ts rename to packages/grant/src/lib/grant/account-protector.ts diff --git a/src/lib/grant/account-records.ts b/packages/grant/src/lib/grant/account-records.ts similarity index 73% rename from src/lib/grant/account-records.ts rename to packages/grant/src/lib/grant/account-records.ts index e43a5495..1e206aca 100644 --- a/src/lib/grant/account-records.ts +++ b/packages/grant/src/lib/grant/account-records.ts @@ -1,7 +1,8 @@ // Where an account's records live: one directory per network and wallet under // ~/.midnight/accounts/, never in the account build's own directory. The build // writes them there (the owner's keys, the roster of grants, its private-state -// stores); mn only names the place. +// stores); mn only names the place. The account package caches its proving +// artefacts beside them, in ~/.midnight/account-artifacts/. import { mkdirSync } from 'node:fs'; import { basename, join } from 'node:path'; @@ -28,3 +29,10 @@ export function accountRecordsDir(network: string, walletName: string, root: str export function ensureAccountRecordsDir(dir: string): void { mkdirSync(dir, { recursive: true, mode: DIR_MODE }); } + +/** Where the account package caches its proving artefacts, under ~/.midnight: each file is fetched the first time a command proves with it. */ +const ACCOUNT_ARTIFACTS_DIR_NAME = 'account-artifacts'; + +export function accountArtifactsDir(root: string): string { + return join(root, ACCOUNT_ARTIFACTS_DIR_NAME); +} diff --git a/src/lib/grant/account.ts b/packages/grant/src/lib/grant/account.ts similarity index 81% rename from src/lib/grant/account.ts rename to packages/grant/src/lib/grant/account.ts index 85285416..b015c075 100644 --- a/src/lib/grant/account.ts +++ b/packages/grant/src/lib/grant/account.ts @@ -34,14 +34,9 @@ import { sealedOwnerStore, sealedPrivateStatePassword, } from './sealed-account.ts'; -import { UsageError, isValidNetworkName, sdkSetOfNetwork, type NetworkConfig, type SdkSet } from '@kuiralabs/midnight-cli-core'; - -/** Where the account package caches its proving artefacts, under ~/.midnight: each file is fetched the first time a command proves with it. */ -const ACCOUNT_ARTIFACTS_DIR_NAME = 'account-artifacts'; - -export function accountArtifactsDir(root: string): string { - return join(root, ACCOUNT_ARTIFACTS_DIR_NAME); -} +import { isValidNetworkName, sdkSetOfNetwork, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import { MIN_NODE_FOR_ACCOUNT, NodeTooOldForAccountError, UnreachableByAccountError } from './account-errors.ts'; +import { accountArtifactsDir } from './account-records.ts'; /** The network the account package acts on: ledger 9, which only a local network runs so far. */ const ACCOUNT_NETWORK_ID = 'undeployed'; @@ -61,18 +56,6 @@ export function privateStateLocationOf(recordsDir: string, password: () => strin return { database: join(recordsDir, PRIVATE_STATE_DATABASE), store: PRIVATE_STATE_STORE, password }; } -/** A network the account package can't reach yet. */ -export class UnreachableByAccountError extends UsageError { - constructor(networkId: string, sdkSet: SdkSet = 'rc') { - super(sdkSet === 'rc' - ? `mn grant runs on ledger 9, which only a local network (undeployed) runs so far; ${networkId} is not one.` - // The account package is built on the rc set: its contracts, proving files and providers. - : `mn grant runs on the rc SDK set, and ${networkId} runs on the ${sdkSet} set. The account package has no ${sdkSet} build yet (its contracts need recompiling and new proving files), so grant can't act on it for now.`); - this.name = 'UnreachableByAccountError'; - Object.setPrototypeOf(this, UnreachableByAccountError.prototype); - } -} - /** Throws when the account package can't act on `networkConfig`'s network, by the SDK set the config under the state root `root` gives it. */ export function assertAccountNetwork(networkConfig: NetworkConfig, root: string): void { const id = networkConfig.networkId.toLowerCase(); @@ -81,20 +64,6 @@ export function assertAccountNetwork(networkConfig: NetworkConfig, root: string) if (networkConfig.networkId.toLowerCase() !== ACCOUNT_NETWORK_ID) throw new UnreachableByAccountError(networkConfig.networkId); } -/** The Node.js the account package needs: it declares 22.18 or newer. */ -export const MIN_NODE_FOR_ACCOUNT = '22.18.0'; - -/** This Node.js is older than the account package needs. */ -export class NodeTooOldForAccountError extends Error { - readonly code = 'UNSUPPORTED_NODE'; - - constructor(version: string) { - super(`mn grant runs the account package, which needs Node.js ${MIN_NODE_FOR_ACCOUNT} or newer; this is Node.js ${version}. Install a current Node.js (https://nodejs.org) and run the command again.`); - this.name = 'NodeTooOldForAccountError'; - Object.setPrototypeOf(this, NodeTooOldForAccountError.prototype); - } -} - /** Throws when this Node.js is older than the account package needs. */ export function assertNodeRunsAccount(version: string = process.versions.node): void { const [major = 0, minor = 0] = version.split('.').map(Number); diff --git a/src/lib/grant/deploy-cost.ts b/packages/grant/src/lib/grant/deploy-cost.ts similarity index 100% rename from src/lib/grant/deploy-cost.ts rename to packages/grant/src/lib/grant/deploy-cost.ts diff --git a/src/lib/grant/device-code.ts b/packages/grant/src/lib/grant/device-code.ts similarity index 100% rename from src/lib/grant/device-code.ts rename to packages/grant/src/lib/grant/device-code.ts diff --git a/src/lib/grant/fee-wallet.ts b/packages/grant/src/lib/grant/fee-wallet.ts similarity index 100% rename from src/lib/grant/fee-wallet.ts rename to packages/grant/src/lib/grant/fee-wallet.ts diff --git a/src/lib/grant/owner-commands.ts b/packages/grant/src/lib/grant/owner-commands.ts similarity index 100% rename from src/lib/grant/owner-commands.ts rename to packages/grant/src/lib/grant/owner-commands.ts diff --git a/src/lib/grant/prepare.ts b/packages/grant/src/lib/grant/prepare.ts similarity index 90% rename from src/lib/grant/prepare.ts rename to packages/grant/src/lib/grant/prepare.ts index e4279964..db0c18b4 100644 --- a/src/lib/grant/prepare.ts +++ b/packages/grant/src/lib/grant/prepare.ts @@ -6,6 +6,7 @@ import { type ParsedArgs, getFlag, UsageError, type PayingTarget, resolvePayingTarget, type Host } from '@kuiralabs/midnight-cli-core'; import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '@kuiralabs/midnight-wallet'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; +import { NoAccountError } from './account-errors.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; import { type GrantRequest, resolveGrantRequest } from './request.ts'; import { contractAddressOnRecord } from './sealed-account.ts'; @@ -26,17 +27,6 @@ export interface PreparedGrant { account: AccountOnRecord | null; } -/** The wallet has no account to run an owner command on. */ -export class NoAccountError extends Error { - readonly code = 'NO_ACCOUNT'; - - constructor(walletName: string, network: string) { - super(`Wallet "${walletName}" has no account on ${network} yet.\nDeploy one: midnight grant deploy`); - this.name = 'NoAccountError'; - Object.setPrototypeOf(this, NoAccountError.prototype); - } -} - /** The account the records in `recordsDir` name, if any. Reads the records alone: no chain, no wallet. */ export async function accountOnRecord(recordsDir: string): Promise { // A sealed account keeps its address in clear beside its sealed records. diff --git a/src/lib/grant/protect-account.ts b/packages/grant/src/lib/grant/protect-account.ts similarity index 100% rename from src/lib/grant/protect-account.ts rename to packages/grant/src/lib/grant/protect-account.ts diff --git a/src/lib/grant/request.ts b/packages/grant/src/lib/grant/request.ts similarity index 100% rename from src/lib/grant/request.ts rename to packages/grant/src/lib/grant/request.ts diff --git a/src/lib/grant/sealed-account.ts b/packages/grant/src/lib/grant/sealed-account.ts similarity index 100% rename from src/lib/grant/sealed-account.ts rename to packages/grant/src/lib/grant/sealed-account.ts diff --git a/packages/grant/tsconfig.build.json b/packages/grant/tsconfig.build.json new file mode 100644 index 00000000..70e97051 --- /dev/null +++ b/packages/grant/tsconfig.build.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": [ + "ES2022" + ], + "moduleResolution": "bundler", + "customConditions": [ + "midnight-cli-source" + ], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowSyntheticDefaultImports": true, + "rewriteRelativeImportExtensions": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "types": [ + "node" + ] + }, + "include": [ + "src/**/*.ts" + ], + // A package's tests run in the workspace; they are neither built nor published. + "exclude": [ + "src/**/__tests__" + ] +} diff --git a/scripts/api-report.mjs b/scripts/api-report.mjs index b54129ad..7c0ae6d9 100644 --- a/scripts/api-report.mjs +++ b/scripts/api-report.mjs @@ -21,7 +21,7 @@ import { barrelExports } from './check-layering.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); /** The public packages, by folder under packages/. */ -export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta', 'wallet', 'contract', 'connect', 'dev']; +export const PUBLIC_PACKAGES = ['cli-core', 'chain', 'engine-rc', 'engine-beta', 'wallet', 'contract', 'connect', 'dev', 'grant']; /** The report's path for the package in `dir` (a folder under packages/). */ export function reportPath(dir) { diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index cc192685..26554886 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -157,6 +157,7 @@ export const WORKSPACE_PACKAGES = [ { name: '@kuiralabs/midnight-contract', root: join(ROOT, 'packages', 'contract'), dir: join(ROOT, 'packages', 'contract', 'src'), home: 'contract' }, { name: '@kuiralabs/midnight-connect', root: join(ROOT, 'packages', 'connect'), dir: join(ROOT, 'packages', 'connect', 'src'), home: 'connect' }, { name: '@kuiralabs/midnight-dev', root: join(ROOT, 'packages', 'dev'), dir: join(ROOT, 'packages', 'dev', 'src'), home: 'dev' }, + { name: '@kuiralabs/midnight-grant', root: join(ROOT, 'packages', 'grant'), dir: join(ROOT, 'packages', 'grant', 'src'), home: 'grant' }, // The rc engine: its files read as engine/rc/, its index the package itself. { name: '@kuiralabs/midnight-engine-rc', root: join(ROOT, 'packages', 'engine-rc'), dir: join(ROOT, 'packages', 'engine-rc', 'src'), prefix: 'engine/rc/', home: 'engine' }, { name: '@kuiralabs/midnight-engine-beta', root: join(ROOT, 'packages', 'engine-beta'), dir: join(ROOT, 'packages', 'engine-beta', 'src'), prefix: 'engine/beta/', home: 'engine' }, diff --git a/scripts/code-reach.mjs b/scripts/code-reach.mjs index 4b48d6c1..3d7df3a1 100644 --- a/scripts/code-reach.mjs +++ b/scripts/code-reach.mjs @@ -136,7 +136,7 @@ export const CUT_IMPORTS = ENGINE_SETS.flatMap((set) => [...new Set(Object.value /** What the shell gives a command whose definition's `shell` asks for it, and the module it loads. */ export const SHELL_PROVISIONS = { payer: 'packages/connect/src/lib/serve-payer.ts', - protectors: 'src/lib/grant/account-protector.ts', + protectors: 'packages/grant/src/lib/grant/account-protector.ts', }; // The class EngineError takes its code as its first argument: `new EngineError('X', …)`, or a subclass's `super('X', …)`. diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index dcc3f39f..157f1a1b 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -2,9 +2,9 @@ // depends on, serves them from a local registry as npm serves published // packages, installs mn globally from it into an empty prefix, and checks the // tree the install holds still works: one copy of each WASM package per SDK -// engine (the shrinkwrap mn ships keeps each engine's set apart), each engine -// loading, the packages a contract run's script imports, and the files the -// code reads at run time. +// engine (the shrinkwrap mn ships keeps each engine's set apart), grant on the +// rc engine's copies, each engine loading, the packages a contract run's +// script imports, and the files the code reads at run time. // // The test suite runs on the lockfile's tree, which a consumer never sees. Two // features broke that way without a test noticing: a newer @scure/base refused @@ -20,11 +20,41 @@ import { execFileSync, spawn } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; +import { PUBLIC_PACKAGES } from './api-report.mjs'; import { packRelease } from './pack-release.mjs'; +import { SOURCE_CONDITION } from './publish-manifest.mjs'; const repo = new URL('..', import.meta.url).pathname; const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); +/** Each public package's name, read from its manifest in the workspace. */ +const PUBLIC_NAMES = PUBLIC_PACKAGES.map((dir) => JSON.parse(readFileSync(join(repo, 'packages', dir, 'package.json'), 'utf-8')).name); + +/** + * What an installed package's manifest says of its source, which no published + * manifest may: the source condition, and each exports target that is a + * source file (under ./src/, or a .ts file that is not a declaration). + */ +function sourceInManifest(manifest) { + const found = []; + const walk = (value, at) => { + if (typeof value === 'string') { + if (value.startsWith('./src/') || (value.endsWith('.ts') && !value.endsWith('.d.ts'))) found.push(`${at} → ${value}`); + return; + } + if (typeof value !== 'object' || value === null) return; + for (const [key, inner] of Object.entries(value)) { + if (key === SOURCE_CONDITION) found.push(`${at} ${SOURCE_CONDITION}`); + walk(inner, at === '' ? key : `${at} ${key}`); + } + }; + walk(manifest.exports ?? {}, ''); + return found; +} + +/** The SDK's WASM packages: an object one copy of them makes, another copy refuses. */ +const WASM_PACKAGES = ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']; + /** Every installed copy of a package under `root`, as its versions. */ function copiesOf(root, name) { const found = []; @@ -125,6 +155,23 @@ const check = (what, ok, detail = '') => { if (!ok) failures.push(what); }; +/** + * grant's account chain is built on the rc set: in the install at `root`, + * grant resolves one copy of each WASM package, at the rc engine's version. + * With `sameCopy`, the very copy the rc engine resolves: mn's shrinkwrap lays + * the two out on one tree. A program that installs both packages itself gets + * each one's shrinkwrapped tree under it, so the copies match by version only. + */ +function checkGrantOnRcSet(root, who, { sameCopy }) { + const at = (copies) => copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(root).length)}`).join(', '); + for (const sdk of WASM_PACKAGES) { + const grant = resolvedCopies(join(root, 'node_modules', '@kuiralabs', 'midnight-grant'), sdk); + const rc = resolvedCopies(join(root, 'node_modules', '@kuiralabs', 'midnight-engine-rc'), sdk); + const matches = grant.length === 1 && rc.length === 1 && (sameCopy ? grant[0].dir === rc[0].dir : grant[0].version === rc[0].version); + check(`${who}@kuiralabs/midnight-grant resolves one copy of ${sdk}, ${sameCopy ? "the rc engine's" : "at the rc engine's version"}`, matches, `grant: ${at(grant)}; rc engine: ${at(rc)}`); + } +} + const work = mkdtempSync(join(tmpdir(), 'mn-fresh-install-')); let registry; try { @@ -143,19 +190,25 @@ try { check('the installed mn runs', run(mn, ['--version'], work).trim() === version, version); check('the package shipped its shrinkwrap', existsSync(join(installed, 'npm-shrinkwrap.json'))); + // mn depends on every public package, so the checks below of each package mn installed cover them all. + const missing = PUBLIC_NAMES.filter((name) => !workspaces.some((pkg) => pkg.name === name)); + check('mn installs every public package', missing.length === 0, missing.length > 0 ? `not a dependency of mn: ${missing.join(', ')}` : `${PUBLIC_NAMES.length} packages`); // One copy of each workspace package: a second copy of core's module state (its settings, its typed errors) splits the process. for (const { name } of workspaces) { const copies = copiesOf(installed, name); check(`one copy of ${name}`, copies.length === 1, copies.join(', ')); + const source = sourceInManifest(JSON.parse(readFileSync(join(installed, 'node_modules', name, 'package.json'), 'utf-8'))); + check(`the installed ${name} manifest names no source`, source.length === 0, source.join(', ')); } // Each engine resolves one copy of each WASM package: an object made by one copy is refused by another. for (const { name } of workspaces.filter(({ name }) => name.startsWith('@kuiralabs/midnight-engine-'))) { const engine = join(installed, 'node_modules', name); - for (const sdk of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { + for (const sdk of WASM_PACKAGES) { const copies = resolvedCopies(engine, sdk); check(`${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(installed).length)}`).join(', ')); } } + checkGrantOnRcSet(installed, '', { sameCopy: true }); // A shielded address is longer than bech32's 90 characters; the address // library must still read the one the installed mn derives. @@ -265,9 +318,10 @@ try { check(`${uri} names only tools the server has`, unknown.length === 0, unknown.length > 0 ? `not a tool: ${unknown.join(', ')}` : `${named.length} of ${tools.length} tools named`); } - // A program that loads an engine without mn: it installs core, chain and the - // engines from the registry, each engine with the shrinkwrap it ships, and - // gets each engine's SDK set once beside one core and one chain it shares. + // A program that loads an engine without mn: it installs the workspace + // packages from the registry, each engine and grant with the shrinkwrap it + // ships, and gets each engine's SDK set once beside one copy of each package + // it shares. const outside = join(work, 'outside'); mkdirSync(outside); writeFileSync(join(outside, 'package.json'), JSON.stringify({ name: 'outside', private: true, type: 'module' })); @@ -278,11 +332,12 @@ try { } for (const { name } of workspaces.filter(({ name }) => name.startsWith('@kuiralabs/midnight-engine-'))) { const engine = join(outside, 'node_modules', name); - for (const sdk of ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']) { + for (const sdk of WASM_PACKAGES) { const copies = resolvedCopies(engine, sdk); check(`a program outside mn: ${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(outside).length)}`).join(', ')); } } + checkGrantOnRcSet(outside, 'a program outside mn: ', { sameCopy: false }); writeFileSync(join(outside, 'load.mjs'), ` import { createHost } from '@kuiralabs/midnight-cli-core'; const host = createHost({ @@ -297,14 +352,16 @@ try { } // The installed packages are imported by their entry points alone: each - // named entry point loads, the published manifests name no source file, - // and a module that is not an entry point is refused. + // named entry point loads, the published manifests name no source (neither + // the source condition nor a source file), and a module that is not an + // entry point is refused. writeFileSync(join(outside, 'entry.mjs'), ` try { await import(process.argv[2]); console.log('loaded'); } catch (error) { console.log(error.code ?? error.message); } `); for (const { name } of workspaces) { const manifest = readFileSync(join(outside, 'node_modules', name, 'package.json'), 'utf-8'); - check(`a program outside mn: ${name}'s manifest names no source file`, !manifest.includes('midnight-cli-source')); + const source = sourceInManifest(JSON.parse(manifest)); + check(`a program outside mn: ${name}'s manifest names no source`, source.length === 0 && !manifest.includes(SOURCE_CONDITION), source.join(', ')); for (const entry of Object.keys(JSON.parse(manifest).exports).filter((key) => !key.includes('*'))) { const specifier = entry === '.' ? name : `${name}${entry.slice(1)}`; const loaded = run(process.execPath, ['entry.mjs', specifier], outside).trim(); @@ -312,8 +369,9 @@ try { } } // A module of each package that is not an entry point, named as the open - // `./*` used to export it (core's lib/errors as `/lib/errors`). - for (const [name, deepPath] of [ + // `./*` used to export it (core's lib/errors as `/lib/errors`): one + // for every public package. + const deepPaths = [ ['@kuiralabs/midnight-cli-core', 'lib/errors'], ['@kuiralabs/midnight-chain', 'lib/chain-id'], ['@kuiralabs/midnight-engine-rc', 'derive-address'], @@ -322,7 +380,11 @@ try { ['@kuiralabs/midnight-contract', 'lib/contract/runner'], ['@kuiralabs/midnight-connect', 'lib/ws-rpc'], ['@kuiralabs/midnight-dev', 'lib/localnet'], - ]) { + ['@kuiralabs/midnight-grant', 'lib/grant/account'], + ]; + const untried = PUBLIC_NAMES.filter((name) => !deepPaths.some(([each]) => each === name)); + check('a deep path is tried for every public package', untried.length === 0, untried.length > 0 ? `none for ${untried.join(', ')}` : ''); + for (const [name, deepPath] of deepPaths) { check(`a program outside mn finds ${name}'s ${deepPath} built`, existsSync(join(outside, 'node_modules', name, 'dist', `${deepPath}.js`))); const deep = run(process.execPath, ['entry.mjs', `${name}/${deepPath}`], outside).trim(); check(`a program outside mn is refused ${name}/${deepPath}`, deep === 'ERR_PACKAGE_PATH_NOT_EXPORTED', deep); diff --git a/scripts/make-shrinkwrap.mjs b/scripts/make-shrinkwrap.mjs index eef258ff..f314ed50 100644 --- a/scripts/make-shrinkwrap.mjs +++ b/scripts/make-shrinkwrap.mjs @@ -13,10 +13,12 @@ // under it, and its tarball and integrity from `dist`. // // Each SDK engine ships one too (`--package packages/engine-*`), so a program -// that installs an engine without mn gets the set the tests ran on. It leaves -// out the workspace packages the engine depends on (core and chain): those -// are shared with the program that loads the engine, which installs them -// itself, so the process holds one copy of each. +// that installs an engine without mn gets the set the tests ran on; and so +// does grant (`--package packages/grant`), whose account chain is built on the +// rc set. It leaves out the workspace packages the package depends on (core +// and chain; for grant also wallet and contract): those are shared with the +// program that loads it, which installs them itself, so the process holds one +// copy of each. // // The release job writes them beside each package.json just before // publishing (npm packs npm-shrinkwrap.json with the package, as each `files` diff --git a/scripts/pack-release.d.mts b/scripts/pack-release.d.mts new file mode 100644 index 00000000..cb928e0b --- /dev/null +++ b/scripts/pack-release.d.mts @@ -0,0 +1,10 @@ +// Types for what scripts/pack-release.mjs exports when imported. +/** Whether a workspace package ships a shrinkwrap of its own: each engine and grant. */ +export function shipsShrinkwrap(name: string): boolean; +/** Packs the release into `dir` for a registry on `port` (0: any free one), leaving that registry running. */ +export function packRelease(dir: string, port?: number): Promise<{ + registry: { url: string; close(): Promise }; + name: string; + version: string; + workspaces: { folder: string; name: string; version: string }[]; +}>; diff --git a/scripts/pack-release.mjs b/scripts/pack-release.mjs index ae983dd7..ce45f066 100644 --- a/scripts/pack-release.mjs +++ b/scripts/pack-release.mjs @@ -1,5 +1,5 @@ // mn as a release publishes it, packed into a folder: the workspace packages -// mn depends on (each engine with its shrinkwrap, each with the manifest it is +// mn depends on (each engine and grant with its shrinkwrap, each with the manifest it is // published with: scripts/publish-manifest.mjs), and mn with the shrinkwrap // the release job writes, its workspace packages' tarballs and integrity as a // local registry on `port` serves them (scripts/local-registry.mjs). Until those packages are on npm, a @@ -23,6 +23,13 @@ import { packPublished } from './publish-manifest.mjs'; const repo = fileURLToPath(new URL('..', import.meta.url)); const run = (command, args, cwd) => execFileSync(command, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); +/** + * Whether a workspace package ships a shrinkwrap of its own: each engine (its + * SDK set) and grant (the account chain, built on the rc set), as the release + * job writes them. + */ +export const shipsShrinkwrap = (name) => name.startsWith('@kuiralabs/midnight-engine-') || name === '@kuiralabs/midnight-grant'; + /** * Packs the release into `dir` for a registry on `port` (0: any free one), * leaving that registry running; resolves to it, mn's name and version, and @@ -37,14 +44,14 @@ export async function packRelease(dir, port = 0) { return { folder, name, version }; }) .filter(({ name }) => manifest.dependencies[name] !== undefined); - // Each engine with the shrinkwrap the release job writes for it. + // Each engine and grant with the shrinkwrap the release job writes for it. for (const { folder, name } of workspaces) { - const engine = name.startsWith('@kuiralabs/midnight-engine-'); - if (engine) makeShrinkwrap({ dir: folder }); + const shrinkwrapped = shipsShrinkwrap(name); + if (shrinkwrapped) makeShrinkwrap({ dir: folder }); try { packPublished(join(repo, folder), dir); } finally { - if (engine) rmSync(join(repo, folder, 'npm-shrinkwrap.json'), { force: true }); + if (shrinkwrapped) rmSync(join(repo, folder, 'npm-shrinkwrap.json'), { force: true }); } } const registry = await startLocalRegistryProcess(dir, port); diff --git a/src/__tests__/api-report.test.ts b/src/__tests__/api-report.test.ts index ddbad101..f2468d38 100644 --- a/src/__tests__/api-report.test.ts +++ b/src/__tests__/api-report.test.ts @@ -1,13 +1,25 @@ // Each public package's API report is the API its code has: a change to an // export fails here until `node scripts/api-report.mjs write` writes the report -// again, so the change shows in review. +// again, so the change shows in review. Each report has a section for every +// entry point its package's exports map lists, and no other. import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; import { PUBLIC_PACKAGES, apiReport, reportPath } from '../../scripts/api-report.mjs'; +const PACKAGES = join(import.meta.dirname, '..', '..', 'packages'); + describe('the API reports', () => { it.each([...PUBLIC_PACKAGES])('%s: the checked-in report is the code\'s API', (dir) => { expect(readFileSync(reportPath(dir), 'utf8'), 'run node scripts/api-report.mjs write and review the diff').toBe(apiReport(dir)); }, 120_000); }); + +describe("each API report's sections", () => { + it.each([...PUBLIC_PACKAGES])('%s: one for each entry point', (dir) => { + const { name, exports } = JSON.parse(readFileSync(join(PACKAGES, dir, 'package.json'), 'utf8')) as { name: string; exports: Record }; + const sections = [...readFileSync(reportPath(dir), 'utf8').matchAll(/^## `([^`]+)`$/gm)].map((match) => match[1]); + expect(sections.sort()).toStrictEqual(Object.keys(exports).map((subpath) => (subpath === '.' ? name : `${name}${subpath.slice(1)}`)).sort()); + }); +}); diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index c46bc529..99a82c4f 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -195,7 +195,7 @@ describe('the accepted flags', () => { kinds.set(m[2]!, (kinds.get(m[2]!) ?? new Set()).add(m[1] !== 'hasFlag')); } } - // The grant request's limits are read in a loop over their names (LIMIT_FLAGS in lib/grant/request.ts), as values. + // The grant request's limits are read in a loop over their names (LIMIT_FLAGS in the grant package's lib/grant/request.ts), as values. for (const limit of ['cap', 'per-call', 'max-coin', 'expires-in']) kinds.set(limit, new Set([true])); for (const command of registry.commands) { for (const flag of [...command.flags, ...registry.globalFlags]) { diff --git a/src/__tests__/entry-points.test.ts b/src/__tests__/entry-points.test.ts index c4bedfc7..8f86ecaf 100644 --- a/src/__tests__/entry-points.test.ts +++ b/src/__tests__/entry-points.test.ts @@ -20,6 +20,7 @@ const ENTRY_POINTS: Record = { contract: ['.', './commands'], connect: ['.', './commands'], dev: ['.', './commands'], + grant: ['.', './commands'], }; describe('the public entry points', () => { diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index bcea5e03..befdd215 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -37,8 +37,7 @@ import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { cliCall } from './helpers/cli-call.ts'; import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; import { UnsupportedNodeError } from '../lib/node-version.ts'; -import { NoAccountError } from '../lib/grant/prepare.ts'; -import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; +import { NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from '@kuiralabs/midnight-grant'; import { installedCommands } from '../lib/installed-commands.ts'; // The handlers, as the shell loads them. diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 84060b65..81f38838 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -1,8 +1,7 @@ import { describe, it, expect } from 'vitest'; import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR, EXIT_INVALID_ARGS, WrongPassphraseError, OtherSdkSetError, UsageError } from '@kuiralabs/midnight-cli-core'; import { MixedSdkLayoutError, toEngineError } from '@kuiralabs/midnight-cli-core/engine'; -import { NodeTooOldForAccountError, UnreachableByAccountError } from '../lib/grant/account.ts'; -import { NoAccountError } from '../lib/grant/prepare.ts'; +import { NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from '@kuiralabs/midnight-grant'; import { NoPassphraseError } from '@kuiralabs/midnight-wallet'; import { installedCommands } from '../lib/installed-commands.ts'; diff --git a/src/__tests__/package-metadata.test.ts b/src/__tests__/package-metadata.test.ts index 2ed72ba3..f003e1f9 100644 --- a/src/__tests__/package-metadata.test.ts +++ b/src/__tests__/package-metadata.test.ts @@ -3,6 +3,8 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { PKG_REPOSITORY_URL } from '../lib/pkg.ts'; import { buildManual } from '../commands/manual.ts'; +import { PUBLIC_PACKAGES } from '../../scripts/api-report.mjs'; +import { shipsShrinkwrap } from '../../scripts/pack-release.mjs'; // The root package.json is the one place the repository's address is written. // Every published package must carry the same address, because npm provenance @@ -56,7 +58,54 @@ describe('the SDK in the manifests', () => { } }); - it('is no dependency of core, chain, wallet, contract, connect or dev', () => { - for (const dir of ['cli-core', 'chain', 'wallet', 'contract', 'connect', 'dev']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); + it('is no dependency of core, chain, wallet, contract, connect, dev or grant', () => { + for (const dir of ['cli-core', 'chain', 'wallet', 'contract', 'connect', 'dev', 'grant']) expect(Object.keys(manifest(dir).dependencies ?? {}).filter(isSdk), dir).toStrictEqual([]); + }); +}); + +// What npm shows of each public package, and what an install of it holds: +// the same license, author and Node.js as mn, and only its build (with the +// shrinkwrap the release job writes, for a package that ships one). +describe("the public packages' manifests", () => { + const manifest = (dir: string) => JSON.parse(readFileSync(join('packages', dir, 'package.json'), 'utf8')); + + it('are every @kuiralabs workspace package mn depends on', () => { + const workspaceNames = (root.workspaces as string[]).map((folder) => JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8')).name as string); + const ours = workspaceNames.filter((name) => name.startsWith('@kuiralabs/')); + expect(PUBLIC_PACKAGES.map((dir) => manifest(dir).name).sort()).toStrictEqual(ours.sort()); + for (const name of ours) expect(root.dependencies[name], name).toBeDefined(); + }); + + it.each([...PUBLIC_PACKAGES])("%s: mn's license, its author's GitHub account, mn's Node.js, and only its build in files", (dir) => { + const { name, license, author, engines, files } = manifest(dir); + expect(license).toBe(root.license); + expect(root.author).toContain(`https://github.com/${author}`); + expect(engines).toStrictEqual({ node: root.engines.node }); + expect(files).toStrictEqual(shipsShrinkwrap(name) ? ['dist', 'npm-shrinkwrap.json'] : ['dist']); + }); +}); + +// The release job publishes the public packages before mn, each after the +// workspace packages it declares, so a package's exact pins resolve when it +// is published. +describe("the release job's publish order", () => { + const workflow = readFileSync(join('.github', 'workflows', 'release-sidecar.yml'), 'utf8'); + const step = workflow.slice(workflow.indexOf('- name: Publish the workspace packages mn depends on')); + const order = /for dir in ([^;]+); do/.exec(step)![1]!.trim().split(/\s+/).map((dir) => dir.replace(/^packages\//, '')); + + it('publishes every public package, once', () => { + expect([...order].sort()).toStrictEqual([...PUBLIC_PACKAGES].sort()); + }); + + it('publishes each package after the workspace packages it depends on', () => { + const dirOf = new Map(PUBLIC_PACKAGES.map((dir) => [JSON.parse(readFileSync(join('packages', dir, 'package.json'), 'utf8')).name as string, dir])); + for (const [at, dir] of order.entries()) { + const declared = Object.keys(JSON.parse(readFileSync(join('packages', dir, 'package.json'), 'utf8')).dependencies ?? {}).filter((name) => dirOf.has(name)); + for (const name of declared) expect(order.indexOf(dirOf.get(name)!), `${dir} needs ${name} published first`).toBeLessThan(at); + } + }); + + it('publishes mn after them', () => { + expect(workflow.indexOf('- name: Publish main package')).toBeGreaterThan(workflow.indexOf('- name: Publish the workspace packages mn depends on')); }); }); diff --git a/src/__tests__/payer.test.ts b/src/__tests__/payer.test.ts index f9a2117b..e1589960 100644 --- a/src/__tests__/payer.test.ts +++ b/src/__tests__/payer.test.ts @@ -9,16 +9,17 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { parseArgs, saveCliConfig, NoPayerError, resolvePayingTarget, networkTargetOf, type NetworkName, createSdkWarningRouter, CancelledError, createHost } from '@kuiralabs/midnight-cli-core'; import { silentSpinner } from '@kuiralabs/midnight-cli-core/ui'; -import { NoAccountError } from '../lib/grant/prepare.ts'; +import { NoAccountError } from '@kuiralabs/midnight-grant'; import { probeServeNetwork, servePayerAt } from '@kuiralabs/midnight-connect'; import { assertWalletCanPay } from '@kuiralabs/midnight-wallet'; import { contractDefinition } from '@kuiralabs/midnight-contract/commands'; -import grantCommand from '../commands/grant.ts'; +import { grantDefinition } from '@kuiralabs/midnight-grant/commands'; import { cliCall } from './helpers/cli-call.ts'; import { stateRootIn } from '../../test-support/state-root-in.ts'; -// The handler, as the shell loads it. +// The handlers, as the shell loads them. const { default: contractCommand } = await contractDefinition.load(); +const { default: grantCommand } = await grantDefinition.load(); // The host the tests' calls run in: nobody to ask, notices dropped. const host = createHost(); diff --git a/src/__tests__/sdk-free-base.test.ts b/src/__tests__/sdk-free-base.test.ts index 58b08fb5..c7c39fd7 100644 --- a/src/__tests__/sdk-free-base.test.ts +++ b/src/__tests__/sdk-free-base.test.ts @@ -2,7 +2,8 @@ // in core and chain) load with no Midnight SDK: each is imported in a node // whose module hook refuses every Midnight SDK and account package. And the // built `mn` loads none for --version, help or config, which run before any -// command needs one. +// command needs one, or for wallet list, whose dispatch loads grant's entry +// point for the protector `wallet protect` runs. import { describe, expect, it } from 'vitest'; import { spawnSync } from 'node:child_process'; @@ -84,7 +85,7 @@ describe('the built mn', () => { // the bundle's external packages resolve as they do for an installed mn. const out = join(ROOT, 'node_modules', '.cache', 'mn-sdk-loads-build'); - it('loads no Midnight SDK for --version, help or config get', () => { + it('loads no Midnight SDK for --version, help, config get or wallet list', () => { const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) as { scripts: { build: string } }; const bunBuild = pkg.scripts.build.slice(pkg.scripts.build.indexOf('bun build')); expect(bunBuild, 'the build script runs bun build into dist').toContain('--outdir dist '); @@ -98,7 +99,7 @@ describe('the built mn', () => { const dir = mkdtempSync(join(tmpdir(), 'mn-sdk-loads-')); try { const register = sdkHook(dir, 'record'); - for (const args of [['--version'], ['help'], ['config', 'get', 'network']]) { + for (const args of [['--version'], ['help'], ['config', 'get', 'network'], ['wallet', 'list']]) { rmSync(join(dir, 'sdk.log'), { force: true }); const run = spawnSync(process.execPath, ['--import', pathToFileURL(register).href, bin, ...args], { cwd: dir, encoding: 'utf8', timeout: 60_000, input: '', env: { ...process.env, HOME: dir, NO_COLOR: '1' }, diff --git a/src/__tests__/state-root.test.ts b/src/__tests__/state-root.test.ts index 934a653a..c0fe5ecf 100644 --- a/src/__tests__/state-root.test.ts +++ b/src/__tests__/state-root.test.ts @@ -14,8 +14,7 @@ import { testHost } from '../../test-support/test-host.ts'; import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; import { cliCall } from './helpers/cli-call.ts'; import { passphraseForNewSecret, createWallet, walletSecretFrom } from '@kuiralabs/midnight-wallet'; -import { accountRecordsDir } from '../lib/grant/account-records.ts'; -import { accountArtifactsDir } from '../lib/grant/account.ts'; +import { accountArtifactsDir, accountRecordsDir } from '@kuiralabs/midnight-grant'; import { getComposePath } from '@kuiralabs/midnight-dev'; import before from './fixtures/state-layout-before-1g.json'; diff --git a/src/__tests__/two-hosts.test.ts b/src/__tests__/two-hosts.test.ts index cb8d4dad..3c6280bd 100644 --- a/src/__tests__/two-hosts.test.ts +++ b/src/__tests__/two-hosts.test.ts @@ -95,7 +95,7 @@ async function run(host: Host, argv: string[]): Promise> output, host, loadPayer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, - loadProtectors: async () => [(await import('../lib/grant/account-protector.ts')).accountProtector], + loadProtectors: async () => [(await import('@kuiralabs/midnight-grant')).accountProtector], }); if (result === undefined) throw new Error(`${argv.join(' ')} wrote no result`); return result; diff --git a/src/__tests__/wallet-protect.test.ts b/src/__tests__/wallet-protect.test.ts index a3d03616..83ab3150 100644 --- a/src/__tests__/wallet-protect.test.ts +++ b/src/__tests__/wallet-protect.test.ts @@ -15,7 +15,7 @@ import { walletDefinition } from '@kuiralabs/midnight-wallet/commands'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; -import { accountProtector } from '../lib/grant/account-protector.ts'; +import { accountProtector } from '@kuiralabs/midnight-grant'; import { stateRootIn } from '../../test-support/state-root-in.ts'; import { cliCall } from './helpers/cli-call.ts'; import { testHost } from '../../test-support/test-host.ts'; diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 69d8eb3b..58d47f39 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -12,12 +12,10 @@ import { walletDefinition, generateDefinition, infoDefinition, balanceDefinition import { inspectCostDefinition, contractDefinition, contractGuidance, contractCodes } from '@kuiralabs/midnight-contract/commands'; import { serveDefinition, connectGuidance } from '@kuiralabs/midnight-connect/commands'; import { testDefinition, devDefinition, localnetDefinition, devGuidance, devCodes } from '@kuiralabs/midnight-dev/commands'; -import { grantDefinition } from '../commands/grant.definition.ts'; +import { grantDefinition, grantGuidance, grantCodes } from '@kuiralabs/midnight-grant/commands'; import { statusDefinition, txDefinition, chainGuidance, chainCodes } from '@kuiralabs/midnight-chain/commands'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; -import { grantGuidance } from '../commands/grant.guidance.ts'; -import { grantCodes } from '../commands/grant.codes.ts'; /** The shell answers these before any command runs: no tool passes them on. */ const SHELL_ANSWERS = { notForAgents: 'the shell answers it before any command runs' }; diff --git a/src/wallet.ts b/src/wallet.ts index 9cb1616c..a763fea1 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -94,7 +94,7 @@ async function run(): Promise { host, loadPayer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, // wallet protect also seals grant's accounts, through the protector grant provides. - loadProtectors: async () => [(await import('./lib/grant/account-protector.ts')).accountProtector], + loadProtectors: async () => [(await import('@kuiralabs/midnight-grant')).accountProtector], }); } diff --git a/tsconfig.json b/tsconfig.json index 3ffe7beb..908767fa 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,6 +15,6 @@ "noEmit": true, "types": ["node", "vitest/globals", "ws"] }, - "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts", "packages/wallet/src/**/*.ts", "packages/contract/src/**/*.ts", "packages/connect/src/**/*.ts", "packages/dev/src/**/*.ts"], + "include": ["src/**/*.ts", "test-support/**/*.ts", "packages/cli-core/src/**/*.ts", "packages/chain/src/**/*.ts", "packages/engine-rc/src/**/*.ts", "packages/engine-beta/src/**/*.ts", "packages/wallet/src/**/*.ts", "packages/contract/src/**/*.ts", "packages/connect/src/**/*.ts", "packages/dev/src/**/*.ts", "packages/grant/src/**/*.ts"], "exclude": ["node_modules"] } From 6726d473d0245e40d106a980b74bd8aeffcf0722 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Tue, 3 Nov 2026 22:50:11 -0800 Subject: [PATCH 74/88] mn grant through the loaded engine, stagenet included (SL, part 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each engine declares @kuiralabs/midnight-account-chain (one package for both SDK sets, its SDK as peer dependencies, as approved in Y60) and exposes it as engine.account(); grant reaches it only through the network's engine, so each engine's copy resolves to that engine's SDK set: the rc copy loads the Account build (caller pin), the beta copy the AccountStagenet build (none). The workspace lockfile nests the beta copy under engine-beta; each engine's load refuses a shared copy (MIXED_SDK_LAYOUT), and the clean-install check proves each copy resolves its own engine's ledger and runtimes. A grant request that names a caller is refused on stagenet before any transaction: CALLER_PIN_UNSUPPORTED, exit 2, declared on grant (the package's own CallerPinUnsupportedError classifies the same). Grant's network check, help and MCP enum now name stagenet. Pinned at 0.3.0-rc.1, whose stagenet build ships without its proving keys; stagenet grants complete when 0.3.0-rc.2 and its key release are out (part 2). Suite 2973, beta 193; fresh install 130 checks; scratch chain: final pass 84/84 from a fresh runner, and a grant account deployed and activated with the installed build (185d1177…1442). --- docs/JSON_CONTRACT.md | 1 + docs/SKILL-CORE.md | 2 +- docs/SKILL.md | 3 +- package-lock.json | 63 +++++++--- package.json | 2 +- packages/cli-core/api-report.md | 5 + packages/cli-core/src/engine.ts | 4 +- packages/cli-core/src/lib/engine.ts | 16 +++ packages/cli-core/src/lib/exit-codes.ts | 2 + packages/engine-beta/package.json | 1 + packages/engine-beta/src/index.ts | 25 +++- packages/engine-rc/package.json | 1 + packages/engine-rc/src/index.ts | 25 +++- packages/grant/api-report.md | 13 +- packages/grant/package.json | 1 - .../src/__tests__/account-backup.test.ts | 31 ++--- .../engine-beta-account-chain.test.ts | 112 ++++++++++++++++++ .../src/__tests__/grant-account-chain.test.ts | 73 ++++++++++++ .../grant/src/__tests__/grant-account.test.ts | 4 +- .../__tests__/grant-owner-commands.test.ts | 13 +- .../grant/src/__tests__/grant-prepare.test.ts | 18 ++- .../src/__tests__/protect-account.test.ts | 20 ++-- .../src/__tests__/sealed-account.test.ts | 7 +- packages/grant/src/commands/grant.codes.ts | 3 +- .../grant/src/commands/grant.definition.ts | 7 +- packages/grant/src/commands/grant.guidance.ts | 9 +- packages/grant/src/commands/grant.ts | 33 +++--- packages/grant/src/index.ts | 5 +- .../grant/src/lib/grant/account-backup.ts | 26 ++-- packages/grant/src/lib/grant/account-chain.ts | 39 ++++++ .../grant/src/lib/grant/account-errors.ts | 35 ++++-- packages/grant/src/lib/grant/account.ts | 69 +++++------ packages/grant/src/lib/grant/fee-wallet.ts | 7 +- .../grant/src/lib/grant/owner-commands.ts | 59 ++++----- packages/grant/src/lib/grant/prepare.ts | 25 ++-- .../grant/src/lib/grant/protect-account.ts | 41 ++++--- .../grant/src/lib/grant/sealed-account.ts | 25 ++-- scripts/check-layering.d.mts | 1 + scripts/check-layering.mjs | 23 +++- scripts/fresh-install-check.mjs | 98 +++++++++------ scripts/make-shrinkwrap.mjs | 8 +- src/__tests__/engine-beta-grant.test.ts | 60 ++++++++++ src/__tests__/exit-codes.test.ts | 8 +- src/__tests__/layering.test.ts | 11 +- test-support/grant-request-links.ts | 15 +++ 45 files changed, 785 insertions(+), 264 deletions(-) create mode 100644 packages/grant/src/__tests__/engine-beta-account-chain.test.ts create mode 100644 packages/grant/src/__tests__/grant-account-chain.test.ts create mode 100644 packages/grant/src/lib/grant/account-chain.ts create mode 100644 src/__tests__/engine-beta-grant.test.ts create mode 100644 test-support/grant-request-links.ts diff --git a/docs/JSON_CONTRACT.md b/docs/JSON_CONTRACT.md index e80b21f8..821391d6 100644 --- a/docs/JSON_CONTRACT.md +++ b/docs/JSON_CONTRACT.md @@ -116,6 +116,7 @@ Stable identifiers used in error messages and structured error objects, with the | `UNSUPPORTED_NODE` | 1 | Node.js is older than 22 (22.18 for mn grant). | | `NO_NODE_RUNTIME` | 1 | Contract scripts run under Node.js, and none was found on PATH. | | `NO_ACCOUNT` | 1 | A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network. | +| `CALLER_PIN_UNSUPPORTED` | 2 | A grant request pins the contract that calls the account, and the account on this network (stagenet) has no caller pin; nothing was submitted. | | `WRONG_PASSPHRASE` | 2 | `MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | | `PASSPHRASE_REQUIRED` | 2 | A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none). | | `BLOCKFROST_PROJECT_ID_REQUIRED` | 4 | The network (preprod) is served by Blockfrost and no project id is set. | diff --git a/docs/SKILL-CORE.md b/docs/SKILL-CORE.md index f134c3e1..2c88b977 100644 --- a/docs/SKILL-CORE.md +++ b/docs/SKILL-CORE.md @@ -28,7 +28,7 @@ You have access to the `midnight-wallet-cli` MCP server. This is the **core** sk | "Call circuit X" / "submit a score" | `midnight_contract_call({ address, circuit, args })` — two-step pending token | | "What's the contract state?" / "read the ledger" | `midnight_contract_state({ address, path })` | | "Generate tests for this contract" / "scaffold a test suite" | `midnight_test_create({ path })` (default cli; pass `strategy: "browser"` + `port` + `build-cmd` for UI tests) | -| "Does my wallet have an account?" / "show my grants" | `midnight_grant_status()` / `midnight_grant_list()` (experimental; local ledger-9 only) | +| "Does my wallet have an account?" / "show my grants" | `midnight_grant_status()` / `midnight_grant_list()` (experimental; undeployed and stagenet only) | | "Put NIGHT in my account" / "fund the account" | `midnight_grant_deposit({ amount })`, amount in NIGHT, taken from the wallet's shielded NIGHT (two-step pending token); mn can't take it back out | | "This agent sent me a grant request link" | `midnight_grant_request({ link })` first, show the user who would spend, who they could pay and the limits (defaults apply to any not given), then `midnight_grant_issue({ link })` (two-step pending token) | | "Revoke that agent's grant" / "revoke everything" | `midnight_grant_revoke({ grant })` / `midnight_grant_revoke_all()` (two-step pending token) | diff --git a/docs/SKILL.md b/docs/SKILL.md index c4af1832..68b7b78d 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -111,7 +111,7 @@ When an agent builds and proves its own ledger-9 transaction (its own value alre A wallet's account is a contract its owner deploys. A grant lets an agent spend from it within limits, on the agent's own key; the owner can revoke it at any time. The `midnight_grant_*` tools (CLI: `mn grant`) run the account owner's code from the account package mn installs (`@kuiralabs/midnight-account-chain`) in mn's own process. `midnight_grant_status`, `midnight_grant_list` and `midnight_grant_request` read the account without the wallet; the others are paid by the wallet, with no `mn serve` and no port. They are experimental: names, parameters and results can change. -What has to be true first: Node.js is 22.18 or newer, and the network is `undeployed` (a local ledger-9 stack). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. +What has to be true first: Node.js is 22.18 or newer, and the network is `undeployed` (a local ledger-9 stack) or `stagenet` (where a grant request that pins its calling contract is refused with `CALLER_PIN_UNSUPPORTED`). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. 1. `midnight_grant_status()` says whether the wallet has an account. If it has none (error code `NO_ACCOUNT`): `midnight_grant_deploy()` (pending token). Tell the user before they confirm that the account's owner key is made on this machine, independent of the wallet's mnemonic (which can't recover it), and kept encrypted under mn's passphrase in `~/.midnight/accounts///`; that they keep the account by adding a second device or writing a backup from the command line (`mn grant device`, `mn grant export`); and that a deploy takes a few minutes and about 48 DUST from the wallet, about 17 of it at once (mn waits by itself when a fee is a few minutes of Dust away; a wallet further short is told how long, and the same call carries on later from where it stopped). Running it again finishes a deploy that stopped part way. 2. A grant spends only what the account holds, which `midnight_grant_status()` shows under `held` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: `midnight_grant_deposit({ amount })`, with `amount` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, `midnight_airdrop` with `shielded: true`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. @@ -164,6 +164,7 @@ Every MCP tool error returns `{ error: true, code: , message: ` themselves. Never ask them to paste the id into the chat. Don't retry until they have. | diff --git a/package-lock.json b/package-lock.json index dff4d17d..55f12947 100644 --- a/package-lock.json +++ b/package-lock.json @@ -620,29 +620,31 @@ } }, "node_modules/@kuiralabs/midnight-account-chain": { - "version": "0.3.0-rc.0", - "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.0.tgz", - "integrity": "sha512-1lgUdlVms/oahEs6RoeHOGgJxEjsT0qJXy6ZnpZ1P/Fr4J1Q4OtipEKP0+HeynEmy419u/GlB1wenvuyiKtlhw==", + "version": "0.3.0-rc.1", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.1.tgz", + "integrity": "sha512-Xr7eVun90jzhnRl8ZnEwKRo3AliUNmgUBjFXHrS7e9hqcsjSpeVUgZbeefT0oxfsvftk2FHBMCKBG9PPMzMg2w==", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@midnight-ntwrk/compact-runtime": "0.20.0", - "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1", - "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1", - "@midnightntwrk/ledger-v9": "1.0.0-rc.5", - "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3", - "@midnightntwrk/wallet-sdk": "2.0.0-rc.0", "@scure/base": "2.0.0" }, "engines": { "compactc": "0.35.0", "node": ">=22.18" + }, + "peerDependencies": { + "@midnight-ntwrk/compact-js": "3.0.0-rc.3 || 2.5.5-rc.7", + "@midnight-ntwrk/compact-runtime": "0.20.0 || 0.18.0-rc.1", + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnightntwrk/ledger-v9": "1.0.0-rc.5 || 1.0.0-rc.3", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3" } }, "node_modules/@kuiralabs/midnight-account/node_modules/@noble/curves": { @@ -5818,6 +5820,7 @@ "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { + "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", @@ -5864,6 +5867,34 @@ "effect": "^3.21.5" } }, + "packages/engine-beta/node_modules/@kuiralabs/midnight-account-chain": { + "version": "0.3.0-rc.1", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.1.tgz", + "integrity": "sha512-Xr7eVun90jzhnRl8ZnEwKRo3AliUNmgUBjFXHrS7e9hqcsjSpeVUgZbeefT0oxfsvftk2FHBMCKBG9PPMzMg2w==", + "license": "Apache-2.0", + "dependencies": { + "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@scure/base": "2.0.0" + }, + "engines": { + "compactc": "0.35.0", + "node": ">=22.18" + }, + "peerDependencies": { + "@midnight-ntwrk/compact-js": "3.0.0-rc.3 || 2.5.5-rc.7", + "@midnight-ntwrk/compact-runtime": "0.20.0 || 0.18.0-rc.1", + "@midnight-ntwrk/midnight-js-contracts": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-http-client-proof-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-indexer-public-data-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-level-private-state-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-network-id": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-node-zk-config-provider": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-protocol": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnight-ntwrk/midnight-js-types": "5.0.0-rc.1 || 5.0.0-beta.6", + "@midnightntwrk/ledger-v9": "1.0.0-rc.5 || 1.0.0-rc.3", + "@midnightntwrk/onchain-runtime-v4": "4.0.0-rc.3" + } + }, "packages/engine-beta/node_modules/@midnight-ntwrk/compact-js": { "version": "2.5.5-rc.7", "resolved": "https://registry.npmjs.org/@midnight-ntwrk/compact-js/-/compact-js-2.5.5-rc.7.tgz", @@ -6297,6 +6328,7 @@ "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { + "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", @@ -6328,7 +6360,6 @@ "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@kuiralabs/midnight-contract": "0.1.0-rc.1", diff --git a/package.json b/package.json index 7a032e3c..22ba1041 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,7 @@ "link": "bun link", "prepublishOnly": "npm run build && npm run test", "test": "vitest run", - "test:rc": "vitest run --exclude 'src/__tests__/engine-beta*.test.ts' --exclude 'packages/engine-beta/**'", + "test:rc": "vitest run --exclude '**/src/__tests__/engine-beta*.test.ts' --exclude 'packages/engine-beta/**'", "test:beta": "vitest run src/__tests__/engine-beta packages/engine-beta", "test:live": "vitest run --config vitest.live.config.ts", "test:watch": "vitest", diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index a68e2394..82cc9dd8 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -330,6 +330,7 @@ export interface Engine { readonly contracts: EngineContracts; readonly readers: EngineReaders; readonly wallet: EngineWallet; + account(): Promise; } export interface EngineContractScripts { readonly packages: readonly string[]; @@ -510,6 +511,7 @@ export declare const ERROR_CODES: { readonly AMBIGUOUS_LOCAL_STACKS: "AMBIGUOUS_LOCAL_STACKS"; readonly UNSUPPORTED_NODE: "UNSUPPORTED_NODE"; readonly NO_ACCOUNT: "NO_ACCOUNT"; + readonly CALLER_PIN_UNSUPPORTED: "CALLER_PIN_UNSUPPORTED"; readonly BLOCKFROST_PROJECT_ID_REQUIRED: "BLOCKFROST_PROJECT_ID_REQUIRED"; readonly BLOCKFROST_PROJECT_ID_REJECTED: "BLOCKFROST_PROJECT_ID_REJECTED"; readonly BLOCKFROST_LIMIT_REACHED: "BLOCKFROST_LIMIT_REACHED"; @@ -1079,6 +1081,7 @@ export declare function payWhenDustCovers(pay: () => Promise, dust: DustBa }): Promise; export declare function planDustWait(err: unknown, dust: DustBalanceSource, now: Date): DustWaitPlan | undefined; export declare function sleep(ms: number, signal?: AbortSignal): Promise; +export type AccountEntryPoint = 'artefacts' | 'connector' | 'context' | 'contract' | 'deposit' | 'errors' | 'owner'; export type AirdropParams = Omit; export interface BlockLimits { readTime: number; @@ -1160,7 +1163,9 @@ export interface Engine { readonly contracts: EngineContracts; readonly readers: EngineReaders; readonly wallet: EngineWallet; + account(): Promise; } +export type EngineAccountPackage = Readonly>; export type EngineHost = Pick; export interface EngineWallet { unshieldedBalance(address: string, networkConfig: NetworkConfig, options?: ReadOptions): Promise; diff --git a/packages/cli-core/src/engine.ts b/packages/cli-core/src/engine.ts index b40e8687..b9741849 100644 --- a/packages/cli-core/src/engine.ts +++ b/packages/cli-core/src/engine.ts @@ -18,9 +18,9 @@ export { chooseDustCoins, type DustInput, planDustInputs, spreadFeeAcrossInputs export { DustFeeNotGeneratedError, planRegistration } from './lib/dust-registration-plan.ts'; export { awaitDustForFee, DUST_SHORT_WAIT_MS, type DustWaitPlan, payWhenDustCovers, planDustWait, sleep } from './lib/dust-wait.ts'; export { - type AirdropParams, type BlockLimits, type CachedReadOptions, type CallScript, type DAppConnector, + type AccountEntryPoint, type AirdropParams, type BlockLimits, type CachedReadOptions, type CallScript, type DAppConnector, type DAppConnectorCallbacks, type DeployScript, type DustBalance, type DustExportResult, - type DustRegisterOptions, type DustRegistration, type Engine, type EngineHost, type EngineWallet, + type DustRegisterOptions, type DustRegistration, type Engine, type EngineAccountPackage, type EngineHost, type EngineWallet, type EnsureDustResult, type OpenedConnector, type PrepWallet, type RawStateValue, type ReadOptions, type ScriptParts, type ServedWalletSession, type ShieldedBalanceResult, type ShieldedCachedOptions, type ShieldedTransferParams, type StateScript, type TransactionDetail, type TransferParams, diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index ad0c80a9..fa5a0f67 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -459,6 +459,16 @@ export interface EngineWallet { serveWallet(options: { seed: Buffer; root: string; notice: NoticeSink; networkConfig: NetworkConfig; network: NetworkName; address: string; syncMode: 'full' | 'lite' } & WalletSyncHooks, serve: (session: ServedWalletSession) => Promise): Promise; } +/** The entry points of the account package (@kuiralabs/midnight-account-chain) an engine loads, by their subpath. */ +export type AccountEntryPoint = 'artefacts' | 'connector' | 'context' | 'contract' | 'deposit' | 'errors' | 'owner'; + +/** + * The account package's entry points as an engine loaded them, each a module + * namespace. Core names none of the package's types: grant, which drives the + * package, types the modules it takes from here. + */ +export type EngineAccountPackage = Readonly>; + /** One SDK set, as mn uses it. */ export interface Engine { readonly set: SdkSet; @@ -467,6 +477,12 @@ export interface Engine { readonly contracts: EngineContracts; readonly readers: EngineReaders; readonly wallet: EngineWallet; + /** + * The account package as this engine installs it: the copy whose peer + * dependencies resolve to this engine's SDK set, so it runs the contract + * build for that set. Loaded on first ask; an engine loads without it. + */ + account(): Promise; } /** The SDK set a network runs on, as the network table and the config under the state root `root` name it. */ diff --git a/packages/cli-core/src/lib/exit-codes.ts b/packages/cli-core/src/lib/exit-codes.ts index 8e69e8df..28632950 100644 --- a/packages/cli-core/src/lib/exit-codes.ts +++ b/packages/cli-core/src/lib/exit-codes.ts @@ -52,6 +52,8 @@ export const ERROR_CODES = { UNSUPPORTED_NODE: 'UNSUPPORTED_NODE', /** `mn grant`: the wallet has no account on this network yet. Recovery: `mn grant deploy`. */ NO_ACCOUNT: 'NO_ACCOUNT', + /** `mn grant issue`: the request pins its calling contract, and the network's account build (stagenet's) has no caller pin. Recovery: a request that names no calling contract. */ + CALLER_PIN_UNSUPPORTED: 'CALLER_PIN_UNSUPPORTED', /** The network is served by Blockfrost and no project id is set. Recovery: `mn config set blockfrost-project-id `. */ BLOCKFROST_PROJECT_ID_REQUIRED: 'BLOCKFROST_PROJECT_ID_REQUIRED', /** Blockfrost refused the project id. Recovery: check it at blockfrost.io and set it again. */ diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index 44db09fd..4b0280d9 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -31,6 +31,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { + "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts index 7c57b8f9..8d33e0b2 100644 --- a/packages/engine-beta/src/index.ts +++ b/packages/engine-beta/src/index.ts @@ -21,11 +21,17 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; -// The engine's folder (above src/ or dist/), and the SDK packages it declares: -// each must reach the engine's own copy of every WASM package. +// The account package, whose Midnight libraries are peer dependencies: each +// engine declares it, and its copy in the engine's install resolves them to +// the engine's own SDK set. +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; + +// The engine's folder (above src/ or dist/), and the SDK packages it declares +// with the account package: each must reach the engine's own copy of every +// WASM package. const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) - .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name)); + .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name) || name === ACCOUNT_PACKAGE); assertOneSdkCopy("mn's beta engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); /** What an beta engine is made with besides its host. */ @@ -94,4 +100,17 @@ const SHARED: Omit = { readers: { shieldedBalance: readShieldedBalanceCached, }, + // Imported from this engine's folder, so the copy is the one its install gives it. + async account() { + const [artefacts, connector, context, contract, deposit, errors, owner] = await Promise.all([ + import('@kuiralabs/midnight-account-chain/artefacts'), + import('@kuiralabs/midnight-account-chain/connector'), + import('@kuiralabs/midnight-account-chain/context'), + import('@kuiralabs/midnight-account-chain/contract'), + import('@kuiralabs/midnight-account-chain/deposit'), + import('@kuiralabs/midnight-account-chain/errors'), + import('@kuiralabs/midnight-account-chain/owner'), + ]); + return { artefacts, connector, context, contract, deposit, errors, owner }; + }, }; diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index 29d3267a..b96cce02 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -31,6 +31,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { + "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index a271be3c..510aec25 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -20,11 +20,17 @@ import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; -// The engine's folder (above src/ or dist/), and the SDK packages it declares: -// each must reach the engine's own copy of every WASM package. +// The account package, whose Midnight libraries are peer dependencies: each +// engine declares it, and its copy in the engine's install resolves them to +// the engine's own SDK set. +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; + +// The engine's folder (above src/ or dist/), and the SDK packages it declares +// with the account package: each must reach the engine's own copy of every +// WASM package. const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) - .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name)); + .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name) || name === ACCOUNT_PACKAGE); assertOneSdkCopy("mn's rc engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); /** What an rc engine is made with besides its host. */ @@ -93,4 +99,17 @@ const SHARED: Omit = { readers: { shieldedBalance: readShieldedBalanceCached, }, + // Imported from this engine's folder, so the copy is the one its install gives it. + async account() { + const [artefacts, connector, context, contract, deposit, errors, owner] = await Promise.all([ + import('@kuiralabs/midnight-account-chain/artefacts'), + import('@kuiralabs/midnight-account-chain/connector'), + import('@kuiralabs/midnight-account-chain/context'), + import('@kuiralabs/midnight-account-chain/contract'), + import('@kuiralabs/midnight-account-chain/deposit'), + import('@kuiralabs/midnight-account-chain/errors'), + import('@kuiralabs/midnight-account-chain/owner'), + ]); + return { artefacts, connector, context, contract, deposit, errors, owner }; + }, }; diff --git a/packages/grant/api-report.md b/packages/grant/api-report.md index 60c14031..9ba6d928 100644 --- a/packages/grant/api-report.md +++ b/packages/grant/api-report.md @@ -6,6 +6,10 @@ Generated by `node scripts/api-report.mjs write` from the code: every entry poin ```ts export declare const accountProtector: WalletProtector; +export declare class CallerPinUnavailableError extends Error { + readonly code = "CALLER_PIN_UNSUPPORTED"; + constructor(network: string, caller: string); +} export declare class NoAccountError extends Error { readonly code = "NO_ACCOUNT"; constructor(walletName: string, network: string); @@ -15,7 +19,7 @@ export declare class NodeTooOldForAccountError extends Error { constructor(version: string); } export declare class UnreachableByAccountError extends UsageError { - constructor(networkId: string, sdkSet?: SdkSet); + constructor(networkId: string); } export declare function accountArtifactsDir(root: string): string; export declare function accountRecordsDir(network: string, walletName: string, root: string): string; @@ -31,6 +35,13 @@ export declare const grantCodes: readonly [ readonly order: 210; readonly summary: "A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network."; readonly recovery: "Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow)."; + }, + { + readonly code: "CALLER_PIN_UNSUPPORTED"; + readonly exitCode: 2; + readonly order: 215; + readonly summary: "A grant request pins the contract that calls the account, and the account on this network (stagenet) has no caller pin; nothing was submitted."; + readonly recovery: "Tell the user; ask the agent for a grant request that names no calling contract, or issue it on undeployed."; } ]; export declare const grantDefinition: CommandDefinition; diff --git a/packages/grant/package.json b/packages/grant/package.json index f03ab936..38e291ca 100644 --- a/packages/grant/package.json +++ b/packages/grant/package.json @@ -37,7 +37,6 @@ }, "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@kuiralabs/midnight-account-chain": "0.3.0-rc.0", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@kuiralabs/midnight-contract": "0.1.0-rc.1", diff --git a/packages/grant/src/__tests__/account-backup.test.ts b/packages/grant/src/__tests__/account-backup.test.ts index 154d8b25..52f068cc 100644 --- a/packages/grant/src/__tests__/account-backup.test.ts +++ b/packages/grant/src/__tests__/account-backup.test.ts @@ -22,12 +22,15 @@ import { parseDeviceCode } from '../lib/grant/device-code.ts'; import { createAccountKey, sealedDeviceKeys, sealedOwnerStore, sealedPrivateStatePassword } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from '../../../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; +import { accountChainOf } from '../lib/grant/account-chain.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); +// The account package's owner entry, as the rc engine installs it. +const { owner } = await accountChainOf(rcEngine); -// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. -const host = createHost({ engineLoader: loadInstalledEngine }); +// The host the tests' calls run in: nobody to ask, notices dropped, its state root under the first machine's home, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine, paths: () => ({ stateRoot: stateRootIn(here), home: here }) }); const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -66,7 +69,7 @@ beforeEach(async () => { const store = sealedOwnerStore(fromDir, key); store.writeOwner(RECORD); store.writeRoster(ROSTER); - sealedDeviceKeys(fromDir, key).keep(freshOwnerDevice('k1')); + sealedDeviceKeys(fromDir, key, owner).keep(freshOwnerDevice('k1')); sealedPrivateStatePassword(fromDir, key, rcEngine.contracts.acceptsPrivateStatePassword); await (await privateStateIn(here, fromDir)).privateState.set(PRIVATE_STATE_ID, PRIVATE_STATE as never); }); @@ -91,7 +94,7 @@ describe("an account's backup", () => { it('imports for a wallet with no account, which then acts as the same owner, its private state with it', async () => { await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); establishPassphrase(stateRootIn(there), PASSPHRASE); - expect(await importAccount(toDir, 'undeployed', PASSPHRASE, backup)).toEqual({ contractAddress: ACCOUNT }); + expect(await importAccount(toDir, 'undeployed', PASSPHRASE, backup, host.engines)).toEqual({ contractAddress: ACCOUNT }); const { account, privateState } = await privateStateIn(there, toDir); const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), host, source: source() }); expect(account.store.readOwner()).toEqual(RECORD); @@ -102,13 +105,13 @@ describe("an account's backup", () => { it('is never imported over an account, nor for another network', async () => { await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); - await expect(importAccount(fromDir, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/already has an account/); - await expect(importAccount(toDir, 'preview', PASSPHRASE, backup)).rejects.toThrow(/undeployed/); + await expect(importAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines)).rejects.toThrow(/already has an account/); + await expect(importAccount(toDir, 'preview', PASSPHRASE, backup, host.engines)).rejects.toThrow(/undeployed/); }); it('opens only with the passphrase it was made with', async () => { await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines); - await expect(importAccount(toDir, 'undeployed', 'not the passphrase it was made with', backup)).rejects.toThrow(WrongPassphraseError); + await expect(importAccount(toDir, 'undeployed', 'not the passphrase it was made with', backup, host.engines)).rejects.toThrow(WrongPassphraseError); expect(fs.existsSync(toDir)).toBe(false); }); }); @@ -117,11 +120,11 @@ describe("a backup made for another device", () => { it('leaves out this machine\'s owner key, and gives the device it was made for the records', async () => { establishPassphrase(stateRootIn(there), PASSPHRASE); fs.mkdirSync(toDir, { recursive: true }); - const pending = createPendingDevice(toDir, PASSPHRASE); + const pending = createPendingDevice(toDir, PASSPHRASE, owner); expect(pending.arm).toBe('v1'); const pendingCode = ownDeviceCode(toDir, openAccountKey(toDir, PASSPHRASE), pending); await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines, { forDevice: parseDeviceCode(pendingCode) }); - await importAccount(toDir, 'undeployed', PASSPHRASE, backup); + await importAccount(toDir, 'undeployed', PASSPHRASE, backup, host.engines); const { account, privateState } = await privateStateIn(there, toDir); const original = await openGrantAccount(NETWORK, fromDir, () => {}, { root: stateRootIn(here), host, source: source() }); expect(account.store.readOwner()).toEqual(RECORD); @@ -136,22 +139,22 @@ describe("a backup made for another device", () => { it('is refused on a machine without the device it was made for', async () => { establishPassphrase(stateRootIn(there), PASSPHRASE); fs.mkdirSync(toDir, { recursive: true }); - createPendingDevice(toDir, PASSPHRASE); + createPendingDevice(toDir, PASSPHRASE, owner); const other = path.join(root, 'other'); const otherDir = accountsOf(other); establishPassphrase(stateRootIn(other), PASSPHRASE); fs.mkdirSync(otherDir, { recursive: true }); - const stranger = createPendingDevice(otherDir, PASSPHRASE); + const stranger = createPendingDevice(otherDir, PASSPHRASE, owner); await exportAccount(fromDir, 'undeployed', PASSPHRASE, backup, host.engines, { forDevice: parseDeviceCode(ownDeviceCode(otherDir, openAccountKey(otherDir, PASSPHRASE), stranger)) }); - await expect(importAccount(toDir, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/made for another device/); + await expect(importAccount(toDir, 'undeployed', PASSPHRASE, backup, host.engines)).rejects.toThrow(/made for another device/); const empty = accountsOf(path.join(root, 'empty')); - await expect(importAccount(empty, 'undeployed', PASSPHRASE, backup)).rejects.toThrow(/device new/); + await expect(importAccount(empty, 'undeployed', PASSPHRASE, backup, host.engines)).rejects.toThrow(/device new/); }); it('keeps the pending device when made again: one key per machine', () => { establishPassphrase(stateRootIn(there), PASSPHRASE); fs.mkdirSync(toDir, { recursive: true }); - expect(createPendingDevice(toDir, PASSPHRASE).pk).toEqual(createPendingDevice(toDir, PASSPHRASE).pk); + expect(createPendingDevice(toDir, PASSPHRASE, owner).pk).toEqual(createPendingDevice(toDir, PASSPHRASE, owner).pk); }); }); diff --git a/packages/grant/src/__tests__/engine-beta-account-chain.test.ts b/packages/grant/src/__tests__/engine-beta-account-chain.test.ts new file mode 100644 index 00000000..f96fe8b6 --- /dev/null +++ b/packages/grant/src/__tests__/engine-beta-account-chain.test.ts @@ -0,0 +1,112 @@ +// Grant on stagenet reaches the account package through the beta engine: its +// own copy, nested in its folder so the package's Midnight libraries resolve +// to the beta set. That copy runs the stagenet contract build, which pins no +// caller, so an issue of a request that pins its calling contract is refused +// as it is prepared, before any wallet is opened. Nothing here reaches a +// chain. Its own process: the beta set beside nothing else (the rc engine's +// copy: grant-account-chain.test.ts). + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createHost, parseArgs } from '@kuiralabs/midnight-cli-core'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { accountChainFor } from '../lib/grant/account-chain.ts'; +import { CallerPinUnavailableError } from '../lib/grant/account-errors.ts'; +import { prepareGrant } from '../lib/grant/prepare.ts'; +import { agentLink } from '../../../../test-support/grant-request-links.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; + +const ENGINE_DIR = new URL('../../../engine-beta', import.meta.url).pathname; +const ROOT = new URL('../../../..', import.meta.url).pathname; +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; +const ENDPOINTS = ['--node', 'ws://127.0.0.1:9', '--indexer-ws', 'ws://127.0.0.1:9/api/v4/graphql/ws', '--proof-server', 'http://127.0.0.1:9']; +// An account's records as an earlier mn left them, read by the beta copy of the package. +const ACCOUNT = '5e'.repeat(32); +const OWNER_RECORD = { contractAddress: ACCOUNT, deviceArm: 'k1', deviceSk: '4f'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }; +const CALLER = new Uint8Array(32).fill(0xc4); + +let home: string; +// The host the tests' calls run in: nobody to ask, notices dropped, its state root under the test's home, and the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine, paths: () => ({ stateRoot: stateRootIn(home), home }) }); +const recordsOf = (wallet: string) => path.join(stateRootIn(home), 'accounts', 'stagenet', wallet); +const prepare = (...argv: string[]) => prepareGrant(parseArgs(['grant', ...argv, '--wallet', 'alice', '--network', 'stagenet', ...ENDPOINTS]), stateRootIn(home), host); +const withAccount = () => { + fs.mkdirSync(recordsOf('alice'), { recursive: true }); + fs.writeFileSync(path.join(recordsOf('alice'), 'owner.json'), JSON.stringify(OWNER_RECORD)); +}; +const betaCopy = () => resolvedPackageFolder(ENGINE_DIR, ACCOUNT_PACKAGE)!; + +beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-grant-chain-beta-'))); +}); +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** The folder of the package's copy a loaded build is in: its build directory is /dist/managed/. */ +const copyOf = (accountBuild: string): string => path.resolve(accountBuild, '..', '..', '..'); + +describe('the account package on stagenet', () => { + it('is the beta engine\'s own copy, as the engine loads it, not the one at the root', async () => { + const engine = await host.engines.for('stagenet'); + expect(engine.set).toBe('beta'); + const chain = await accountChainFor(host.engines, 'stagenet'); + const loaded = await engine.account(); + for (const entry of ['artefacts', 'connector', 'context', 'contract', 'deposit', 'errors', 'owner'] as const) expect(chain[entry], entry).toBe(loaded[entry]); + expect(copyOf(chain.contract.ACCOUNT_BUILD)).toBe(betaCopy()); + expect(betaCopy()).not.toBe(resolvedPackageFolder(ROOT, ACCOUNT_PACKAGE)); + }); + + it('resolves its compact runtime to the beta engine\'s, and runs the stagenet build, which pins no caller', async () => { + const engine = await host.engines.for('stagenet'); + const { contract, owner } = await accountChainFor(host.engines, 'stagenet'); + const runtime = resolvedPackageFolder(copyOf(contract.ACCOUNT_BUILD), '@midnight-ntwrk/compact-runtime')!; + expect(JSON.parse(fs.readFileSync(path.join(runtime, 'package.json'), 'utf8')).version).toBe(engine.contracts.scripts.compactRuntimeVersion); + expect(engine.contracts.scripts.compactRuntimeVersion).toBe('0.18.0-rc.1'); + expect(contract.ACCOUNT_BUILD_NAME).toBe('AccountStagenet'); + expect(path.basename(contract.ACCOUNT_BUILD)).toBe('AccountStagenet'); + expect(contract.supportsCallerPin()).toBe(false); + expect(owner.supportsCallerPin()).toBe(false); + }); +}); + +describe('preparing mn grant on stagenet', () => { + it('prepares the deploy of a new account, its records under stagenet', async () => { + fs.mkdirSync(path.join(stateRootIn(home), 'wallets'), { recursive: true }); + fs.writeFileSync(path.join(stateRootIn(home), 'wallets', 'alice.json'), '{}'); + const prepared = await prepare('deploy'); + expect(prepared.target.network).toBe('stagenet'); + expect(prepared.account).toBeNull(); + expect(prepared.recordsDir).toBe(recordsOf('alice')); + }); + + it('reads an account on record with the beta copy of the package', async () => { + withAccount(); + expect((await prepare('status')).account).toEqual({ address: ACCOUNT }); + }); + + it('refuses an issue of a request that pins its calling contract, shown or confirmed, with CALLER_PIN_UNSUPPORTED', async () => { + withAccount(); + const link = await agentLink(betaCopy(), ACCOUNT, CALLER); + for (const confirm of [[], ['--yes']]) { + const refused = prepare('issue', link, ...confirm); + await expect(refused).rejects.toThrow(CallerPinUnavailableError); + await expect(refused).rejects.toMatchObject({ code: 'CALLER_PIN_UNSUPPORTED' }); + await expect(refused).rejects.toThrow(`The grant request pins the contract that calls the account (${'c4'.repeat(32)}), and the account on stagenet can't pin a caller`); + } + }); + + it('prepares an issue of a request that names no calling contract', async () => { + withAccount(); + const link = await agentLink(betaCopy(), ACCOUNT); + expect((await prepare('issue', link, '--yes')).request).toMatchObject({ subcommand: 'issue', link, confirmed: true }); + }); + + it('refuses a link that is not a grant request as a usage error', async () => { + withAccount(); + await expect(prepare('issue', 'midnight-example:grant-request?r=AAECAw')).rejects.toMatchObject({ code: 'INVALID_ARGS' }); + }); +}); diff --git a/packages/grant/src/__tests__/grant-account-chain.test.ts b/packages/grant/src/__tests__/grant-account-chain.test.ts new file mode 100644 index 00000000..7f380df3 --- /dev/null +++ b/packages/grant/src/__tests__/grant-account-chain.test.ts @@ -0,0 +1,73 @@ +// Grant reaches the account package through the engine of the network's SDK +// set. On a local network that is the rc engine: its copy of the package, +// whose Midnight libraries resolve to the rc set, runs the release +// candidates' contract build, which pins callers, so a request that pins its +// calling contract is prepared as it always was. Nothing here reaches a chain. +// (The beta engine's copy: engine-beta-account-chain.test.ts.) + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createHost, parseArgs } from '@kuiralabs/midnight-cli-core'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { accountChainFor } from '../lib/grant/account-chain.ts'; +import { prepareGrant } from '../lib/grant/prepare.ts'; +import { agentLink } from '../../../../test-support/grant-request-links.ts'; +import { stateRootIn } from '../../../../test-support/state-root-in.ts'; +import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; + +const ENGINE_DIR = new URL('../../../engine-rc', import.meta.url).pathname; +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; +const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; +// An account's records as mn 0.6.0-rc.10 left them. +const ACCOUNT = '5e'.repeat(32); +const OWNER_RECORD = { contractAddress: ACCOUNT, deviceArm: 'k1', deviceSk: '4f'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }; + +let home: string; +// The host the tests' calls run in: nobody to ask, notices dropped, its state root under the test's home, and the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine, paths: () => ({ stateRoot: stateRootIn(home), home }) }); + +beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-grant-chain-rc-'))); +}); +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** The folder of the package's copy a loaded build is in: its build directory is /dist/managed/. */ +const copyOf = (accountBuild: string): string => path.resolve(accountBuild, '..', '..', '..'); + +describe('the account package on a local network', () => { + it('is the rc engine\'s copy, as the engine loads it', async () => { + const engine = await host.engines.for('undeployed'); + const chain = await accountChainFor(host.engines, 'undeployed'); + const loaded = await engine.account(); + for (const entry of ['artefacts', 'connector', 'context', 'contract', 'deposit', 'errors', 'owner'] as const) expect(chain[entry], entry).toBe(loaded[entry]); + expect(copyOf(chain.contract.ACCOUNT_BUILD)).toBe(resolvedPackageFolder(ENGINE_DIR, ACCOUNT_PACKAGE)); + }); + + it('resolves its compact runtime to the rc engine\'s, and runs the build with the caller pin', async () => { + const engine = await host.engines.for('undeployed'); + const { contract, owner } = await accountChainFor(host.engines, 'undeployed'); + const runtime = resolvedPackageFolder(copyOf(contract.ACCOUNT_BUILD), '@midnight-ntwrk/compact-runtime')!; + expect(JSON.parse(fs.readFileSync(path.join(runtime, 'package.json'), 'utf8')).version).toBe(engine.contracts.scripts.compactRuntimeVersion); + expect(engine.contracts.scripts.compactRuntimeVersion).toBe('0.20.0'); + expect(contract.ACCOUNT_BUILD_NAME).toBe('Account'); + expect(path.basename(contract.ACCOUNT_BUILD)).toBe('Account'); + expect(contract.supportsCallerPin()).toBe(true); + expect(owner.supportsCallerPin()).toBe(true); + }); + + it('prepares an issue of a request that pins its calling contract, shown or confirmed', async () => { + const records = path.join(stateRootIn(home), 'accounts', 'undeployed', 'alice'); + fs.mkdirSync(records, { recursive: true }); + fs.writeFileSync(path.join(records, 'owner.json'), JSON.stringify(OWNER_RECORD)); + const link = await agentLink(resolvedPackageFolder(ENGINE_DIR, ACCOUNT_PACKAGE)!, ACCOUNT, new Uint8Array(32).fill(0xc4)); + for (const confirm of [[], ['--yes']]) { + const prepared = await prepareGrant(parseArgs(['grant', 'issue', link, ...confirm, '--wallet', 'alice', ...ENDPOINTS]), stateRootIn(home), host); + expect(prepared.request).toMatchObject({ subcommand: 'issue', link, confirmed: confirm.length === 1 }); + expect(prepared.account).toEqual({ address: ACCOUNT }); + } + }); +}); diff --git a/packages/grant/src/__tests__/grant-account.test.ts b/packages/grant/src/__tests__/grant-account.test.ts index b9a97395..ec77f351 100644 --- a/packages/grant/src/__tests__/grant-account.test.ts +++ b/packages/grant/src/__tests__/grant-account.test.ts @@ -15,8 +15,8 @@ import { createAccountKey, isSealedAccount, sealedOwnerStore } from '../lib/gran import { stateRootIn } from '../../../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. -const host = createHost({ engineLoader: loadInstalledEngine }); +// The host the tests' calls run in: nobody to ask, notices dropped, its state root under the test's home, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine, paths: () => ({ stateRoot: stateRootIn(home), home }) }); const PASSPHRASE = 'correct horse battery staple'; const RECORD = { contractAddress: '5e'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }; diff --git a/packages/grant/src/__tests__/grant-owner-commands.test.ts b/packages/grant/src/__tests__/grant-owner-commands.test.ts index 18eae747..a28de60a 100644 --- a/packages/grant/src/__tests__/grant-owner-commands.test.ts +++ b/packages/grant/src/__tests__/grant-owner-commands.test.ts @@ -4,9 +4,14 @@ import { describe, expect, it } from 'vitest'; import { freshGrantee, grantRequestFor, grantRequestLink } from '@kuiralabs/midnight-account-chain/agent'; -import { UsageError } from '@kuiralabs/midnight-cli-core'; +import { UsageError, createHost } from '@kuiralabs/midnight-cli-core'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; +import { accountChainOf } from '../lib/grant/account-chain.ts'; import { DEFAULT_GRANT_LIMITS, grantRequestOf, issuePreview } from '../lib/grant/owner-commands.ts'; +// The account package as the rc engine installs it. +const chain = await accountChainOf(createRcEngine(createHost())); + const ACCOUNT = '5e'.repeat(32); const NOW = new Date('2026-10-18T12:00:00.000Z'); const MERCHANT = new Uint8Array(32).fill(0x9a); @@ -33,7 +38,7 @@ describe('a grant request link', () => { describe('what an issue would grant', () => { it("takes mn's defaults for the limits not given, and signs nothing", () => { - const { result, lines } = issuePreview(grantRequestOf(linkFor(2)), {}, NOW); + const { result, lines } = issuePreview(grantRequestOf(linkFor(2)), {}, NOW, chain); expect(result).toEqual({ confirmed: false, request: { @@ -54,12 +59,12 @@ describe('what an issue would grant', () => { }); it('takes the limits given', () => { - const { result } = issuePreview(grantRequestOf(linkFor(0)), { cap: '900', perCall: '100', maxCoin: '50', expiresIn: '60' }, NOW); + const { result } = issuePreview(grantRequestOf(linkFor(0)), { cap: '900', perCall: '100', maxCoin: '50', expiresIn: '60' }, NOW, chain); expect(result.request).toMatchObject({ payee: 'any shielded coin key', perCallCap: '100', cap: '900', maxCoinValue: '50', expires: '2026-10-18T12:01:00.000Z' }); }); it('names the calling contract a request pins, in full, and what the pin means', () => { - const { result, lines } = issuePreview(grantRequestOf(linkFor(2, new Uint8Array(32).fill(0xc4))), {}, NOW); + const { result, lines } = issuePreview(grantRequestOf(linkFor(2, new Uint8Array(32).fill(0xc4))), {}, NOW, chain); const caller = `via contract ${'c4'.repeat(32)} only: the agent spends only when that contract calls the account, and that call is public on chain`; expect(result.request).toMatchObject({ caller }); expect(lines).toContain(` caller: ${caller}`); diff --git a/packages/grant/src/__tests__/grant-prepare.test.ts b/packages/grant/src/__tests__/grant-prepare.test.ts index be448fc6..57aefae6 100644 --- a/packages/grant/src/__tests__/grant-prepare.test.ts +++ b/packages/grant/src/__tests__/grant-prepare.test.ts @@ -6,13 +6,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { parseArgs, UsageError, createHost } from '@kuiralabs/midnight-cli-core'; +import { parseArgs, UsageError } from '@kuiralabs/midnight-cli-core'; import { NoAccountError, UnreachableByAccountError } from '../lib/grant/account-errors.ts'; import { prepareGrant } from '../lib/grant/prepare.ts'; import { createAccountKey, sealedOwnerStore } from '../lib/grant/sealed-account.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped. -const host = createHost(); +// The host the tests' calls run in: nobody to ask, notices dropped, the state root under the test's home, and the engines the CLI ships. +const host = testHost(); const ENDPOINTS = ['--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; @@ -49,15 +50,10 @@ describe('prepareGrant', () => { await expect(prepare('revoke', '--wallet', 'alice')).rejects.toThrow(UsageError); }); - it('refuses a network the account package can\'t reach, creating nothing', async () => { - await expect(asAlice('status', '--network', 'preprod')).rejects.toThrow(UnreachableByAccountError); - expect(fs.existsSync(accounts())).toBe(false); - }); - - it('refuses stagenet, which runs the beta SDK set the account package has no build for, saying so', async () => { - const refusal = asAlice('status', '--network', 'stagenet'); + it('refuses a network the account package can\'t reach, saying which it reaches, creating nothing', async () => { + const refusal = asAlice('status', '--network', 'preprod'); await expect(refusal).rejects.toThrow(UnreachableByAccountError); - await expect(refusal).rejects.toThrow('mn grant runs on the rc SDK set, and StageNet runs on the beta set'); + await expect(refusal).rejects.toThrow('mn grant runs on ledger 9, which only a local network (undeployed) and stagenet run so far; PreProd is not one.'); expect(fs.existsSync(accounts())).toBe(false); }); diff --git a/packages/grant/src/__tests__/protect-account.test.ts b/packages/grant/src/__tests__/protect-account.test.ts index b272ca7f..3fb5c8bb 100644 --- a/packages/grant/src/__tests__/protect-account.test.ts +++ b/packages/grant/src/__tests__/protect-account.test.ts @@ -20,8 +20,8 @@ import { isSealedAccount } from '../lib/grant/sealed-account.ts'; import { stateRootIn } from '../../../../test-support/state-root-in.ts'; import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; -// The host the tests' calls run in: nobody to ask, notices dropped, and an engine of its own from the engines the CLI ships. -const host = createHost({ engineLoader: loadInstalledEngine }); +// The host the tests' calls run in: nobody to ask, notices dropped, its state root under the test's home, and an engine of its own from the engines the CLI ships. +const host = createHost({ engineLoader: loadInstalledEngine, paths: () => ({ stateRoot: stateRootIn(home), home }) }); const PASSPHRASE = 'correct horse battery staple'; const ACCOUNT = '5e'.repeat(32); @@ -70,7 +70,7 @@ afterEach(() => { describe('protecting an account an earlier mn made in plain text', () => { it('seals its records, roster and owner key, and leaves nothing secret in plain text', async () => { await writePlainAccount(); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('sealed-now'); + expect(await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines)).toBe('sealed-now'); expect(isSealedAccount(dir)).toBe(true); expect(plainTextLeft()).toEqual([]); const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); @@ -82,7 +82,7 @@ describe('protecting an account an earlier mn made in plain text', () => { it('moves its private state onto a password of its own, off the public one', async () => { await writePlainAccount(); - await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines); + await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines); const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); const own = await account.location.password(); expect(own).not.toBe(LEGACY_STORE_PASSWORD); @@ -92,22 +92,22 @@ describe('protecting an account an earlier mn made in plain text', () => { it('is left as it is once sealed', async () => { await writePlainAccount(); - await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('already-sealed'); + await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines); + expect(await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines)).toBe('already-sealed'); }); it('has nothing to protect where there is no account', async () => { fs.mkdirSync(dir, { recursive: true }); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('nothing'); + expect(await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines)).toBe('nothing'); }); it('is refused while caught half way, and finished by the next run', async () => { await writePlainAccount(); // A run that stopped after moving the private state, before the account was sealed. - await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines, { stopBeforeSealing: true }); + await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines, { stopBeforeSealing: true }); expect(isSealedAccount(dir)).toBe(false); await expect(openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, warn: () => {} })).rejects.toThrow(AccountMigrationInterruptedError); - expect(await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines)).toBe('sealed-now'); + expect(await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines)).toBe('sealed-now'); const account = await openGrantAccount(NETWORK, dir, () => {}, { root: stateRootIn(home), host, source: { env: { [PASSPHRASE_ENV]: PASSPHRASE } } }); expect(await (await privateStateUnder(await account.location.password())).get(PRIVATE_STATE_ID)).toEqual(PRIVATE_STATE); expect(plainTextLeft()).toEqual([]); @@ -116,7 +116,7 @@ describe('protecting an account an earlier mn made in plain text', () => { it('seals the records of a deploy that never landed, kept aside in plain text', async () => { await writePlainAccount(); fs.writeFileSync(path.join(dir, 'owner.unlanded-1790000000000.json'), JSON.stringify({ ...RECORD, deviceArm: 'k1', deviceSk: DEVICE_SECRET })); - await protectAccount(dir, PASSPHRASE, COIN_KEY, host.engines); + await protectAccount(dir, 'undeployed', PASSPHRASE, COIN_KEY, host.engines); expect(plainTextLeft()).toEqual([]); expect(fs.readdirSync(dir).some((f) => f.startsWith('owner.unlanded-1790000000000') && f.endsWith('.sealed.json'))).toBe(true); }); diff --git a/packages/grant/src/__tests__/sealed-account.test.ts b/packages/grant/src/__tests__/sealed-account.test.ts index 9429f3bd..7eb53cd4 100644 --- a/packages/grant/src/__tests__/sealed-account.test.ts +++ b/packages/grant/src/__tests__/sealed-account.test.ts @@ -25,9 +25,12 @@ import { sealedOwnerStore, sealedPrivateStatePassword, } from '../lib/grant/sealed-account.ts'; +import { accountChainOf } from '../lib/grant/account-chain.ts'; // An rc engine, for what every host's has alike: its keys, ledger and contracts. const rcEngine = createRcEngine(createHost()); +// The account package's owner entry, as the rc engine installs it. +const { owner } = await accountChainOf(rcEngine); const PASSPHRASE = 'correct horse battery staple'; const RECORD = { contractAddress: 'ab'.repeat(32), bootSalt: 'ef'.repeat(32), encryptionSecret: '12'.repeat(32) }; @@ -79,7 +82,7 @@ describe('an account sealed under its data key', () => { describe("the account's owner key", () => { it('is kept sealed, once, and read back as the same device', () => { const key = createAccountKey(dir, PASSPHRASE); - const keys = sealedDeviceKeys(dir, key); + const keys = sealedDeviceKeys(dir, key, owner); expect(keys.read()).toBeUndefined(); const device = keys.keep(freshOwnerDevice('k1')); expect(filesText()).not.toContain(device.secretText()); @@ -92,7 +95,7 @@ describe("the account's owner key", () => { it('moves aside with records of a deploy that never landed', () => { const key = createAccountKey(dir, PASSPHRASE); const store = sealedOwnerStore(dir, key); - const keys = sealedDeviceKeys(dir, key); + const keys = sealedDeviceKeys(dir, key, owner); keys.keep(freshOwnerDevice('k1')); store.writeOwner(RECORD); store.setAsideOwner(); diff --git a/packages/grant/src/commands/grant.codes.ts b/packages/grant/src/commands/grant.codes.ts index d1f6de02..cd2ff401 100644 --- a/packages/grant/src/commands/grant.codes.ts +++ b/packages/grant/src/commands/grant.codes.ts @@ -1,7 +1,8 @@ // The error codes the grant package owns. -import { defineCodes, EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core'; +import { defineCodes, EXIT_GENERAL_ERROR, EXIT_INVALID_ARGS } from '@kuiralabs/midnight-cli-core'; export const grantCodes = defineCodes([ { code: 'NO_ACCOUNT', exitCode: EXIT_GENERAL_ERROR, order: 210, summary: 'A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network.', recovery: 'Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow).' }, + { code: 'CALLER_PIN_UNSUPPORTED', exitCode: EXIT_INVALID_ARGS, order: 215, summary: 'A grant request pins the contract that calls the account, and the account on this network (stagenet) has no caller pin; nothing was submitted.', recovery: 'Tell the user; ask the agent for a grant request that names no calling contract, or issue it on undeployed.' }, ]); diff --git a/packages/grant/src/commands/grant.definition.ts b/packages/grant/src/commands/grant.definition.ts index daf2317f..95640111 100644 --- a/packages/grant/src/commands/grant.definition.ts +++ b/packages/grant/src/commands/grant.definition.ts @@ -61,9 +61,10 @@ export const grantDefinition: CommandDefinition = { name: 'network', takesValue: true, help: [ - '--network Network (default: undeployed, the only one the account package reaches)', + '--network Network (default: undeployed; the account package reaches undeployed', + ' and stagenet)', ], - agent: { type: 'string', enum: ['undeployed'], description: 'Only undeployed (a local ledger-9 stack)' }, + agent: { type: 'string', enum: ['undeployed', 'stagenet'], description: 'undeployed (a local ledger-9 stack) or stagenet' }, }, { name: 'per-call', @@ -170,7 +171,7 @@ export const grantDefinition: CommandDefinition = { intro: { brief: 'Grants that let agents spend', order: 12 }, needsWalletSdk: true, shell: { payer: true }, - errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_ACCOUNT', 'NO_PAYER'] }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_ACCOUNT', 'CALLER_PIN_UNSUPPORTED', 'NO_PAYER'] }, load: () => import('./grant.ts'), mcp: { tools: [ diff --git a/packages/grant/src/commands/grant.guidance.ts b/packages/grant/src/commands/grant.guidance.ts index d8a8beef..451ec74d 100644 --- a/packages/grant/src/commands/grant.guidance.ts +++ b/packages/grant/src/commands/grant.guidance.ts @@ -34,8 +34,9 @@ the first time a command needs them, into ~/.midnight/account-artifacts, each checked against the package's manifest: the verifier keys (under 0.1 MB) when a command first reads the account, and each circuit's proving key (up to a few hundred MB) when one first proves with it, said as it goes. -It needs Node.js 22.18 or newer and reaches only an undeployed (local) -ledger-9 network. +It needs Node.js 22.18 or newer and reaches the ledger-9 networks: an +undeployed (local) one, and stagenet, whose account can't pin the contract +that calls it (a request that names one is refused, CALLER_PIN_UNSUPPORTED). midnight grant deploy [--json] → { address, resumed, activated, network, wallet, ownerKey } @@ -129,7 +130,7 @@ Amounts are whole numbers of the token's smallest unit, as text in JSON. text: 'skill-core', section: 'intent-routing', order: 50, - body: `| "Does my wallet have an account?" / "show my grants" | \`midnight_grant_status()\` / \`midnight_grant_list()\` (experimental; local ledger-9 only) | + body: `| "Does my wallet have an account?" / "show my grants" | \`midnight_grant_status()\` / \`midnight_grant_list()\` (experimental; undeployed and stagenet only) | | "Put NIGHT in my account" / "fund the account" | \`midnight_grant_deposit({ amount })\`, amount in NIGHT, taken from the wallet's shielded NIGHT (two-step pending token); mn can't take it back out | | "This agent sent me a grant request link" | \`midnight_grant_request({ link })\` first, show the user who would spend, who they could pay and the limits (defaults apply to any not given), then \`midnight_grant_issue({ link })\` (two-step pending token) | | "Revoke that agent's grant" / "revoke everything" | \`midnight_grant_revoke({ grant })\` / \`midnight_grant_revoke_all()\` (two-step pending token) | @@ -149,7 +150,7 @@ Amounts are whole numbers of the token's smallest unit, as text in JSON. A wallet's account is a contract its owner deploys. A grant lets an agent spend from it within limits, on the agent's own key; the owner can revoke it at any time. The \`midnight_grant_*\` tools (CLI: \`mn grant\`) run the account owner's code from the account package mn installs (\`@kuiralabs/midnight-account-chain\`) in mn's own process. \`midnight_grant_status\`, \`midnight_grant_list\` and \`midnight_grant_request\` read the account without the wallet; the others are paid by the wallet, with no \`mn serve\` and no port. They are experimental: names, parameters and results can change. -What has to be true first: Node.js is 22.18 or newer, and the network is \`undeployed\` (a local ledger-9 stack). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. +What has to be true first: Node.js is 22.18 or newer, and the network is \`undeployed\` (a local ledger-9 stack) or \`stagenet\` (where a grant request that pins its calling contract is refused with \`CALLER_PIN_UNSUPPORTED\`). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. 1. \`midnight_grant_status()\` says whether the wallet has an account. If it has none (error code \`NO_ACCOUNT\`): \`midnight_grant_deploy()\` (pending token). Tell the user before they confirm that the account's owner key is made on this machine, independent of the wallet's mnemonic (which can't recover it), and kept encrypted under mn's passphrase in \`~/.midnight/accounts///\`; that they keep the account by adding a second device or writing a backup from the command line (\`mn grant device\`, \`mn grant export\`); and that a deploy takes a few minutes and about 48 DUST from the wallet, about 17 of it at once (mn waits by itself when a fee is a few minutes of Dust away; a wallet further short is told how long, and the same call carries on later from where it stopped). Running it again finishes a deploy that stopped part way. 2. A grant spends only what the account holds, which \`midnight_grant_status()\` shows under \`held\` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: \`midnight_grant_deposit({ amount })\`, with \`amount\` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, \`midnight_airdrop\` with \`shielded: true\`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. diff --git a/packages/grant/src/commands/grant.ts b/packages/grant/src/commands/grant.ts index 12ae38b4..b36a4231 100644 --- a/packages/grant/src/commands/grant.ts +++ b/packages/grant/src/commands/grant.ts @@ -4,13 +4,15 @@ import { existsSync } from 'node:fs'; // Usage: midnight grant [options] // // The account's owner code is the account package mn installs -// (@kuiralabs/midnight-account-chain), called in this process. status and list +// (@kuiralabs/midnight-account-chain), called in this process through the +// engine of the network's SDK set, which installs its copy. status and list // read the account without a wallet, and so does an issue shown but not // confirmed. The others are paid by this wallet, through its DApp connector in // this process: no server, no port. import { type ParsedArgs, hasFlag, getFlag, DustRequiredError, UsageError, type CallContext, payerFor, throwIfCancelled, withTransportCode } from '@kuiralabs/midnight-cli-core'; import { dim, header, keyValue, formatNight, type Spinner } from '@kuiralabs/midnight-cli-core/ui'; +import { accountChainFor } from '../lib/grant/account-chain.ts'; import { type GrantAccount, openGrantAccount, ownerDeviceOf } from '../lib/grant/account.ts'; import { deployShortOfDustNote } from '../lib/grant/deploy-cost.ts'; import { type OwnerCommandOutput, grantRequestOf, grantsOf, issue, issuePreview, revoke, revokeAll, statusOf } from '../lib/grant/owner-commands.ts'; @@ -62,7 +64,7 @@ export default async function grantCommand(args: ParsedArgs, ctx: CallContext): // Reading the account or a request submits nothing: a wallet with no Dust can still do it, and none is opened. const payer = paysAFee(request) ? payerFor(`grant ${request.subcommand}`, ctx) : undefined; const funds = payer ? await payer.assertCanPay(target, walletFlag, spinnerFor('Checking wallet...'), ctx.signal) : undefined; - const paying = payer ? await openPayingWallet(payer, target, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal) : undefined; + const paying = payer ? await openPayingWallet(payer, target, (await accountChainFor(ctx.host.engines, target.network)).connector, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal) : undefined; try { await runOwned(request, { target, walletName, recordsDir, account, jsonMode, paying, funds, spinnerFor }, ctx); } finally { @@ -89,7 +91,8 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const { createPendingDevice, openAccountKey, ownJoinCode } = await import('../lib/grant/sealed-account.ts'); const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('@kuiralabs/midnight-wallet'); const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(ctx.host, target.root) : await passphraseForNewSecret(ctx.host, target.root); - const device = createPendingDevice(recordsDir, passphrase); + const { owner } = await accountChainFor(ctx.host.engines, target.network); + const device = createPendingDevice(recordsDir, passphrase, owner); const code = ownJoinCode(recordsDir, openAccountKey(recordsDir, passphrase), device); spinner.stop('Device ready'); if (jsonMode) { @@ -109,7 +112,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const { unlockPassphrase, passphraseForNewSecret, isPassphraseSet } = await import('@kuiralabs/midnight-wallet'); try { const passphrase = isPassphraseSet(target.root) ? await unlockPassphrase(ctx.host, target.root) : await passphraseForNewSecret(ctx.host, target.root); - const { contractAddress } = await importAccount(recordsDir, target.network, passphrase, request.file); + const { contractAddress } = await importAccount(recordsDir, target.network, passphrase, request.file, ctx.host.engines); spinner.stop('Imported'); if (jsonMode) ctx.output.result({ subcommand: request.subcommand, network: target.network, wallet: walletName, ownerKey: 'sealed', address: contractAddress }); else ctx.output.stderr('\n' + keyValue('Account', contractAddress) + '\n' + dim(' Use it from one machine at a time: this machine now acts as the same owner device.') + '\n\n'); @@ -137,7 +140,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, }; // The owner's session, paid by the wallet. const ownerSession = async () => { - const { connectOver, openSessionOver } = await import('@kuiralabs/midnight-account-chain/owner'); + const { connectOver, openSessionOver } = owned.chain.owner; if (account === null) throw new Error('An owner command was prepared without an account'); const { feeWallet } = await payingWallet(); // A sealed account's device reads the owner-device mailbox: it catches up on another device's rotation, and is listed for later ones. @@ -157,7 +160,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, throwIfCancelled(ctx.signal); switch (request.subcommand) { case 'deploy': { - const { deployOwnerAccount, freshOwnerDevice } = await import('@kuiralabs/midnight-account-chain/owner'); + const { deployOwnerAccount, freshOwnerDevice } = owned.chain.owner; const { feeWallet } = await payingWallet(); // The device the records hold, or for a new account a key made here, on the k1 arm and // independent of any other (MIP-0013), kept sealed before the deploy is submitted. @@ -177,7 +180,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, return; } case 'deposit': { - const { connectOver, depositShielded } = await import('@kuiralabs/midnight-account-chain/deposit'); + const { connectOver, depositShielded } = owned.chain.deposit; if (account === null) throw new Error('A deposit was prepared without an account'); const wallet = await payingWallet(); const value = BigInt(request.value); @@ -200,27 +203,27 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, } case 'status': case 'list': { - const { readOwnerView } = await import('@kuiralabs/midnight-account-chain/owner'); + const { readOwnerView } = owned.chain.owner; const device = ownerDeviceOf(owned); const view = await readOwnerView(owned.context.network, owned.store, device); const code = owned.ownCode?.() ?? 'none until the account is protected (midnight wallet protect)'; - report(request.subcommand === 'status' ? statusOf(view, device.arm, code) : grantsOf(view, owned.context.clock())); + report(request.subcommand === 'status' ? statusOf(view, device.arm, code) : grantsOf(view, owned.context.clock(), owned.chain)); return; } case 'issue': { const grantRequest = grantRequestOf(request.link); if (!request.confirmed) { - report(issuePreview(grantRequest, request.limits, owned.context.clock())); + report(issuePreview(grantRequest, request.limits, owned.context.clock(), owned.chain)); return; } - report(await issue(await ownerSession(), grantRequest, request.limits, owned.context.clock())); + report(await issue(await ownerSession(), grantRequest, request.limits, owned.context.clock(), owned.chain)); return; } case 'revoke': - report(await revoke(await ownerSession(), request.target)); + report(await revoke(await ownerSession(), request.target, owned.chain)); return; case 'revoke-all': - report(await revokeAll(await ownerSession())); + report(await revokeAll(await ownerSession(), owned.chain)); return; case 'device': { if (owned.protection !== 'sealed') throw new UsageError('The account is not protected: its devices are managed once it is. Encrypt it first: midnight wallet protect'); @@ -239,7 +242,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, } const named = parseDeviceCode(request.code); if (request.action === 'add') { - const { addOwnerDevice } = await import('@kuiralabs/midnight-account-chain/owner'); + const { addOwnerDevice } = owned.chain.owner; const { exportAccount } = await import('../lib/grant/account-backup.ts'); if (named.arm !== 'v1') throw new UsageError('The account adds JubJub devices only (a v1 device code, as midnight grant device new makes).'); if (named.attestation === undefined) { @@ -262,7 +265,7 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, } return; } - const { removeOwnerDevice } = await import('@kuiralabs/midnight-account-chain/owner'); + const { removeOwnerDevice } = owned.chain.owner; const removing = identityCodeOf(request.code); if (removing === own) throw new UsageError('A device does not remove itself: remove this one from another device on the account.'); const { removed } = await removeOwnerDevice(await ownerSession(), deviceKeyOf(named), named.readKey); diff --git a/packages/grant/src/index.ts b/packages/grant/src/index.ts index afaad8d7..73cc2b5d 100644 --- a/packages/grant/src/index.ts +++ b/packages/grant/src/index.ts @@ -2,12 +2,13 @@ // the MCP server. The protector `wallet protect` runs to seal the accounts an // earlier mn kept in plain text; the errors a caller classifies grant's // refusals by (a network the account package can't act on, a Node.js too old -// for it, a wallet with no account); and where a state root keeps the +// for it, a wallet with no account, a caller pin the network's account can't +// hold); and where a state root keeps the // accounts' records and the account package's proving artefacts. None of them // loads the account package or its SDK set: the shell loads this entry point // for every wallet command. Each name is listed, so the API is what this file // says. The grant command, its codes and guidance are "./commands". export { accountProtector } from './lib/grant/account-protector.ts'; -export { NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from './lib/grant/account-errors.ts'; +export { CallerPinUnavailableError, NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from './lib/grant/account-errors.ts'; export { accountArtifactsDir, accountRecordsDir } from './lib/grant/account-records.ts'; diff --git a/packages/grant/src/lib/grant/account-backup.ts b/packages/grant/src/lib/grant/account-backup.ts index 7cae8d38..84b6f4dd 100644 --- a/packages/grant/src/lib/grant/account-backup.ts +++ b/packages/grant/src/lib/grant/account-backup.ts @@ -10,10 +10,11 @@ // a second device (`midnight grant device add`). import * as fs from 'node:fs'; -import { type HostEngines, UsageError, FileExistsError, writeJsonDurably, type SealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core'; +import { type HostEngines, type NetworkName, UsageError, FileExistsError, writeJsonDurably, type SealedSecret, openSecret, sealSecret } from '@kuiralabs/midnight-cli-core'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; -import { type OwnerRecord, type Roster, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; +import type { OwnerRecord, Roster } from '@kuiralabs/midnight-account-chain/owner'; +import { accountChainOf } from './account-chain.ts'; import { privateStateLocationOf } from './account.ts'; import { type DeviceIdentity, deviceCodeOf } from './device-code.ts'; import { @@ -81,13 +82,15 @@ const sealedAccountIn = (dir: string, passphrase: string) => { * Writes the account in `dir` on `network` to `file`, sealed under * `passphrase`. Never over a file that exists. With `forDevice`, the backup * is for that device, just added to the account: it carries everything but - * this machine's owner key. Its private-state password is read under the - * policy of an engine of `engines`. + * this machine's owner key. Its owner key is read, and its private-state + * password under the policy of, the network's engine among `engines`. */ -export async function exportAccount(dir: string, network: string, passphrase: string, file: string, engines: HostEngines, { forDevice }: { forDevice?: DeviceIdentity } = {}): Promise<{ contractAddress: string; file: string }> { +export async function exportAccount(dir: string, network: NetworkName, passphrase: string, file: string, engines: HostEngines, { forDevice }: { forDevice?: DeviceIdentity } = {}): Promise<{ contractAddress: string; file: string }> { const key = sealedAccountIn(dir, passphrase); + const engine = await engines.for(network); + const { owner } = await accountChainOf(engine); const record = sealedOwnerStore(dir, key).readOwner(); - const device = sealedDeviceKeys(dir, key).read(); + const device = sealedDeviceKeys(dir, key, owner).read(); if (record === undefined || device === undefined) throw new UsageError(`The account in ${dir} has not been deployed yet: there is nothing to back up.`); const database = privateStateLocationOf(dir, () => '').database; const bundle: AccountBundle = { @@ -95,7 +98,7 @@ export async function exportAccount(dir: string, network: string, passphrase: st roster: sealedOwnerStore(dir, key).readRoster(), ...(forDevice === undefined ? { device: { arm: device.arm, secret: device.secretText(), readSecret: Buffer.from(sealedDeviceReadSecret(dir, key)).toString('hex') } } : {}), devices: [...new Set([...knownDevices(dir, key, device), ...(forDevice === undefined ? [] : [deviceCodeOf(forDevice, forDevice.readKey)])])], - privateStatePassword: sealedPrivateStatePassword(dir, key, (await engines.any()).contracts.acceptsPrivateStatePassword), + privateStatePassword: sealedPrivateStatePassword(dir, key, engine.contracts.acceptsPrivateStatePassword), privateState: fs.existsSync(database) ? Object.fromEntries(filesUnder(database).map((f) => [f, fs.readFileSync(path.join(database, f)).toString('base64')])) : {}, }; const backup: AccountBackupFile = { @@ -115,21 +118,22 @@ export async function exportAccount(dir: string, network: string, passphrase: st return { contractAddress: record.contractAddress, file: resolved }; } -/** Imports the backup in `file` as the account in `dir` on `network`, which must have none, sealed under `passphrase`. */ -export async function importAccount(dir: string, network: string, passphrase: string, file: string): Promise<{ contractAddress: string }> { +/** Imports the backup in `file` as the account in `dir` on `network`, which must have none, sealed under `passphrase`; its owner key made by the network's engine among `engines`. */ +export async function importAccount(dir: string, network: NetworkName, passphrase: string, file: string, engines: HostEngines): Promise<{ contractAddress: string }> { const backup = JSON.parse(fs.readFileSync(path.resolve(file), 'utf8')) as Partial; if (backup.kind !== BACKUP_KIND || backup.v !== BACKUP_VERSION) throw new UsageError(`${file} is not an account backup mn can read.`); if (backup.network !== network) throw new UsageError(`${file} is a backup of an account on ${backup.network}, not on ${network}.`); // Opened before anything is written, so a wrong passphrase leaves nothing behind. const bundle = JSON.parse(openSecret(backup.sealed, passphrase, 'account-backup').toString('utf8')) as AccountBundle; const database = privateStateLocationOf(dir, () => '').database; + const { owner } = await accountChainOf(await engines.for(network)); let key: Buffer; if (bundle.device === undefined) { // Made for another device: this machine's pending device must be the one it names. if (!isPendingDevice(dir)) throw new UsageError(`${file} was made for another device to join the account. Make this machine's device first, with: midnight grant device new`); key = openAccountKey(dir, passphrase); - const pending = sealedDeviceKeys(dir, key).read(); + const pending = sealedDeviceKeys(dir, key, owner).read(); const pendingCode = pending === undefined ? undefined : ownDeviceCode(dir, key, pending); if (pendingCode === undefined || !bundle.devices.includes(pendingCode)) { throw new UsageError(`${file} was made for another device, not this machine's (${pendingCode ?? 'none'}).`); @@ -139,7 +143,7 @@ export async function importAccount(dir: string, network: string, passphrase: st const hasAccount = isSealedAccount(dir) || isAccountMigrating(dir) || fs.existsSync(path.join(dir, 'owner.json')) || fs.existsSync(database); if (hasAccount) throw new UsageError(`The wallet already has an account in ${dir}; a backup is never imported over one.`); key = createAccountKey(dir, passphrase); - sealedDeviceKeys(dir, key).keep(ownerDeviceFromSecret(bundle.device.arm, bundle.device.secret)); + sealedDeviceKeys(dir, key, owner).keep(owner.ownerDeviceFromSecret(bundle.device.arm, bundle.device.secret)); keepDeviceReadSecret(dir, key, new Uint8Array(Buffer.from(bundle.device.readSecret, 'hex'))); } const store = sealedOwnerStore(dir, key); diff --git a/packages/grant/src/lib/grant/account-chain.ts b/packages/grant/src/lib/grant/account-chain.ts new file mode 100644 index 00000000..83e15403 --- /dev/null +++ b/packages/grant/src/lib/grant/account-chain.ts @@ -0,0 +1,39 @@ +// The account package (@kuiralabs/midnight-account-chain) as grant reaches +// it: through the engine of the network's SDK set, which installs the copy +// whose Midnight libraries are that set's. That copy runs the contract build +// for the set: the release candidates' (with the caller pin) on a local +// network, the stagenet build (without it) on stagenet. Grant never imports +// the package's code itself, only its types here: a copy it imported would +// resolve the package's libraries from grant's own folder, whatever the +// network's set. + +import type * as Artefacts from '@kuiralabs/midnight-account-chain/artefacts'; +import type * as Connector from '@kuiralabs/midnight-account-chain/connector'; +import type * as Context from '@kuiralabs/midnight-account-chain/context'; +import type * as Contract from '@kuiralabs/midnight-account-chain/contract'; +import type * as Deposit from '@kuiralabs/midnight-account-chain/deposit'; +import type * as Errors from '@kuiralabs/midnight-account-chain/errors'; +import type * as Owner from '@kuiralabs/midnight-account-chain/owner'; +import type { Engine, HostEngines, NetworkName } from '@kuiralabs/midnight-cli-core'; + +/** The account package's entry points grant uses, as one engine loaded them. */ +export interface AccountChain { + readonly artefacts: typeof Artefacts; + readonly connector: typeof Connector; + readonly context: typeof Context; + readonly contract: typeof Contract; + readonly deposit: typeof Deposit; + readonly errors: typeof Errors; + readonly owner: typeof Owner; +} + +/** The account package as `engine` installs it. */ +export async function accountChainOf(engine: Engine): Promise { + // Core leaves the modules untyped (it names none of the package's types); they are these entry points. + return (await engine.account()) as AccountChain; +} + +/** The account package as the engine for `network`'s SDK set installs it. */ +export async function accountChainFor(engines: HostEngines, network: NetworkName): Promise { + return accountChainOf(await engines.for(network)); +} diff --git a/packages/grant/src/lib/grant/account-errors.ts b/packages/grant/src/lib/grant/account-errors.ts index d56d2861..49f37e12 100644 --- a/packages/grant/src/lib/grant/account-errors.ts +++ b/packages/grant/src/lib/grant/account-errors.ts @@ -1,23 +1,40 @@ // The errors mn grant refuses with before it reaches the account package: a // network the package can't act on, a Node.js older than it needs, a wallet -// with no account yet. They import no account package, so a caller (the -// shell, the MCP server, a program classifying a failure) has them without -// loading the account chain and the SDK set it is built on. +// with no account yet, a grant request the network's account build can't +// hold. They import no account package, so a caller (the shell, the MCP +// server, a program classifying a failure) has them without loading the +// account chain and the SDK set it is built on. -import { UsageError, type SdkSet } from '@kuiralabs/midnight-cli-core'; +import { UsageError } from '@kuiralabs/midnight-cli-core'; /** A network the account package can't reach yet. */ export class UnreachableByAccountError extends UsageError { - constructor(networkId: string, sdkSet: SdkSet = 'rc') { - super(sdkSet === 'rc' - ? `mn grant runs on ledger 9, which only a local network (undeployed) runs so far; ${networkId} is not one.` - // The account package is built on the rc set: its contracts, proving files and providers. - : `mn grant runs on the rc SDK set, and ${networkId} runs on the ${sdkSet} set. The account package has no ${sdkSet} build yet (its contracts need recompiling and new proving files), so grant can't act on it for now.`); + constructor(networkId: string) { + super(`mn grant runs on ledger 9, which only a local network (undeployed) and stagenet run so far; ${networkId} is not one.`); this.name = 'UnreachableByAccountError'; Object.setPrototypeOf(this, UnreachableByAccountError.prototype); } } +/** + * A grant request that pins the contract calling the account, on a network + * whose account build has no caller pin: stagenet's toolchain (compactc 0.33) + * has no way for a contract to read its caller, so the account there can't + * hold a grant to one. + */ +export class CallerPinUnavailableError extends Error { + readonly code = 'CALLER_PIN_UNSUPPORTED'; + + constructor(network: string, caller: string) { + super( + `The grant request pins the contract that calls the account (${caller}), and the account on ${network} can't pin a caller: its build there has no caller check. ` + + 'Ask the agent for a request that names no calling contract, or issue this one on a network whose account pins callers (undeployed).', + ); + this.name = 'CallerPinUnavailableError'; + Object.setPrototypeOf(this, CallerPinUnavailableError.prototype); + } +} + /** The Node.js the account package needs: it declares 22.18 or newer. */ export const MIN_NODE_FOR_ACCOUNT = '22.18.0'; diff --git a/packages/grant/src/lib/grant/account.ts b/packages/grant/src/lib/grant/account.ts index b015c075..1c981cb9 100644 --- a/packages/grant/src/lib/grant/account.ts +++ b/packages/grant/src/lib/grant/account.ts @@ -1,7 +1,8 @@ // What `mn grant` gives the account package (@kuiralabs/midnight-account-chain), -// which it calls in its own process: the network it acts on, where the proving -// keys are cached, its progress, and the account's records, device key and -// private state, all in the account's records directory. +// which it calls in its own process through the engine of the network's SDK +// set: the network it acts on, where the proving keys are cached, its +// progress, and the account's records, device key and private state, all in +// the account's records directory. // // The records are where every account so far keeps them, so an account made by // an earlier mn opens unchanged: owner.json (the account's records and its @@ -9,16 +10,8 @@ // midnight-level-db under the store name and password it was first made with. import { join } from 'node:path'; -import { artefactCache } from '@kuiralabs/midnight-account-chain/artefacts'; -import { type AccountContext, type ProgressEvent, accountContext, describeProgress, networkOf } from '@kuiralabs/midnight-account-chain/context'; -import { - type DirectoryDeviceKeys, - type OwnerDevice, - type OwnerStore, - type PrivateStateLocation, - directoryDeviceKeys, - directoryOwnerStore, -} from '@kuiralabs/midnight-account-chain/owner'; +import type { AccountContext, ProgressEvent } from '@kuiralabs/midnight-account-chain/context'; +import type { DirectoryDeviceKeys, OwnerDevice, OwnerStore, PrivateStateLocation } from '@kuiralabs/midnight-account-chain/owner'; import { PRIVATE_STATE_DATABASE } from '@kuiralabs/midnight-contract'; import { type PassphraseSource, passphraseForNewSecret, unlockPassphrase, type UnlockHost } from '@kuiralabs/midnight-wallet'; import { @@ -34,12 +27,17 @@ import { sealedOwnerStore, sealedPrivateStatePassword, } from './sealed-account.ts'; -import { isValidNetworkName, sdkSetOfNetwork, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import type { NetworkConfig, NetworkName } from '@kuiralabs/midnight-cli-core'; +import { type AccountChain, accountChainOf } from './account-chain.ts'; import { MIN_NODE_FOR_ACCOUNT, NodeTooOldForAccountError, UnreachableByAccountError } from './account-errors.ts'; import { accountArtifactsDir } from './account-records.ts'; -/** The network the account package acts on: ledger 9, which only a local network runs so far. */ -const ACCOUNT_NETWORK_ID = 'undeployed'; +/** + * The networks the account package acts on, by the network id midnight-js + * keeps (mn's own, lower-cased): ledger 9's, a local network on the release + * candidates' set and stagenet on its beta set. + */ +const ACCOUNT_NETWORKS: readonly NetworkName[] = ['undeployed', 'stagenet']; /** The private state's database, store and password, as every account so far was made with them. */ const PRIVATE_STATE_STORE = 'midnight-bench-account'; @@ -56,12 +54,11 @@ export function privateStateLocationOf(recordsDir: string, password: () => strin return { database: join(recordsDir, PRIVATE_STATE_DATABASE), store: PRIVATE_STATE_STORE, password }; } -/** Throws when the account package can't act on `networkConfig`'s network, by the SDK set the config under the state root `root` gives it. */ -export function assertAccountNetwork(networkConfig: NetworkConfig, root: string): void { - const id = networkConfig.networkId.toLowerCase(); - const sdkSet = isValidNetworkName(id) ? sdkSetOfNetwork(id, root) : 'rc'; - if (sdkSet !== 'rc') throw new UnreachableByAccountError(networkConfig.networkId, sdkSet); - if (networkConfig.networkId.toLowerCase() !== ACCOUNT_NETWORK_ID) throw new UnreachableByAccountError(networkConfig.networkId); +/** The network the account package acts on for `networkConfig`; throws when it can't act on it. */ +export function assertAccountNetwork(networkConfig: NetworkConfig): NetworkName { + const network = ACCOUNT_NETWORKS.find((name) => name === networkConfig.networkId.toLowerCase()); + if (network === undefined) throw new UnreachableByAccountError(networkConfig.networkId); + return network; } /** Throws when this Node.js is older than the account package needs. */ @@ -80,6 +77,8 @@ export type AccountProtection = 'sealed' | 'plain-text'; /** Everything the account package needs to act on one wallet's account. */ export interface GrantAccount { + /** The account package, as the engine of the network's SDK set installs it. */ + chain: AccountChain; context: AccountContext; store: OwnerStore; keys: DirectoryDeviceKeys | SealedDeviceKeys; @@ -95,7 +94,7 @@ export interface GrantAccount { export interface OpenAccountOptions { /** The state root holding mn's passphrase check and the proving artefacts. */ root: string; - /** The host: who is asked for the passphrase, the passphrase it has unlocked, its notices, and its engines (whose policy the private-state password meets). */ + /** The host: who is asked for the passphrase, the passphrase it has unlocked, its notices, and its engines (the network's installs the account package, and its policy is the one the private-state password meets). */ host: UnlockHost; source?: PassphraseSource; warn?: (line: string) => void; @@ -109,23 +108,27 @@ export interface OpenAccountOptions { */ export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: string, say: (line: string) => void, options: OpenAccountOptions): Promise { const { root } = options; - assertAccountNetwork(networkConfig, root); - const progress = (event: ProgressEvent): void => say(describeProgress(event).trim()); - const network = networkOf({ networkId: ACCOUNT_NETWORK_ID, node: httpOf(networkConfig.node), indexer: networkConfig.indexer, proofServer: networkConfig.proofServer }); - const context = accountContext({ network, artefacts: artefactCache(accountArtifactsDir(root), { progress }), progress }); + const networkId = assertAccountNetwork(networkConfig); + const engine = await options.host.engines.for(networkId); + const chain = await accountChainOf(engine); + const { artefacts, context: contexts, owner } = chain; + const progress = (event: ProgressEvent): void => say(contexts.describeProgress(event).trim()); + const network = contexts.networkOf({ networkId, node: httpOf(networkConfig.node), indexer: networkConfig.indexer, proofServer: networkConfig.proofServer }); + const context = contexts.accountContext({ network, artefacts: artefacts.artefactCache(accountArtifactsDir(root), { progress }), progress }); const database = join(recordsDir, PRIVATE_STATE_DATABASE); // The account's private state is midnight-js's, which the engine's policy checks a new password against. - const { contracts } = await options.host.engines.any(); + const { contracts } = engine; const sealed = (key: Buffer): GrantAccount => ({ + chain, context, store: sealedOwnerStore(recordsDir, key), - keys: sealedDeviceKeys(recordsDir, key), + keys: sealedDeviceKeys(recordsDir, key, owner), location: { database, store: PRIVATE_STATE_STORE, password: () => sealedPrivateStatePassword(recordsDir, key, contracts.acceptsPrivateStatePassword) }, protection: 'sealed', deviceReadSecret: () => sealedDeviceReadSecret(recordsDir, key), ownCode: () => { - const device = sealedDeviceKeys(recordsDir, key).read(); + const device = sealedDeviceKeys(recordsDir, key, owner).read(); if (device === undefined) throw new Error('The account\'s records hold no owner key.'); return ownDeviceCode(recordsDir, key, device); }, @@ -134,13 +137,13 @@ export async function openGrantAccount(networkConfig: NetworkConfig, recordsDir: // Caught half way through being sealed: its private state may be under its new password already. if (isAccountMigrating(recordsDir)) throw new AccountMigrationInterruptedError(recordsDir); - const plainStore = directoryOwnerStore(recordsDir); - const plainKeys = directoryDeviceKeys(recordsDir); + const plainStore = owner.directoryOwnerStore(recordsDir); + const plainKeys = owner.directoryDeviceKeys(recordsDir); if (plainStore.readOwner() !== undefined || plainKeys.read() !== undefined) { const warning = `Warning: the account in ${recordsDir} is not protected: its owner key and records are in plain text. Encrypt them with: midnight wallet protect`; if (options.warn !== undefined) options.warn(warning); else options.host.notice(warning); - return { context, store: plainStore, keys: plainKeys, location: { database, store: PRIVATE_STATE_STORE, password: () => LEGACY_STORE_PASSWORD }, protection: 'plain-text' }; + return { chain, context, store: plainStore, keys: plainKeys, location: { database, store: PRIVATE_STATE_STORE, password: () => LEGACY_STORE_PASSWORD }, protection: 'plain-text' }; } return sealed(createAccountKey(recordsDir, await passphraseForNewSecret(options.host, root, options.source))); } diff --git a/packages/grant/src/lib/grant/fee-wallet.ts b/packages/grant/src/lib/grant/fee-wallet.ts index 10fc45b8..4f4172a8 100644 --- a/packages/grant/src/lib/grant/fee-wallet.ts +++ b/packages/grant/src/lib/grant/fee-wallet.ts @@ -2,6 +2,7 @@ // process, made into the account package's fee wallet. import type { FeeWallet } from '@kuiralabs/midnight-account-chain/owner'; +import type { AccountChain } from './account-chain.ts'; import { NATIVE_TOKEN_TYPE, type Payer, type PayingTarget, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; @@ -13,9 +14,9 @@ export interface PayingWallet { stop: () => Promise; } -/** The payer's wallet for `target`, as the account package's fee wallet, keeping the SDK's warnings to the paying call's `sdkWarnings`. Stopping it stops the wallet. */ -export async function openPayingWallet(payer: Payer, target: PayingTarget, wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { - const { feeWalletOver } = await import('@kuiralabs/midnight-account-chain/connector'); +/** The payer's wallet for `target`, as the fee wallet of the account package's `connector` (the network engine's), keeping the SDK's warnings to the paying call's `sdkWarnings`. Stopping it stops the wallet. */ +export async function openPayingWallet(payer: Payer, target: PayingTarget, connector: AccountChain['connector'], wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { + const { feeWalletOver } = connector; const session = await payer.connect(target, wallet, progress, sdkWarnings, signal); try { const feeWallet = await feeWalletOver({ diff --git a/packages/grant/src/lib/grant/owner-commands.ts b/packages/grant/src/lib/grant/owner-commands.ts index 2a7a9944..b8c783ae 100644 --- a/packages/grant/src/lib/grant/owner-commands.ts +++ b/packages/grant/src/lib/grant/owner-commands.ts @@ -8,20 +8,11 @@ // whose fees the wallet pays. import { randomBytes } from 'node:crypto'; -import { NIGHT } from '@kuiralabs/midnight-account-chain/contract'; -import { - type GrantRequest, - type OwnerView, - type Session, - exhaustedGrants, - grantRequestFromLink, - issueReadGrant, - revokeEveryGrant, - revokeReadGrant, - sealedResponseLink, - termsFor, -} from '@kuiralabs/midnight-account-chain/owner'; +import { type GrantRequest, grantRequestFromLink, sealedResponseLink } from '@kuiralabs/midnight-account'; +import type { OwnerView, Session } from '@kuiralabs/midnight-account-chain/owner'; import { UsageError } from '@kuiralabs/midnight-cli-core'; +import type { AccountChain } from './account-chain.ts'; +import { CallerPinUnavailableError } from './account-errors.ts'; import type { GrantLimits as RequestedLimits } from './request.ts'; /** What a command gives: its result, and the lines a person reads. */ @@ -70,9 +61,9 @@ export function statusOf(view: OwnerView, arm: string, code: string): OwnerComma }; } -export function grantsOf(view: OwnerView, now: Date): OwnerCommandOutput { +export function grantsOf(view: OwnerView, now: Date, chain: AccountChain): OwnerCommandOutput { const { ledger, roster } = view; - const exhausted = new Set(exhaustedGrants(ledger, roster, now).map((entry) => entry.grantId)); + const exhausted = new Set(chain.owner.exhaustedGrants(ledger, roster, now).map((entry) => entry.grantId)); const listed = new Map(roster.entries.map((entry) => [entry.grantId, entry] as const)); const nowSeconds = secondsOf(now); const rows = [...ledger.grants].map(([id, record]) => { @@ -112,10 +103,22 @@ export function grantRequestOf(link: string): GrantRequest { } } +/** + * Refuses the request in `link` when it pins the contract that calls the + * account and `chain`'s build (the network's) has no caller pin: before any + * wallet is opened. Where the build pins callers, the link is left to be read + * where it always is. + */ +export async function assertCallerPinnable(link: string, network: string, chain: AccountChain): Promise { + if (chain.contract.supportsCallerPin()) return; + const { caller } = grantRequestOf(link); + if (caller !== undefined) throw new CallerPinUnavailableError(network, hexOf(caller)); +} + /** The limits an issue sets: those given, mn's defaults for the rest. */ -function limitsOf(requested: RequestedLimits) { +function limitsOf(requested: RequestedLimits, chain: AccountChain) { return { - color: NIGHT, + color: chain.contract.NIGHT, perCallCap: requested.perCall === undefined ? DEFAULT_GRANT_LIMITS.perCallCap : BigInt(requested.perCall), cap: requested.cap === undefined ? DEFAULT_GRANT_LIMITS.cap : BigInt(requested.cap), maxCoinValue: requested.maxCoin === undefined ? DEFAULT_GRANT_LIMITS.maxCoinValue : BigInt(requested.maxCoin), @@ -133,8 +136,8 @@ function callerTerm(caller: Uint8Array | undefined): string { } /** What an issue would grant, before anything is signed: the terms a person confirms. */ -export function issueTerms(request: GrantRequest, requested: RequestedLimits, now: Date) { - const terms = termsFor(request, limitsOf(requested), now); +export function issueTerms(request: GrantRequest, requested: RequestedLimits, now: Date, chain: AccountChain) { + const terms = chain.owner.termsFor(request, limitsOf(requested, chain), now); const asked = { account: request.account, clientId: request.clientId, @@ -150,14 +153,14 @@ export function issueTerms(request: GrantRequest, requested: RequestedLimits, no return { terms, asked, askedLines: Object.entries(asked).map(([name, value]) => ` ${name}: ${value}`) }; } -export function issuePreview(request: GrantRequest, requested: RequestedLimits, now: Date): OwnerCommandOutput { - const { asked, askedLines } = issueTerms(request, requested, now); +export function issuePreview(request: GrantRequest, requested: RequestedLimits, now: Date, chain: AccountChain): OwnerCommandOutput { + const { asked, askedLines } = issueTerms(request, requested, now, chain); return { result: { confirmed: false, request: asked }, lines: ['the request asks for:', ...askedLines, 're-run with --yes to issue it'] }; } -export async function issue(session: Session, request: GrantRequest, requested: RequestedLimits, now: Date): Promise { - const { terms, asked } = issueTerms(request, requested, now); - const issued = await issueReadGrant(session, request, terms, new Uint8Array(randomBytes(32))); +export async function issue(session: Session, request: GrantRequest, requested: RequestedLimits, now: Date, chain: AccountChain): Promise { + const { terms, asked } = issueTerms(request, requested, now, chain); + const issued = await chain.owner.issueReadGrant(session, request, terms, new Uint8Array(randomBytes(32))); const fallbackLink = sealedResponseLink(issued); // A grant an interrupted run had issued keeps that run's terms: say those, not the ones asked for now. const granted = issued.resumed @@ -175,8 +178,8 @@ export async function issue(session: Session, request: GrantRequest, requested: }; } -export async function revoke(session: Session, target: string): Promise { - const { revoked, alreadyRevoked } = await revokeReadGrant(session, target); +export async function revoke(session: Session, target: string, chain: AccountChain): Promise { + const { revoked, alreadyRevoked } = await chain.owner.revokeReadGrant(session, target); const [grantId] = revoked; if (grantId !== undefined) return { result: { revoked: hexOf(grantId) }, lines: [`revoked ${hexOf(grantId)}`] }; // Already revoked, by an earlier run (one interrupted after its revocation @@ -184,7 +187,7 @@ export async function revoke(session: Session, target: string): Promise `already revoked: ${id}`) }; } -export async function revokeAll(session: Session): Promise { - await revokeEveryGrant(session); +export async function revokeAll(session: Session, chain: AccountChain): Promise { + await chain.owner.revokeEveryGrant(session); return { result: { revokedAll: true, generation: (await session.readLedger()).grant_generation.toString() }, lines: ['revoked every grant'] }; } diff --git a/packages/grant/src/lib/grant/prepare.ts b/packages/grant/src/lib/grant/prepare.ts index db0c18b4..2d6f4d16 100644 --- a/packages/grant/src/lib/grant/prepare.ts +++ b/packages/grant/src/lib/grant/prepare.ts @@ -1,13 +1,16 @@ // Everything `mn grant` settles before a wallet is opened: what is asked, // which network, where the account's records are, whether there is an -// account yet, and for a command that starts one, that its wallet exists. The CLI runs it first; the MCP server runs it before it issues a -// confirmation token. +// account yet, for a command that starts one, that its wallet exists, and for +// an issue, that the network's account can hold the grant asked for. The CLI +// runs it first; the MCP server runs it before it issues a confirmation token. import { type ParsedArgs, getFlag, UsageError, type PayingTarget, resolvePayingTarget, type Host } from '@kuiralabs/midnight-cli-core'; import { assertWalletFileExists, getActiveWalletName, resolveWalletPath } from '@kuiralabs/midnight-wallet'; +import { type AccountChain, accountChainFor } from './account-chain.ts'; import { assertAccountNetwork, assertNodeRunsAccount } from './account.ts'; import { NoAccountError } from './account-errors.ts'; import { accountRecordsDir, accountWalletName, ensureAccountRecordsDir } from './account-records.ts'; +import { assertCallerPinnable } from './owner-commands.ts'; import { type GrantRequest, resolveGrantRequest } from './request.ts'; import { contractAddressOnRecord } from './sealed-account.ts'; @@ -27,13 +30,17 @@ export interface PreparedGrant { account: AccountOnRecord | null; } -/** The account the records in `recordsDir` name, if any. Reads the records alone: no chain, no wallet. */ -export async function accountOnRecord(recordsDir: string): Promise { +/** + * The account the records in `recordsDir` name, if any. Reads the records + * alone: no chain, no wallet. Records in plain text are read by the account + * package, which `chain` gives when they are looked for. + */ +export async function accountOnRecord(recordsDir: string, chain: () => Promise): Promise { // A sealed account keeps its address in clear beside its sealed records. const sealedAddress = contractAddressOnRecord(recordsDir); if (sealedAddress !== undefined) return { address: sealedAddress }; - const { directoryOwnerStore } = await import('@kuiralabs/midnight-account-chain/owner'); - const record = directoryOwnerStore(recordsDir).readOwner(); + const { owner } = await chain(); + const record = owner.directoryOwnerStore(recordsDir).readOwner(); return record === undefined ? null : { address: record.contractAddress }; } @@ -42,10 +49,11 @@ export async function prepareGrant(args: ParsedArgs, root: string, host: Host): assertNodeRunsAccount(); const target = resolvePayingTarget(args, 'grant', request.subcommand, root, host); // Refuses a network the account can't reach before anything is created. - assertAccountNetwork(target.networkConfig, root); + const network = assertAccountNetwork(target.networkConfig); + const chain = () => accountChainFor(host.engines, network); const walletName = accountWalletName(getFlag(args, 'wallet'), () => getActiveWalletName(root)); const recordsDir = accountRecordsDir(target.network, walletName, root); - const account = await accountOnRecord(recordsDir); + const account = await accountOnRecord(recordsDir, chain); if (request.subcommand === 'import' && account !== null) { throw new UsageError(`Wallet "${walletName}" already has an account on ${target.network} (${account.address}); a backup is never imported over one.`); } @@ -56,6 +64,7 @@ export async function prepareGrant(args: ParsedArgs, root: string, host: Host): if (request.subcommand !== 'deploy' && request.subcommand !== 'import' && !makesItsOwn && account === null) { throw new NoAccountError(walletName, target.network); } + if (request.subcommand === 'issue') await assertCallerPinnable(request.link, target.network, await chain()); // Only a command that writes an account's first records makes their folder, // and only for a wallet there is: a command refused leaves nothing behind. if (account === null) { diff --git a/packages/grant/src/lib/grant/protect-account.ts b/packages/grant/src/lib/grant/protect-account.ts index a6b32595..2419e3fe 100644 --- a/packages/grant/src/lib/grant/protect-account.ts +++ b/packages/grant/src/lib/grant/protect-account.ts @@ -13,10 +13,10 @@ // never opened under the public password its private state has left. import * as fs from 'node:fs'; -import type { HostEngines } from '@kuiralabs/midnight-cli-core'; +import { type Engine, type HostEngines, isValidNetworkName } from '@kuiralabs/midnight-cli-core'; import * as path from 'node:path'; import type { Arm } from '@kuiralabs/midnight-account'; -import { changePrivateStatePassword, directoryOwnerStore, ownerDeviceFromSecret } from '@kuiralabs/midnight-account-chain/owner'; +import { accountChainOf } from './account-chain.ts'; import { LEGACY_STORE_PASSWORD, privateStateLocationOf } from './account.ts'; import { ACCOUNTS_DIR_NAME, accountRecordsDir } from './account-records.ts'; import { @@ -43,41 +43,52 @@ const PLAIN_SET_ASIDE = /^owner\.unlanded-\d+\.json$/; const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b); /** - * Seals the account in `dir` under `passphrase`, if it is in plain text. Its - * private state is scoped to the paying wallet's shielded coin public key, - * `coinPublicKey` (hex); its new password is one an engine of `engines` - * accepts. `stopBeforeSealing` stops after step 4, as an interrupted run - * would, for the tests. + * The engine an account on `network` (a folder's name under accounts/) is + * sealed with: the network's, which installs the account package over its + * SDK set; an engine of `engines` for a folder that names no network. */ -export async function protectAccount(dir: string, passphrase: string, coinPublicKey: string, engines: HostEngines, { stopBeforeSealing = false }: { stopBeforeSealing?: boolean } = {}): Promise { +const engineForAccountsOn = (engines: HostEngines, network: string): Promise => + (isValidNetworkName(network) ? engines.for(network) : engines.any()); + +/** + * Seals the account in `dir`, on `network`, under `passphrase`, if it is in + * plain text. Its private state is scoped to the paying wallet's shielded + * coin public key, `coinPublicKey` (hex); the account package and the + * password policy are those of the network's engine among `engines`. + * `stopBeforeSealing` stops after step 4, as an interrupted run would, for + * the tests. + */ +export async function protectAccount(dir: string, network: string, passphrase: string, coinPublicKey: string, engines: HostEngines, { stopBeforeSealing = false }: { stopBeforeSealing?: boolean } = {}): Promise { if (isSealedAccount(dir)) { // A run that stopped after sealing, before the plain text was removed. for (const file of [PLAIN_OWNER_FILE, PLAIN_ROSTER_FILE]) fs.rmSync(path.join(dir, file), { force: true }); return 'already-sealed'; } - const plain = directoryOwnerStore(dir); + const engine = await engineForAccountsOn(engines, network); + const { owner } = await accountChainOf(engine); + const plain = owner.directoryOwnerStore(dir); const record = plain.readOwner(); // The owner key beside the records, as an earlier mn kept it in owner.json. const plainOwner = fs.existsSync(path.join(dir, PLAIN_OWNER_FILE)) ? (JSON.parse(fs.readFileSync(path.join(dir, PLAIN_OWNER_FILE), 'utf8')) as { deviceArm?: Arm; deviceSk?: string }) : {}; - const device = plainOwner.deviceSk === undefined ? undefined : ownerDeviceFromSecret(plainOwner.deviceArm ?? 'v1', plainOwner.deviceSk); + const device = plainOwner.deviceSk === undefined ? undefined : owner.ownerDeviceFromSecret(plainOwner.deviceArm ?? 'v1', plainOwner.deviceSk); const hasRoster = fs.existsSync(path.join(dir, PLAIN_ROSTER_FILE)); if (record === undefined && device === undefined && !hasRoster) return 'nothing'; // 1, 2 const key = migratingAccountKey(dir, passphrase); const store = sealedOwnerStore(dir, key); - const keys = sealedDeviceKeys(dir, key); + const keys = sealedDeviceKeys(dir, key, owner); if (record !== undefined) store.writeOwner(record); store.writeRoster(plain.readRoster()); if (device !== undefined && keys.read() === undefined) keys.keep(device); // 3 - const password = sealedPrivateStatePassword(dir, key, (await engines.any()).contracts.acceptsPrivateStatePassword); + const password = sealedPrivateStatePassword(dir, key, engine.contracts.acceptsPrivateStatePassword); const location = privateStateLocationOf(dir, () => LEGACY_STORE_PASSWORD); if (record !== undefined && fs.existsSync(location.database)) { - await changePrivateStatePassword({ getCoinPublicKey: () => coinPublicKey }, record.contractAddress, location, () => password); + await owner.changePrivateStatePassword({ getCoinPublicKey: () => coinPublicKey }, record.contractAddress, location, () => password); } // 4 @@ -116,8 +127,8 @@ export async function protectAllAccounts(stateRootDir: string, passphrase: strin if (fs.readdirSync(dir).length === 0) continue; try { const outcome = isSealedAccount(dir) - ? await protectAccount(dir, passphrase, '', engines) - : await protectAccount(dir, passphrase, await coinKeyOf(wallet), engines); + ? await protectAccount(dir, network, passphrase, '', engines) + : await protectAccount(dir, network, passphrase, await coinKeyOf(wallet), engines); if (outcome !== 'nothing') report.push({ network, wallet, outcome }); } catch (error) { report.push({ network, wallet, error: error instanceof Error ? error.message : String(error) }); diff --git a/packages/grant/src/lib/grant/sealed-account.ts b/packages/grant/src/lib/grant/sealed-account.ts index 79944821..495a96f0 100644 --- a/packages/grant/src/lib/grant/sealed-account.ts +++ b/packages/grant/src/lib/grant/sealed-account.ts @@ -21,15 +21,9 @@ import { randomBytes } from 'node:crypto'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { type Arm, x25519KeyPair, x25519PublicOf } from '@kuiralabs/midnight-account'; -import { - type LocalOwnerDevice, - type OwnerRecord, - type OwnerStore, - type Roster, - freshOwnerDevice, - ownerDeviceFromSecret, -} from '@kuiralabs/midnight-account-chain/owner'; +import type { LocalOwnerDevice, OwnerRecord, OwnerStore, Roster } from '@kuiralabs/midnight-account-chain/owner'; import { FILE_MODE, UsageError, FileExistsError, readJsonIfPresent, writeJsonDurably, type KeyedSecret, freshDataKey, openSecret, openWithKey, sealSecret, sealWithKey } from '@kuiralabs/midnight-cli-core'; +import type { AccountChain } from './account-chain.ts'; import { deviceCodeOf, joinCodeOf } from './device-code.ts'; const ACCOUNT_KEY_FILE = 'account-key.json'; @@ -165,12 +159,16 @@ export interface SealedDeviceKeys { keep(device: D): D; } -export function sealedDeviceKeys(dir: string, key: Uint8Array): SealedDeviceKeys { +/** What makes an owner device in the account package: a fresh one, or one from its secret. */ +export type OwnerDevices = Pick; + +/** The device kept in `dir`, made from its secret by `devices` (the account package's owner entry, from the network's engine). */ +export function sealedDeviceKeys(dir: string, key: Uint8Array, devices: OwnerDevices): SealedDeviceKeys { const deviceFile = path.join(dir, DEVICE_FILE); return { read: () => { const file = readJsonIfPresent(deviceFile); - return file === undefined ? undefined : ownerDeviceFromSecret(file.arm, openWithKey(key, file.secret, 'owner-device').toString('utf8')); + return file === undefined ? undefined : devices.ownerDeviceFromSecret(file.arm, openWithKey(key, file.secret, 'owner-device').toString('utf8')); }, keep: (device) => { try { @@ -249,17 +247,18 @@ export function isPendingDevice(dir: string): boolean { * owns: a JubJub key (the arm the contract adds devices on), made here and * sealed under `passphrase`, before the account's records come in a backup. * Made once: asked again, the same device. Refused where an account is. + * `devices` makes it: the account package's owner entry, from the network's engine. */ -export function createPendingDevice(dir: string, passphrase: string): LocalOwnerDevice { +export function createPendingDevice(dir: string, passphrase: string, devices: OwnerDevices): LocalOwnerDevice { if (isPendingDevice(dir)) { - const kept = sealedDeviceKeys(dir, openAccountKey(dir, passphrase)).read(); + const kept = sealedDeviceKeys(dir, openAccountKey(dir, passphrase), devices).read(); if (kept !== undefined) return kept; } if (isSealedAccount(dir) || isAccountMigrating(dir) || fs.existsSync(path.join(dir, 'owner.json'))) { throw new UsageError(`The wallet already has an account in ${dir}: a new device is made for a wallet with none.`); } const key = createAccountKey(dir, passphrase); - const device = sealedDeviceKeys(dir, key).keep(freshOwnerDevice('v1')); + const device = sealedDeviceKeys(dir, key, devices).keep(devices.freshOwnerDevice('v1')); sealedDeviceList(dir, key).write([deviceCodeOf(device, x25519PublicOf(sealedDeviceReadSecret(dir, key)))]); return device; } diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index da773e11..e4c32a14 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -3,6 +3,7 @@ export function sourceFiles(dir?: string): string[]; export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; export function importRule(fromRel: string, toRel: string): string | undefined; +export function accountImportRule(home: string, specifier: string, typeOnly: boolean): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; /** The imports of a test file that break a rule: a test imports its own package relatively, every other by an entry point. */ export function testProblems(file: string): { home: string; rule: string; where: string; specifier: string }[]; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 26554886..85a4c83e 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -135,7 +135,24 @@ const MIDNIGHT_SDK = /^@midnight(-ntwrk|ntwrk)\//; // it ships, which the host installs as core's engine loader. const ENGINE_LOADER = 'lib/installed-engines.ts'; -const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account/; +// The account package (its Midnight libraries are peer dependencies) and the +// account library it is built on (no SDK). Grant drives the account; each +// engine installs the package over its own SDK set, and grant reaches its +// code through the network's engine, importing its types alone: a copy grant +// imported would resolve the package's libraries from grant's folder. +const ACCOUNT_CHAIN = /^@kuiralabs\/midnight-account-chain(\/|$)/; +const ACCOUNT_LIBRARY = /^@kuiralabs\/midnight-account(\/|$)/; + +/** The rule an import of the account package or library from `home` breaks (`typeOnly`: an `import type`), or undefined. */ +export function accountImportRule(home, specifier, typeOnly) { + if (ACCOUNT_CHAIN.test(specifier)) { + if (home === 'engine') return undefined; + if (home === 'grant') return typeOnly ? undefined : "grant → account chain's code (grant reaches it through the network's engine, and imports its types alone)"; + return `${home} → account chain`; + } + if (ACCOUNT_LIBRARY.test(specifier) && home !== 'grant') return `${home} → account chain`; + return undefined; +} // The engine contract's reading of the SDK's and the node's errors: an engine // turns them into typed errors, so only the engines read them, and in core @@ -479,8 +496,8 @@ function sourceProblems(file) { for (const rule of rules) violations.push({ home, rule, where, specifier }); } else if (MIDNIGHT_SDK.test(specifier) && home !== 'engine') { violations.push({ home, rule: `${home} → Midnight SDK (only an engine imports it)`, where, specifier }); - } else if (home !== 'grant' && ACCOUNT_CHAIN.test(specifier)) { - violations.push({ home, rule: `${home} → account chain`, where, specifier }); + } else if (accountImportRule(home, specifier, imported.typeOnly) !== undefined) { + violations.push({ home, rule: accountImportRule(home, specifier, imported.typeOnly), where, specifier }); } } return violations; diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index 157f1a1b..ff45dd30 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -2,9 +2,10 @@ // depends on, serves them from a local registry as npm serves published // packages, installs mn globally from it into an empty prefix, and checks the // tree the install holds still works: one copy of each WASM package per SDK -// engine (the shrinkwrap mn ships keeps each engine's set apart), grant on the -// rc engine's copies, each engine loading, the packages a contract run's -// script imports, and the files the code reads at run time. +// engine (the shrinkwrap mn ships keeps each engine's set apart), each +// engine's copy of the account package on that engine's copies and grant on +// none, each engine loading, the packages a contract run's script imports, +// and the files the code reads at run time. // // The test suite runs on the lockfile's tree, which a consumer never sees. Two // features broke that way without a test noticing: a newer @scure/base refused @@ -73,6 +74,15 @@ function copiesOf(root, name) { return found; } +/** The folder of `dep` as Node resolves it from the package in `from`, or null. */ +function resolveFrom(from, dep) { + for (let at = from; ; at = dirname(at)) { + const manifest = join(at, 'node_modules', dep, 'package.json'); + if (existsSync(manifest)) return realpathSync(dirname(manifest)); + if (dirname(at) === at) return null; + } +} + /** * Every copy of `name` that the package in `dir` reaches through its * dependencies, by Node's resolution from each package's folder: the copies a @@ -81,13 +91,6 @@ function copiesOf(root, name) { function resolvedCopies(dir, name) { const found = new Map(); const seen = new Set(); - const resolveFrom = (from, dep) => { - for (let at = from; ; at = dirname(at)) { - const manifest = join(at, 'node_modules', dep, 'package.json'); - if (existsSync(manifest)) return realpathSync(dirname(manifest)); - if (dirname(at) === at) return null; - } - }; // By the name code imports it under: an npm alias of the same package under another name is another package to its importers. const walk = (pkgDir) => { if (seen.has(pkgDir)) return; @@ -155,20 +158,34 @@ const check = (what, ok, detail = '') => { if (!ok) failures.push(what); }; +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; + /** - * grant's account chain is built on the rc set: in the install at `root`, - * grant resolves one copy of each WASM package, at the rc engine's version. - * With `sameCopy`, the very copy the rc engine resolves: mn's shrinkwrap lays - * the two out on one tree. A program that installs both packages itself gets - * each one's shrinkwrapped tree under it, so the copies match by version only. + * Each engine installs the account package, whose Midnight libraries are peer + * dependencies: in the install at `root`, the copy each engine resolves + * reaches that engine's own copy of each WASM package (its compact runtime + * picks the contract build), the two engines' copies are two, and grant, + * which reaches the package through an engine, reaches no WASM package. */ -function checkGrantOnRcSet(root, who, { sameCopy }) { - const at = (copies) => copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(root).length)}`).join(', '); +function checkAccountPackagePerEngine(root, who) { + const shown = (dir) => (dir === null ? 'none' : `${JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')).version} ${dir.slice(realpathSync(root).length)}`); + const copies = []; + for (const set of ['rc', 'beta']) { + const engine = join(root, 'node_modules', '@kuiralabs', `midnight-engine-${set}`); + const account = resolveFrom(engine, ACCOUNT_PACKAGE); + check(`${who}the ${set} engine resolves ${ACCOUNT_PACKAGE}`, account !== null, shown(account)); + if (account === null) continue; + copies.push(account); + for (const sdk of WASM_PACKAGES) { + const fromAccount = resolveFrom(account, sdk); + const fromEngine = resolveFrom(engine, sdk); + check(`${who}the ${set} engine's ${ACCOUNT_PACKAGE} resolves ${sdk} to the engine's copy`, fromAccount !== null && fromAccount === fromEngine, `account package: ${shown(fromAccount)}; engine: ${shown(fromEngine)}`); + } + } + check(`${who}each engine has a copy of ${ACCOUNT_PACKAGE} of its own`, copies.length === 2 && copies[0] !== copies[1], copies.map(shown).join('; ')); for (const sdk of WASM_PACKAGES) { const grant = resolvedCopies(join(root, 'node_modules', '@kuiralabs', 'midnight-grant'), sdk); - const rc = resolvedCopies(join(root, 'node_modules', '@kuiralabs', 'midnight-engine-rc'), sdk); - const matches = grant.length === 1 && rc.length === 1 && (sameCopy ? grant[0].dir === rc[0].dir : grant[0].version === rc[0].version); - check(`${who}@kuiralabs/midnight-grant resolves one copy of ${sdk}, ${sameCopy ? "the rc engine's" : "at the rc engine's version"}`, matches, `grant: ${at(grant)}; rc engine: ${at(rc)}`); + check(`${who}@kuiralabs/midnight-grant reaches no copy of ${sdk}`, grant.length === 0, grant.map((c) => shown(c.dir)).join(', ')); } } @@ -208,7 +225,7 @@ try { check(`${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(installed).length)}`).join(', ')); } } - checkGrantOnRcSet(installed, '', { sameCopy: true }); + checkAccountPackagePerEngine(installed, ''); // A shielded address is longer than bech32's 90 characters; the address // library must still read the one the installed mn derives. @@ -289,23 +306,26 @@ try { check(`the ${network} run leaves the dApp's folder as it was`, ran.leftAsItWas); } - // mn grant drives the account package it installed: its owner records load - // from the installed tree and answer that the new wallet has no account. - // Asking that reaches no chain and opens no proving-artefact cache (the - // release gate's live run checks the cache, around the first deploy). - let grant = ''; - try { - execFileSync(mn, ['grant', 'status', '--wallet', 'check', '--network', 'undeployed', '--node', 'ws://127.0.0.1:9', '--indexer-ws', 'ws://127.0.0.1:9/api/v4/graphql/ws', '--proof-server', 'http://127.0.0.1:9'], { - cwd: work, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], env, - }); - grant = 'answered without an error'; - } catch (error) { - grant = String(error.stderr ?? error.message); + // mn grant drives the account package it installed, through the engine of + // each network's set: its owner records load from that engine's copy in the + // installed tree and answer that the new wallet has no account. Asking that + // reaches no chain and opens no proving-artefact cache (the release gate's + // live run checks the cache, around the first deploy). + for (const [network, set] of [['undeployed', 'rc'], ['stagenet', 'beta']]) { + let grant = ''; + try { + execFileSync(mn, ['grant', 'status', '--wallet', 'check', '--network', network, '--node', 'ws://127.0.0.1:9', '--indexer-ws', 'ws://127.0.0.1:9/api/v4/graphql/ws', '--proof-server', 'http://127.0.0.1:9'], { + cwd: work, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], env, + }); + grant = 'answered without an error'; + } catch (error) { + grant = String(error.stderr ?? error.message); + } + check(`mn grant on ${network} drives the ${set} engine's installed account package`, new RegExp(`Wallet "check" has no account on ${network} yet`).test(grant), grant.includes('has no account') ? 'no account yet, as for a new wallet' : grant.trim().split('\n').slice(-2).join(' | ')); } - check('mn grant drives the installed account package', /Wallet "check" has no account on undeployed yet/.test(grant), grant.includes('has no account') ? 'no account yet, as for a new wallet' : grant.trim().split('\n').slice(-2).join(' | ')); check('it opens no proving-artefact cache', !existsSync(join(home, '.midnight', 'account-artifacts')), 'none under ~/.midnight'); - const chains = copiesOf(installed, '@kuiralabs/midnight-account-chain'); - check('one copy of @kuiralabs/midnight-account-chain', chains.length === 1, chains.join(', ')); + const chains = copiesOf(installed, ACCOUNT_PACKAGE); + check(`two copies of ${ACCOUNT_PACKAGE}, one for each engine`, chains.length === 2, chains.join(', ')); // The MCP server reads its skill documents from the installed package. const { tools, resources } = await askMcpServer(join(prefix, 'bin', 'midnight-wallet-mcp'), env); @@ -320,8 +340,8 @@ try { // A program that loads an engine without mn: it installs the workspace // packages from the registry, each engine and grant with the shrinkwrap it - // ships, and gets each engine's SDK set once beside one copy of each package - // it shares. + // ships, and gets each engine's SDK set once, with its copy of the account + // package, beside one copy of each package it shares. const outside = join(work, 'outside'); mkdirSync(outside); writeFileSync(join(outside, 'package.json'), JSON.stringify({ name: 'outside', private: true, type: 'module' })); @@ -337,7 +357,7 @@ try { check(`a program outside mn: ${name} resolves one copy of ${sdk}`, copies.length === 1, copies.map((c) => `${c.version} ${c.dir.slice(realpathSync(outside).length)}`).join(', ')); } } - checkGrantOnRcSet(outside, 'a program outside mn: ', { sameCopy: false }); + checkAccountPackagePerEngine(outside, 'a program outside mn: '); writeFileSync(join(outside, 'load.mjs'), ` import { createHost } from '@kuiralabs/midnight-cli-core'; const host = createHost({ diff --git a/scripts/make-shrinkwrap.mjs b/scripts/make-shrinkwrap.mjs index f314ed50..5966ffe7 100644 --- a/scripts/make-shrinkwrap.mjs +++ b/scripts/make-shrinkwrap.mjs @@ -13,9 +13,11 @@ // under it, and its tarball and integrity from `dist`. // // Each SDK engine ships one too (`--package packages/engine-*`), so a program -// that installs an engine without mn gets the set the tests ran on; and so -// does grant (`--package packages/grant`), whose account chain is built on the -// rc set. It leaves out the workspace packages the package depends on (core +// that installs an engine without mn gets the set the tests ran on, with the +// account package beside it (its Midnight libraries are peer dependencies, so +// they resolve to that set); and so does grant (`--package packages/grant`), +// which reaches the account package through an engine and pins only the +// account library's own tree. It leaves out the workspace packages the package depends on (core // and chain; for grant also wallet and contract): those are shared with the // program that loads it, which installs them itself, so the process holds one // copy of each. diff --git a/src/__tests__/engine-beta-grant.test.ts b/src/__tests__/engine-beta-grant.test.ts new file mode 100644 index 00000000..d99b6c42 --- /dev/null +++ b/src/__tests__/engine-beta-grant.test.ts @@ -0,0 +1,60 @@ +// mn grant issue on stagenet, run as the CLI runs it: the beta engine's copy +// of the account package pins no caller, so a request that pins its calling +// contract is refused with CALLER_PIN_UNSUPPORTED before the command asks for +// its payer, and so before any wallet is opened or transaction built; the +// same request without the pin gets as far as the payer. The home directory +// is a temporary one; nothing here reaches a chain. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { parseArgs, NoPayerError } from '@kuiralabs/midnight-cli-core'; +import { resolvedPackageFolder } from '@kuiralabs/midnight-cli-core/engine'; +import { grantDefinition } from '@kuiralabs/midnight-grant/commands'; +import { cliCall } from './helpers/cli-call.ts'; +import { expectDeclared } from './helpers/expect-declared.ts'; +import { agentLink } from '../../test-support/grant-request-links.ts'; + +const { default: grantCommand } = await grantDefinition.load(); + +const BETA_ENGINE = new URL('../../packages/engine-beta', import.meta.url).pathname; +const ENDPOINTS = ['--node', 'ws://127.0.0.1:9', '--indexer-ws', 'ws://127.0.0.1:9/api/v4/graphql/ws', '--proof-server', 'http://127.0.0.1:9']; +// An account's records as an earlier mn left them. +const ACCOUNT = '5e'.repeat(32); +const OWNER_RECORD = { contractAddress: ACCOUNT, deviceArm: 'k1', deviceSk: '4f'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }; + +let home: string; +let origHome: string | undefined; + +beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'mn-grant-stagenet-'))); + origHome = process.env.HOME; + process.env.HOME = home; + const records = path.join(home, '.midnight', 'accounts', 'stagenet', 'alice'); + fs.mkdirSync(records, { recursive: true }); + fs.writeFileSync(path.join(records, 'owner.json'), JSON.stringify(OWNER_RECORD)); +}); + +afterEach(() => { + process.env.HOME = origHome; + fs.rmSync(home, { recursive: true, force: true }); +}); + +const issue = (link: string, ...flags: string[]) => cliCall(grantCommand, parseArgs(['grant', 'issue', link, ...flags, '--wallet', 'alice', '--network', 'stagenet', '--json', ...ENDPOINTS])); +const betaLink = (caller?: Uint8Array) => agentLink(resolvedPackageFolder(BETA_ENGINE, '@kuiralabs/midnight-account-chain')!, ACCOUNT, caller); + +describe('mn grant issue on stagenet', () => { + it('refuses a request that pins its calling contract before it asks for a payer, with CALLER_PIN_UNSUPPORTED', async () => { + const link = await betaLink(new Uint8Array(32).fill(0xc4)); + for (const confirm of [[], ['--yes']]) { + const refused = issue(link, ...confirm); + await expect(refused).rejects.toMatchObject({ code: 'CALLER_PIN_UNSUPPORTED' }); + await refused.catch((err: unknown) => expectDeclared('grant', err)); + } + }); + + it('takes the same request without the pin as far as the payer it was given none of', async () => { + await expect(issue(await betaLink(), '--yes')).rejects.toThrow(NoPayerError); + }); +}); diff --git a/src/__tests__/exit-codes.test.ts b/src/__tests__/exit-codes.test.ts index 81f38838..127cdaf3 100644 --- a/src/__tests__/exit-codes.test.ts +++ b/src/__tests__/exit-codes.test.ts @@ -1,7 +1,8 @@ import { describe, it, expect } from 'vitest'; import { classifyError, humanizeNetworkError, ERROR_CODES, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR, EXIT_INVALID_ARGS, WrongPassphraseError, OtherSdkSetError, UsageError } from '@kuiralabs/midnight-cli-core'; import { MixedSdkLayoutError, toEngineError } from '@kuiralabs/midnight-cli-core/engine'; -import { NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from '@kuiralabs/midnight-grant'; +import { CallerPinUnavailableError, NoAccountError, NodeTooOldForAccountError, UnreachableByAccountError } from '@kuiralabs/midnight-grant'; +import { CallerPinUnsupportedError } from '@kuiralabs/midnight-account-chain/errors'; import { NoPassphraseError } from '@kuiralabs/midnight-wallet'; import { installedCommands } from '../lib/installed-commands.ts'; @@ -74,6 +75,11 @@ describe('classifyError: mn grant', () => { expect(classifyError(new NoAccountError('alice', 'undeployed'), installedCommands)).toEqual({ exitCode: EXIT_GENERAL_ERROR, errorCode: ERROR_CODES.NO_ACCOUNT }); }); + it('counts a caller pin the network\'s account can\'t hold as the caller\'s to fix: grant\'s refusal, and the account package\'s own by its code', () => { + expect(classifyError(new CallerPinUnavailableError('stagenet', 'c4'.repeat(32)), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.CALLER_PIN_UNSUPPORTED }); + expect(classifyError(new CallerPinUnsupportedError('this build of the account (AccountStagenet) pins no caller'), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.CALLER_PIN_UNSUPPORTED }); + }); + it('counts a network the account package can\'t reach as the caller\'s to fix', () => { expect(classifyError(new UnreachableByAccountError('PreProd'), installedCommands)).toEqual({ exitCode: EXIT_INVALID_ARGS, errorCode: ERROR_CODES.INVALID_ARGS }); }); diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index 5be72529..d7a277d5 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { findLayeringProblems, importRule, importedModules, testProblems } from '../../scripts/check-layering.mjs'; +import { accountImportRule, findLayeringProblems, importRule, importedModules, testProblems } from '../../scripts/check-layering.mjs'; const ROOT = join(import.meta.dirname, '..', '..'); const FIXTURES = join(import.meta.dirname, 'fixtures', 'layering'); @@ -71,6 +71,15 @@ describe('the layering', () => { expect(importRule('lib/exit-codes.ts', 'lib/sdk-errors.ts')).toBe("core → the SDK's errors (only an engine reads them)"); }); + it("lets an engine install the account package, and grant reach its code only through one", () => { + expect(accountImportRule('engine', '@kuiralabs/midnight-account-chain/owner', false)).toBeUndefined(); + expect(accountImportRule('grant', '@kuiralabs/midnight-account-chain/owner', true)).toBeUndefined(); + expect(accountImportRule('grant', '@kuiralabs/midnight-account-chain/owner', false)).toBe("grant → account chain's code (grant reaches it through the network's engine, and imports its types alone)"); + expect(accountImportRule('grant', '@kuiralabs/midnight-account', false)).toBeUndefined(); + expect(accountImportRule('wallet', '@kuiralabs/midnight-account-chain/owner', true)).toBe('wallet → account chain'); + expect(accountImportRule('core', '@kuiralabs/midnight-account', false)).toBe('core → account chain'); + }); + it('lets only an engine import the SDK', () => { // findLayeringProblems above finds none elsewhere; core, chain and every package are held to it alike. expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); diff --git a/test-support/grant-request-links.ts b/test-support/grant-request-links.ts new file mode 100644 index 00000000..7da6f25f --- /dev/null +++ b/test-support/grant-request-links.ts @@ -0,0 +1,15 @@ +// A grant request link as an agent sends it, made by the agent entry of one +// copy of the account package: the copy an engine installs, so a test loads +// that copy's SDK set alone. + +import * as path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +type Agent = typeof import('@kuiralabs/midnight-account-chain/agent'); + +/** A request for a payment to one coin key, from slot 3 of `account`, through the calling contract `caller` if one is named; made by the copy of the package in the folder `copy`. */ +export async function agentLink(copy: string, account: string, caller?: Uint8Array): Promise { + const { freshGrantee, grantRequestFor, grantRequestLink } = (await import(pathToFileURL(path.join(copy, 'dist', 'src', 'entry', 'agent.js')).href)) as Agent; + const identity = { account, clientId: 'rdns:org.example.agent', grantee: freshGrantee('k1'), readSecret: new Uint8Array(32).fill(7) }; + return grantRequestLink(grantRequestFor(identity, 3, new Uint8Array(32).fill(0x9a), 2, caller)); +} From 22799f5334726af27ad23c4e207ac09ce70487f0 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 00:02:34 -0800 Subject: [PATCH 75/88] What a host provides: ./process, the session, engines that let go (3G) Core gains "./process", the only package code that touches the process, and only when a host calls it: installSdkProcessGuard (the guard against the wallet SDK's transient rejections during sync, with its console filter as an option; a rejection no call listens to is reported by default, and mn keeps exiting) and syncHeapAdvice / syncHeapTargetMb (the heap a cold sync needs). mn's shell uses them; no package source may import it. openWalletSession is exported from core's "." with an sdkWarnings option, listening until close(). Both engines now let a program end after session.close(): the facade opens its node submission client only on the first submit (a node that is down kept a never-submitting session reconnecting forever), and stopping the facade clears its 5 s race timer. Child-process tests hang before and end in about 40 ms after. packages/cli-core/README.md, "Your process", shows a program's setup and what mn's shell does that a program must do; a test runs its setup block. A child-process test proves a floating Wallet.Sync rejection kills a program without the guard and not with it, on Node and bun. Suite 3000, beta 195; snapshot unchanged; fresh install (an outside program loads ./process); live gate from a fresh runner: final pass 84/84, mn dev 8/8, stagenet pass 18/18. --- packages/cli-core/README.md | 64 +++++ packages/cli-core/api-report.md | 45 ++++ packages/cli-core/package.json | 5 + .../__tests__/process-guard-program.test.ts | 126 ++++++++++ .../src/__tests__/readme-process.test.ts | 95 +++++++ .../src/__tests__/sdk-process-guard.test.ts | 211 ++++++++++++++++ .../cli-core/src/__tests__/sync-heap.test.ts | 74 ++++++ packages/cli-core/src/index.ts | 5 +- packages/cli-core/src/lib/call-context.ts | 4 +- packages/cli-core/src/lib/constants.ts | 2 +- packages/cli-core/src/lib/sdk-warnings.ts | 14 +- packages/cli-core/src/lib/wallet-session.ts | 35 ++- packages/cli-core/src/process.ts | 8 + .../cli-core/src/process/sdk-process-guard.ts | 123 +++++++++ packages/cli-core/src/process/sync-heap.ts | 77 ++++++ .../src/__tests__/facade-stop.test.ts | 6 + packages/engine-beta/src/facade.ts | 44 +++- packages/engine-beta/src/transfer.ts | 4 +- .../src/__tests__/facade-stop.test.ts | 6 + .../src/__tests__/wallet-session.test.ts | 105 +++++++- packages/engine-rc/src/facade.ts | 44 +++- packages/engine-rc/src/transfer.ts | 4 +- scripts/check-layering.d.mts | 2 + scripts/check-layering.mjs | 27 +- scripts/check-process-safety.d.mts | 2 + scripts/check-process-safety.mjs | 31 ++- src/__tests__/entry-points.test.ts | 2 +- src/__tests__/heap-guard.test.ts | 51 ---- src/__tests__/layering.test.ts | 25 +- src/__tests__/process-safety.test.ts | 235 +++--------------- src/lib/cli-host.ts | 12 +- src/lib/heap-guard.ts | 58 ++--- src/lib/sdk-noise.ts | 76 ------ test-support/facade-stop-suite.ts | 113 +++++++++ test-support/stand-in-indexer.ts | 65 +++++ 35 files changed, 1377 insertions(+), 423 deletions(-) create mode 100644 packages/cli-core/README.md create mode 100644 packages/cli-core/src/__tests__/process-guard-program.test.ts create mode 100644 packages/cli-core/src/__tests__/readme-process.test.ts create mode 100644 packages/cli-core/src/__tests__/sdk-process-guard.test.ts create mode 100644 packages/cli-core/src/__tests__/sync-heap.test.ts create mode 100644 packages/cli-core/src/process.ts create mode 100644 packages/cli-core/src/process/sdk-process-guard.ts create mode 100644 packages/cli-core/src/process/sync-heap.ts create mode 100644 packages/engine-beta/src/__tests__/facade-stop.test.ts create mode 100644 packages/engine-rc/src/__tests__/facade-stop.test.ts delete mode 100644 src/lib/sdk-noise.ts create mode 100644 test-support/facade-stop-suite.ts diff --git a/packages/cli-core/README.md b/packages/cli-core/README.md new file mode 100644 index 00000000..8d7fa98b --- /dev/null +++ b/packages/cli-core/README.md @@ -0,0 +1,64 @@ +# @kuiralabs/midnight-cli-core + +The base of the Midnight CLI packages: the host a program passes to them, typed errors and their codes, networks, settings and the state root, the wallet session, and the engine contract the SDK engines are built against. + +## Your process: what mn's shell does that you must do + +mn's shell does a few things to its own process so that the wallet SDK can run in it. A library never does them: it would be changing a process that is yours. When your program runs the SDK through these packages, the things below are yours to do, and core gives you the parts you can't write yourself in its `./process` entry point. Nothing in `./process` runs when you import it; you call it, once, at start. + +### The setup + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { createHost, openWalletSession } from '@kuiralabs/midnight-cli-core'; +import { installSdkProcessGuard, syncHeapAdvice } from '@kuiralabs/midnight-cli-core/process'; +import { createBetaEngine } from '@kuiralabs/midnight-engine-beta'; + +const guard = installSdkProcessGuard(); +const heap = syncHeapAdvice(); +if (heap) console.error(`A first sync may need more heap: start with NODE_OPTIONS=${heap.nodeOptions}`); +const stateRoot = join(homedir(), '.my-app'); +const host = createHost({ paths: { stateRoot, home: homedir() }, notice: (line) => console.error(line), sdkWarnings: guard.calls, engineLoader: async (_set, host) => createBetaEngine(host) }); +const cancel = new AbortController(); +process.once('SIGINT', () => cancel.abort()); + +const session = await guard.calls.run((sdkWarnings) => openWalletSession({ seed: Buffer.from(process.env.WALLET_SEED, 'hex'), network: 'stagenet', root: stateRoot, notice: host.notice, engines: host.engines, sdkWarnings, signal: cancel.signal, onMessage: (line) => console.error(line) })); +try { + console.log(await session.balances()); +} finally { + await session.close(); +} +``` + +This opens a wallet on stagenet (which runs the beta SDK set, so the program loads the beta engine; preprod, preview and a local network run the rc engine, `createRcEngine` from `@kuiralabs/midnight-engine-rc`), prints what it holds, closes it, and ends by itself. `WALLET_SEED` is the wallet's seed in hex: 64 bytes from a mnemonic, or 32 raw. A test in this package runs the block above as it is written here, with only the engine standing in. + +### What each part does + +**A. The SDK's transient rejections.** During a sync the wallet SDK lets transient failures (`Wallet.Sync: Internal Server Error`, a dropped indexer socket) escape as unhandled promise rejections while it retries the work itself. Node exits 1 on an unhandled rejection, so without the guard your program dies in the middle of a sync. `installSdkProcessGuard()` installs one `unhandledRejection` handler: a transient `Wallet.*` rejection goes to the call that is listening for the SDK's warnings, and the program goes on. With no call listening, it goes to `onWarning` (a line on `console.warn` unless you give one). Any other unhandled rejection is printed and exits 1, as before. mn installs it with `outsideCalls: 'exit'`, which exits 1 on a transient rejection no call listens for; that is mn's choice, not the default. `guard.uninstall()` takes the handler off again. + +**B. The SDK's console noise.** The SDK prints its retried failures as stack traces on `console.error`, and polkadot-js prints a `RPC-CORE` line for each failed submit. `installSdkProcessGuard({ console: true })` keeps both off the console while a call listens, handing the traces to that call as warnings; at any other time the console is untouched. It is off by default, because it replaces `console.error` and `console.warn`. polkadot-js's `API-WS` lines (a node connection lost and retried) are not filtered. + +**C. Which call a warning belongs to.** `guard.calls.run(work)` runs `work` as one call and gives it its `sdkWarnings`; a warning raised while that call runs goes to that call alone. Pass them to `openWalletSession`: the session listens from the open until `close()`, and with `onMessage` you get each warning as a line, `SDK: `. Pass `guard.calls` to `createHost` too, so library calls made through the host listen the same way. + +**D. The heap a cold sync needs.** The first shielded or Dust sync of a wallet against a hosted network streams the chain's history through the SDK: its live working set stays near 300 MB, but short-lived objects took the heap to about 8.4 GB in a cold shielded sync measured on preprod. Under Node's default old-space limit (about 4 GB) the process can die with `JavaScript heap out of memory` before it writes the cache that makes every later sync cheap. The limit is fixed when Node starts, so no library can raise it. `syncHeapAdvice()` says whether this process's limit is too small on this machine and, if so, the flag to start with (`--max-old-space-size=16384`, or 70% of the machine's memory if that is less); it returns null when the limit will do. Start your program with that flag in `NODE_OPTIONS`, or re-run it with the flag before it loads the SDK, as mn's shell does. `syncHeapTargetMb(options)` is the same computation with every input given. + +**E. Ctrl-C.** mn aborts the running work on SIGINT and SIGTERM and exits 5 seconds later whatever is still running. In a program, make one `AbortController`, abort it on the signal, and pass its `signal` to every call that takes one: an open that is cancelled stops what it started and rejects with `CancelledError`. Exiting after a grace period is your choice to make. + +**F. Ending the process.** `await session.close()` reverts what the session built but never submitted, stops the wallet and closes what the engine opened: the indexer's sockets, the node client, the timers. After it, a program with nothing else to do ends by itself. mn still calls `process.exit` after a command that ran the SDK; a program does not have to. + +**G. Blockfrost project ids.** Preprod's endpoints carry a Blockfrost project id in their URLs, and URLs end up in error messages and progress lines. mn hides them in everything it prints. Pass anything you print or log through `redactProjectId(text)` from this package; libraries you don't control (polkadot-js prints the URL it lost) write to the console themselves, so to catch those too, wrap your output streams as mn does. + +### Node and bun + +The guard works on both. On Node, a warning keeps the identity of the call it was raised in through the SDK's WebSocket callbacks, timers, RxJS and Effect fibers. Under bun (1.3) the identity is lost on everything resumed from a WebSocket: such a warning goes to the one call listening, or, with several listening, to none of them (never to the wrong one); either way it stays off the console while a call listens. + +The heap advice is Node's: under bun `syncHeapAdvice()` returns null, because bun's heap is JavaScriptCore's and neither `NODE_OPTIONS` nor `--max-old-space-size` sets it. How much memory a cold sync takes under bun has not been measured. + +### Troubleshooting + +- **`Unhandled rejection:` with a `Wallet.Sync` error, then exit 1.** The guard isn't installed, or it was installed with `outsideCalls: 'exit'` and no call was listening. Install it before the first sync, and open the session inside `guard.calls.run` with `sdkWarnings`. +- **`JavaScript heap out of memory` during the first sync.** Start with the `NODE_OPTIONS` that `syncHeapAdvice()` names. Later syncs start from the cache and need far less. +- **The program doesn't end after it is done.** A session was not closed: every `openWalletSession` needs its `await session.close()`, also when the work in between threw (use `finally`). On Node, `process.getActiveResourcesInfo()` lists what is still open. If the SDK's wallets don't stop within 5 seconds the engine gives up waiting and what they hold stays open; then exit explicitly, as mn does. +- **`OtherSdkSetError`.** One process runs one SDK set: stagenet is on the beta set, the other networks on rc. A program that needs both runs two processes. +- **Warnings reach the console while a session is open.** Without `console: true` the guard leaves the console alone, so the SDK's traces print there; pass `console: true` to keep them off while a call listens. diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 82cc9dd8..545eb9f6 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -767,6 +767,21 @@ export declare function isTransportFailure(failure: unknown): boolean; export declare function withTransportCode(err: unknown): unknown; export type VerboseLog = (phase: string, message: string) => void; export declare function clearWalletCache(address: string | undefined, network: string | undefined, root: string): void; +export declare function openWalletSession(options: OpenWalletSessionOptions): Promise; +export interface OpenWalletSessionOptions { + seed: Buffer; + network: NetworkName; + root: string; + notice: NoticeSink; + engines: HostEngines; + networkConfig?: NetworkConfig; + settings?: NetworkSettings; + forceShielded?: boolean; + dustWaitMs?: number; + signal?: AbortSignal; + onMessage?: (message: string) => void; + sdkWarnings?: CallSdkWarnings; +} export declare function sessionOver(network: NetworkName, opened: OpenedConnector, readTransaction: (tx: string, stage: 'unsealed' | 'sealed') => TransactionDetail[], reopening?: SessionReopening): WalletSession; export interface WalletSession { readonly network: NetworkName; @@ -1417,6 +1432,36 @@ export interface WalletCacheData { } ``` +## `@kuiralabs/midnight-cli-core/process` + +```ts +export declare function installSdkProcessGuard(options?: SdkProcessGuardOptions): SdkProcessGuard; +export interface SdkProcessGuard { + readonly calls: SdkWarningCalls; + uninstall(): void; +} +export interface SdkProcessGuardOptions { + readonly console?: boolean; + readonly outsideCalls?: 'exit' | 'report'; + readonly onWarning?: (tag: string, message: string) => void; +} +export interface SyncHeapAdvice { + readonly maxOldSpaceMb: number; + readonly nodeOptions: string; +} +export declare function syncHeapAdvice(options?: { + readonly desiredMb?: number; +}): SyncHeapAdvice | null; +export declare function syncHeapTargetMb(opts: SyncHeapTargetOptions): number | null; +export interface SyncHeapTargetOptions { + readonly totalMb: number; + readonly currentLimitMb: number; + readonly desiredMb?: number; + readonly ramFraction?: number; + readonly minGainMb?: number; +} +``` + ## `@kuiralabs/midnight-cli-core/ui` ```ts diff --git a/packages/cli-core/package.json b/packages/cli-core/package.json index c3b60e7a..c665560b 100644 --- a/packages/cli-core/package.json +++ b/packages/cli-core/package.json @@ -36,6 +36,11 @@ "midnight-cli-source": "./src/commands.ts", "types": "./dist/commands.d.ts", "default": "./dist/commands.js" + }, + "./process": { + "midnight-cli-source": "./src/process.ts", + "types": "./dist/process.d.ts", + "default": "./dist/process.js" } }, "files": [ diff --git a/packages/cli-core/src/__tests__/process-guard-program.test.ts b/packages/cli-core/src/__tests__/process-guard-program.test.ts new file mode 100644 index 00000000..8e0d1369 --- /dev/null +++ b/packages/cli-core/src/__tests__/process-guard-program.test.ts @@ -0,0 +1,126 @@ +// The SDK process guard as a program meets it: its defaults, in a child +// process that imports "./process" by its package name, on Node and, when it +// is installed, on bun. A floating Wallet.Sync rejection (the SDK's transient +// failure, retried by the SDK) kills a program without the guard and not one +// with it, which reports it instead; a real error still exits 1; importing +// "./process" installs nothing; uninstall gives the process back. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { spawn, spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const ROOT = resolve(import.meta.dirname, '..', '..', '..', '..'); + +/** The SDK's transient failure, escaping as an unhandled rejection, then work that shows whether the program went on. */ +const FLOATING_SYNC_REJECTION = [ + "Promise.reject(Object.assign(new Error('Internal Server Error'), { _tag: 'Wallet.Sync' }));", + "setTimeout(() => console.log('still running'), 200);", +].join('\n'); + +interface Runtime { + readonly name: string; + readonly command: string; + readonly args: readonly string[]; +} + +const NODE: Runtime = { name: 'Node', command: process.execPath, args: ['--import', 'tsx'] }; +// bun runs the workspace's TypeScript sources itself, through the same export condition. +const BUN: Runtime = { name: 'bun', command: 'bun', args: ['--conditions=midnight-cli-source'] }; +const bunInstalled = spawnSync('bun', ['--version'], { encoding: 'utf8' }).status === 0; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'mn-guard-program-')); + // The program resolves the packages as one installed beside it would. + symlinkSync(join(ROOT, 'node_modules'), join(dir, 'node_modules')); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +function runProgram(runtime: Runtime, body: string): Promise<{ code: number | null; stdout: string; stderr: string }> { + writeFileSync(join(dir, 'program.mjs'), body); + return new Promise((done) => { + const child = spawn(runtime.command, [...runtime.args, 'program.mjs'], { cwd: dir, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + const hung = setTimeout(() => child.kill('SIGKILL'), 60_000); + child.on('exit', (code) => { + clearTimeout(hung); + done({ code, stdout, stderr }); + }); + }); +} + +/** "./process" by its package name, as a program outside the repository imports it (the test itself imports nothing of it). */ +const PROCESS_ENTRY = '@kuiralabs/midnight-cli-core/process'; +const importGuard = `import { installSdkProcessGuard } from ${JSON.stringify(PROCESS_ENTRY)};`; + +describe.each([NODE, ...(bunInstalled ? [BUN] : [])])('the SDK process guard in a program, on $name', (runtime) => { + it('without it, a floating Wallet.Sync rejection kills the program: exit 1', async () => { + const { code, stdout } = await runProgram(runtime, FLOATING_SYNC_REJECTION); + expect(code).toBe(1); + expect(stdout).not.toContain('still running'); + }); + + it('with it, the program goes on and the rejection is reported: exit 0, a line on console.warn by default', async () => { + const { code, stdout, stderr } = await runProgram(runtime, [importGuard, 'installSdkProcessGuard();', FLOATING_SYNC_REJECTION].join('\n')); + expect(code, stderr).toBe(0); + expect(stdout).toBe('still running\n'); + expect(stderr).toBe('Wallet.Sync: Internal Server Error (a transient wallet SDK error; the SDK retries)\n'); + }); + + it("with it, the rejection goes to the program's onWarning when it gives one", async () => { + const { code, stdout, stderr } = await runProgram(runtime, [ + importGuard, + "installSdkProcessGuard({ onWarning: (tag, message) => console.log('reported', tag, message) });", + FLOATING_SYNC_REJECTION, + ].join('\n')); + expect(code, stderr).toBe(0); + expect(stdout).toBe('reported Wallet.Sync Internal Server Error\nstill running\n'); + expect(stderr).toBe(''); + }); + + it('with it, a real error still exits 1', async () => { + const { code, stdout, stderr } = await runProgram(runtime, [ + importGuard, + 'installSdkProcessGuard();', + "Promise.reject(new Error('a real failure'));", + "setTimeout(() => console.log('still running'), 200);", + ].join('\n')); + expect(code).toBe(1); + expect(stderr).toContain('a real failure'); + expect(stdout).not.toContain('still running'); + }); + + it('importing "./process" installs nothing: no handler, the console untouched, and the rejection still kills', async () => { + const { code, stdout } = await runProgram(runtime, [ + 'const before = { handlers: process.listenerCount("unhandledRejection"), error: console.error, warn: console.warn };', + `await import(${JSON.stringify(PROCESS_ENTRY)});`, + 'console.log(JSON.stringify({ handlers: process.listenerCount("unhandledRejection") - before.handlers, error: console.error === before.error, warn: console.warn === before.warn }));', + FLOATING_SYNC_REJECTION, + ].join('\n')); + expect(code).toBe(1); + expect(stdout).toBe('{"handlers":0,"error":true,"warn":true}\n'); + }); + + it('uninstall gives the process back: its handler gone, the console restored, and the rejection kills again', async () => { + const { code, stdout } = await runProgram(runtime, [ + importGuard, + 'const before = { handlers: process.listenerCount("unhandledRejection"), error: console.error, warn: console.warn };', + 'const guard = installSdkProcessGuard({ console: true });', + 'const installed = { handlers: process.listenerCount("unhandledRejection") - before.handlers, error: console.error === before.error, warn: console.warn === before.warn };', + 'guard.uninstall();', + 'const uninstalled = { handlers: process.listenerCount("unhandledRejection") - before.handlers, error: console.error === before.error, warn: console.warn === before.warn };', + 'console.log(JSON.stringify({ installed, uninstalled }));', + FLOATING_SYNC_REJECTION, + ].join('\n')); + expect(code).toBe(1); + expect(JSON.parse(stdout.trim())).toEqual({ + installed: { handlers: 1, error: false, warn: false }, + uninstalled: { handlers: 0, error: true, warn: true }, + }); + }); +}); diff --git a/packages/cli-core/src/__tests__/readme-process.test.ts b/packages/cli-core/src/__tests__/readme-process.test.ts new file mode 100644 index 00000000..218126b9 --- /dev/null +++ b/packages/cli-core/src/__tests__/readme-process.test.ts @@ -0,0 +1,95 @@ +// The README's "Your process" setup runs as it is written: its code block, in +// a child process of its own, with only the engine standing in. The stand-in +// is the real beta engine whose openConnector, instead of syncing a wallet, +// lets a transient Wallet.Sync rejection escape (as the SDK does mid-sync) and +// hands back a connector answering the balance reads. The program must survive +// the rejection, see it as its session's warning, print the balances, stop the +// wallet on close, and end by itself. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { spawn } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const ROOT = resolve(import.meta.dirname, '..', '..', '..', '..'); +const README = resolve(import.meta.dirname, '..', '..', 'README.md'); +const BETA_ENGINE = join(ROOT, 'packages', 'engine-beta', 'src', 'index.ts'); +const ENGINE_SPECIFIER = '@kuiralabs/midnight-engine-beta'; +const NIGHT = '00'.repeat(32); + +/** The README's setup block: the first js block under "### The setup". */ +function setupBlock(): string { + const readme = readFileSync(README, 'utf8'); + const section = readme.slice(readme.indexOf('### The setup')); + const block = /```js\n([\s\S]*?)```/.exec(section); + if (block === null) throw new Error('README.md has no js block under "### The setup"'); + return block[1]!; +} + +/** The beta engine, its openConnector standing in for a wallet sync. */ +const STAND_IN_ENGINE = ` +import { createBetaEngine as createRealEngine } from ${JSON.stringify(BETA_ENGINE)}; +export function createBetaEngine(host) { + const engine = createRealEngine(host); + return { ...engine, wallet: { ...engine.wallet, async openConnector(options) { + // The SDK's transient failure, escaping as an unhandled rejection while it syncs. + Promise.reject(Object.assign(new Error('Internal Server Error'), { _tag: 'Wallet.Sync' })); + await new Promise((resolve) => setTimeout(resolve, 50)); + const answers = { getUnshieldedBalances: { '${NIGHT}': 5n }, getShieldedBalances: {}, getDustBalance: { balance: 1n } }; + const handlers = Object.fromEntries(Object.entries(answers).map(([method, answer]) => [method, async () => answer])); + options.onMessage('stand-in wallet opened for ' + options.network); + return { connector: { handlers, revertPendingTxs: async () => {}, dispose: () => {} }, stop: async () => { console.error('stand-in wallet stopped'); } }; + } } }; +} +`; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'mn-readme-process-')); + // The program resolves the packages as one installed beside it would. + symlinkSync(join(ROOT, 'node_modules'), join(dir, 'node_modules')); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +function runSetup(): Promise<{ code: number | null; stdout: string; stderr: string }> { + const block = setupBlock(); + if (!block.includes(`'${ENGINE_SPECIFIER}'`)) throw new Error(`the setup block no longer imports ${ENGINE_SPECIFIER}`); + writeFileSync(join(dir, 'stand-in-engine.mjs'), STAND_IN_ENGINE); + writeFileSync(join(dir, 'program.mjs'), block.replace(`'${ENGINE_SPECIFIER}'`, "'./stand-in-engine.mjs'")); + return new Promise((done) => { + // HOME is the test's folder: the program's state root (~/.my-app) is under it, never the real one. + const child = spawn(process.execPath, ['--import', 'tsx', 'program.mjs'], { + cwd: dir, + env: { ...process.env, HOME: dir, WALLET_SEED: '07'.repeat(32) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + const hung = setTimeout(() => child.kill('SIGKILL'), 60_000); + child.on('exit', (code) => { + clearTimeout(hung); + done({ code, stdout, stderr }); + }); + }); +} + +describe("the README's process setup", () => { + it('opens the wallet, survives the SDK rejection as its warning, prints the balances, closes, and ends by itself', async () => { + const { code, stdout, stderr } = await runSetup(); + expect(code, stderr).toBe(0); + expect(stdout).toContain(`'${NIGHT}': 5n`); + expect(stdout).toContain('dust: 1n'); + expect(stderr).toContain('stand-in wallet opened for stagenet'); + expect(stderr).toContain('SDK: Internal Server Error'); + expect(stderr).not.toContain('Unhandled rejection'); + expect(stderr).toContain('stand-in wallet stopped'); + }); + + it('is about 15 lines of setup: the block stays short', () => { + const lines = setupBlock().split('\n').filter((line) => line.trim() !== ''); + expect(lines.length).toBeLessThanOrEqual(20); + }); +}); diff --git a/packages/cli-core/src/__tests__/sdk-process-guard.test.ts b/packages/cli-core/src/__tests__/sdk-process-guard.test.ts new file mode 100644 index 00000000..65a90429 --- /dev/null +++ b/packages/cli-core/src/__tests__/sdk-process-guard.test.ts @@ -0,0 +1,211 @@ +// The guard against the wallet SDK's transient rejections, core's host-called +// process code, in a child process of its own: a transient Wallet.* rejection +// reaches the call listening for it and the run goes on; any other rejection +// still exits 1. Here as mn's shell installs it (lib/cli-host.ts); its +// defaults, as a program meets them, are process-guard-program.test.ts's. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const ROOT = resolve(import.meta.dirname, '..', '..', '..', '..'); +/** Core's "./process" entry point, by its source. */ +const GUARD = resolve(import.meta.dirname, '..', 'process.ts'); +let dir: string; + +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mn-process-guard-')); }); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe("the guard as mn's shell installs it (console filters on, a rejection outside any call exits)", () => { + const run = (body: string) => { + const script = join(dir, 'noise.mjs'); + writeFileSync(script, [ + `const { installSdkProcessGuard } = await import(${JSON.stringify(GUARD)});`, + `const { WebSocket, WebSocketServer } = await import(${JSON.stringify(join(ROOT, 'node_modules/ws/wrapper.mjs'))});`, + "const { calls } = installSdkProcessGuard({ console: true, outsideCalls: 'exit' });", + // A call that starts listening and stays open, as a library inside it does. What + // the script raises at its top level comes from outside any call: it carries no identity. + 'const listen = (listener) => calls.run(async (warnings) => warnings.listen(listener));', + body, + ].join('\n')); + return spawnSync(process.execPath, ['--import', 'tsx', script], { cwd: ROOT, encoding: 'utf8', timeout: 60_000 }); + }; + + it('hands a transient Wallet.* rejection to the listening library and goes on', () => { + const result = run([ + "await listen((tag, message) => console.log('warned', tag, message));", + "Promise.reject(Object.assign(new Error('Internal Server Error'), { _tag: 'Wallet.Sync' }));", + "console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", + "setTimeout(() => console.log('still running'), 50);", + ].join('\n')); + expect(result.status).toBe(0); + expect(result.stdout).toBe('warned Wallet.Sync Internal Server Error\nstill running\n'); + expect(result.stderr).not.toContain('RPC-CORE'); + }); + + it("hands the SDK's Wallet.* console.error traces, object or string, to the listener, and prints anything else", () => { + const result = run([ + "await listen((tag, message) => console.log('warned', tag, message));", + "console.error({ _tag: 'Wallet.Sync', message: 'Internal Server Error' });", + "console.error('Wallet.Sync: Internal Server Error\\n at somewhere');", + "console.error('a real problem');", + ].join('\n')); + expect(result.status).toBe(0); + expect(result.stdout).toBe('warned Wallet.Sync Internal Server Error\nwarned Wallet.Sync transient error\n'); + expect(result.stderr).toBe('a real problem\n'); + }); + + it('touches nothing while no call listens: SDK traces and RPC noise print as they would without the guard', () => { + const result = run([ + "console.error({ _tag: 'Wallet.Sync', message: 'Internal Server Error' });", + "console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", + "const stop = await listen(undefined);", + "console.warn('RPC-CORE: kept off while listening');", + "stop();", + ].join('\n')); + expect(result.status).toBe(0); + expect(result.stderr).toContain('Wallet.Sync'); + expect(result.stderr).toContain('RPC-CORE: submitAndWatchExtrinsic'); + expect(result.stderr).not.toContain('kept off while listening'); + }); + + it('exits 1 on a Wallet.* rejection while no call listens, as Node does without the guard', () => { + const result = run("Promise.reject(Object.assign(new Error('Internal Server Error'), { _tag: 'Wallet.Sync' }));\nsetTimeout(() => console.log('still running'), 500);"); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + }); + + it('still exits 1 on a rejection that is only a string, even one starting Wallet.', () => { + const result = run("await listen(() => console.log('warned'));\nPromise.reject('Wallet.Sync: not an SDK error object');\nsetTimeout(() => console.log('still running'), 500);"); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + }); + + it('still exits 1 on any other unhandled rejection', () => { + const result = run("Promise.reject(new Error('a real failure'));\nsetTimeout(() => console.log('still running'), 500);"); + expect(result.status).toBe(1); + expect(result.stderr).toContain('a real failure'); + expect(result.stdout).not.toContain('still running'); + }); +}); + +// Each call's SDK warnings are its own. Regression: one listener +// stack for the process, whose newest listener got every warning, so two +// calls at once in the MCP server got each other's. +describe('the guard gives each call its own SDK warnings', () => { + const run = (body: string) => { + const script = join(dir, 'calls.mjs'); + writeFileSync(script, [ + `const { installSdkProcessGuard } = await import(${JSON.stringify(GUARD)});`, + `const { WebSocket, WebSocketServer } = await import(${JSON.stringify(join(ROOT, 'node_modules/ws/wrapper.mjs'))});`, + "const { calls } = installSdkProcessGuard({ console: true, outsideCalls: 'exit' });", + 'const listen = (listener) => calls.run(async (warnings) => warnings.listen(listener));', + "const sdkError = (message, tag = 'Wallet.Sync') => Object.assign(new Error(message), { _tag: tag });", + 'const said = [];', + body, + ].join('\n')); + return spawnSync(process.execPath, ['--import', 'tsx', script], { cwd: ROOT, encoding: 'utf8', timeout: 60_000 }); + }; + + it('two calls at once: what each raises from its timers and its WebSocket callbacks reaches it alone, and none reaches the terminal', () => { + const result = run([ + // A server outside both calls: it answers each socket from its own callbacks, a little later. + 'const server = new WebSocketServer({ port: 0 });', + "await new Promise((resolve) => server.once('listening', resolve));", + "server.on('connection', (socket) => socket.on('message', (m) => setTimeout(() => socket.send(String(m)), 5)));", + 'const call = (name) => calls.run(async (warnings) => {', + ' const stop = warnings.listen((tag, message) => said.push(`${name} got ${tag} ${message}`));', + ' await new Promise((done) => {', + ' setTimeout(() => Promise.reject(sdkError(`${name}: timer rejection`)), 10);', + " setTimeout(() => console.error({ _tag: 'Wallet.Sync', message: `${name}: timer trace` }), 15);", + " setInterval(function tick() { console.error({ _tag: 'Wallet.Sync', message: `${name}: interval trace` }); clearInterval(this); }, 20);", + ' const socket = new WebSocket(`ws://127.0.0.1:${server.address().port}`);', + " socket.on('open', () => socket.send(name));", + " socket.on('message', () => {", + " console.error({ _tag: 'Wallet.Sync', message: `${name}: socket trace` });", + " Promise.reject(sdkError(`${name}: socket rejection`, 'Wallet.Indexer'));", + " console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", + ' socket.close();', + ' setTimeout(done, 40);', + ' });', + ' });', + ' stop();', + '});', + "await Promise.all([call('a'), call('b')]);", + 'server.close();', + "console.log(said.sort().join('\\n'));", + ].join('\n')); + expect(result.status).toBe(0); + expect(result.stdout.trim().split('\n')).toEqual([ + 'a got Wallet.Indexer a: socket rejection', + 'a got Wallet.Sync a: interval trace', + 'a got Wallet.Sync a: socket trace', + 'a got Wallet.Sync a: timer rejection', + 'a got Wallet.Sync a: timer trace', + 'b got Wallet.Indexer b: socket rejection', + 'b got Wallet.Sync b: interval trace', + 'b got Wallet.Sync b: socket trace', + 'b got Wallet.Sync b: timer rejection', + 'b got Wallet.Sync b: timer trace', + ]); + expect(result.stderr).toBe(''); + }); + + it("goes to the newest listener of the call that raised it, and to no other call's", () => { + const result = run([ + "await listen((tag, message) => said.push(`other call: ${message}`));", + 'await calls.run(async (warnings) => {', + " warnings.listen((tag, message) => said.push(`outer: ${message}`));", + " const stopInner = warnings.listen((tag, message) => said.push(`inner: ${message}`));", + " console.error({ _tag: 'Wallet.Sync', message: 'first' });", + ' stopInner();', + " console.error({ _tag: 'Wallet.Sync', message: 'second' });", + '});', + 'console.log(JSON.stringify(said));', + ].join('\n')); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toEqual(['inner: first', 'outer: second']); + }); + + it("a call's warning after it stopped listening goes to no other call, and stays off the terminal while one listens", () => { + const result = run([ + "await listen((tag, message) => said.push(`other call: ${message}`));", + 'await calls.run(async (warnings) => {', + ' warnings.listen(undefined)();', + " console.error({ _tag: 'Wallet.Sync', message: 'after it stopped' });", + " await new Promise((resolve) => { Promise.reject(sdkError('rejected after it stopped')); setTimeout(resolve, 20); });", + '});', + 'console.log(JSON.stringify(said));', + ].join('\n')); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([]); + expect(result.stderr).toBe(''); + }); + + it('a warning from outside any call goes to the one call listening', () => { + const result = run([ + "await listen((tag, message) => said.push(`the call: ${message}`));", + "console.error({ _tag: 'Wallet.Sync', message: 'from nowhere' });", + "Promise.reject(sdkError('rejected from nowhere'));", + 'setTimeout(() => console.log(JSON.stringify(said)), 50);', + ].join('\n')); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toEqual(['the call: from nowhere', 'the call: rejected from nowhere']); + }); + + it('a warning from outside any call while several listen goes to none of them, and stays off the terminal', () => { + const result = run([ + "await listen((tag, message) => said.push(`a: ${message}`));", + "await listen((tag, message) => said.push(`b: ${message}`));", + "console.error({ _tag: 'Wallet.Sync', message: 'from nowhere' });", + "Promise.reject(sdkError('rejected from nowhere'));", + "console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", + 'setTimeout(() => console.log(JSON.stringify(said)), 50);', + ].join('\n')); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([]); + expect(result.stderr).toBe(''); + }); +}); diff --git a/packages/cli-core/src/__tests__/sync-heap.test.ts b/packages/cli-core/src/__tests__/sync-heap.test.ts new file mode 100644 index 00000000..91ab3538 --- /dev/null +++ b/packages/cli-core/src/__tests__/sync-heap.test.ts @@ -0,0 +1,74 @@ +// The heap a cold wallet sync needs: the limit to ask for (pure), and the +// advice for this process, which names the flag that sets it. + +import v8 from 'node:v8'; +import os from 'node:os'; +import { describe, it, expect } from 'vitest'; +import { syncHeapAdvice, syncHeapTargetMb } from '../process/sync-heap.ts'; +import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB } from '../lib/constants.ts'; + +describe('syncHeapTargetMb', () => { + // The OOM repro: a 128 GB box with Node's default ~4.3 GB old-space cap. + it('bumps to the desired target when RAM and current limit allow', () => { + expect(syncHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288 })) + .toBe(SYNC_HEAP_TARGET_MB); + }); + + it('returns null when the current limit already has enough headroom', () => { + // e.g. the user already raised the heap via NODE_OPTIONS — don't re-exec. + expect(syncHeapTargetMb({ totalMb: 131072, currentLimitMb: 16384 })).toBeNull(); + }); + + it('caps the target at the RAM fraction on small machines', () => { + // 8 GB machine: 70% = 5734 MB, below the 12 GB desired. + expect(syncHeapTargetMb({ totalMb: 8192, currentLimitMb: 4288 })) + .toBe(Math.floor(8192 * SYNC_HEAP_RAM_FRACTION)); + }); + + it('returns null when the RAM-capped target is not a worthwhile gain', () => { + // 6 GB machine: 70% = 4300 MB, only ~12 MB over the current 4288 — below the + // min-gain threshold, so re-exec isn't worth it. + expect(syncHeapTargetMb({ totalMb: 6144, currentLimitMb: 4288 })).toBeNull(); + }); + + it('respects the min-gain threshold exactly at the boundary', () => { + const current = 4288; + // target would be current + minGain exactly → not a *worthwhile* gain (<=). + const totalMb = Math.ceil((current + SYNC_HEAP_MIN_GAIN_MB) / SYNC_HEAP_RAM_FRACTION); + expect(syncHeapTargetMb({ totalMb, currentLimitMb: current })).toBeNull(); + // one MB more of RAM tips it over. + expect(syncHeapTargetMb({ totalMb: totalMb + 2, currentLimitMb: current })).not.toBeNull(); + }); + + it('honors an explicit desired override', () => { + expect(syncHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288, desiredMb: 8192 })) + .toBe(8192); + }); + + it('rejects a non-positive or NaN desired override', () => { + expect(syncHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288, desiredMb: 0 })).toBeNull(); + expect(syncHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288, desiredMb: NaN })).toBeNull(); + }); + + it('returns null for bogus total memory', () => { + expect(syncHeapTargetMb({ totalMb: 0, currentLimitMb: 4288 })).toBeNull(); + expect(syncHeapTargetMb({ totalMb: NaN, currentLimitMb: 4288 })).toBeNull(); + }); +}); + +describe('syncHeapAdvice', () => { + const MB = 1024 * 1024; + const totalMb = Math.floor(os.totalmem() / MB); + const currentLimitMb = Math.floor(v8.getHeapStatistics().heap_size_limit / MB); + + it("reads this machine's memory and this process's heap, and names the flag that sets the limit", () => { + // Just above the gain that is worth a restart: advised as asked wherever the machine's memory allows it. + const desiredMb = currentLimitMb + SYNC_HEAP_MIN_GAIN_MB + 1; + const fits = desiredMb <= Math.floor(totalMb * SYNC_HEAP_RAM_FRACTION); + expect(syncHeapAdvice({ desiredMb })).toEqual(fits ? { maxOldSpaceMb: desiredMb, nodeOptions: `--max-old-space-size=${desiredMb}` } : null); + }); + + it('advises nothing when the heap this process has will do', () => { + expect(syncHeapAdvice({ desiredMb: currentLimitMb })).toBeNull(); + }); +}); diff --git a/packages/cli-core/src/index.ts b/packages/cli-core/src/index.ts index 22daf643..01d4fbc1 100644 --- a/packages/cli-core/src/index.ts +++ b/packages/cli-core/src/index.ts @@ -4,7 +4,8 @@ // wallet session and swap offer types, and the rest the packages above core // import. Each name is listed, so the API is what this file says. // Engine implementors also import "./engine"; terminal output is "./ui"; -// core's command, codes and guidance are "./commands". +// core's command, codes and guidance are "./commands"; what a host does to its +// own process (the SDK rejection guard, the sync heap) is "./process". export { assembleGuidance, codeGuidancePieces, GuidanceError, type GuidancePiece, type GuidanceText, @@ -112,4 +113,4 @@ export { checkTerms, type OfferContents, type SwapLeg, type SwapTerms, TermsMism export { isTransportFailure, withTransportCode } from './lib/transport-failure.ts'; export { type VerboseLog } from './lib/verbose.ts'; export { clearWalletCache } from './lib/wallet-cache.ts'; -export { sessionOver, type WalletSession } from './lib/wallet-session.ts'; +export { openWalletSession, type OpenWalletSessionOptions, sessionOver, type WalletSession } from './lib/wallet-session.ts'; diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index 36aa3b74..4129d400 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -4,8 +4,8 @@ // and the payer and protectors its caller gives. Nothing about a call lives in // a module global, so two calls in one process cannot mix. The context reaches // libraries as explicit parameters, never as ambient per-call storage; the one -// exception is the shell's, which tags the SDK's noise with the call that -// raised it (lib/sdk-noise.ts). +// exception is the host's process guard, which tags the SDK's noise with the +// call that raised it (core's "./process", process/sdk-process-guard.ts). // // The CLI builds one from the process's streams, its signal and --verbose // (lib/command-dispatch.ts); the MCP server builds one per request diff --git a/packages/cli-core/src/lib/constants.ts b/packages/cli-core/src/lib/constants.ts index 4c136cff..d9a8ed52 100644 --- a/packages/cli-core/src/lib/constants.ts +++ b/packages/cli-core/src/lib/constants.ts @@ -56,7 +56,7 @@ export const BALANCE_CHECK_TIMEOUT_MS = 60_000; // 1 minute — GraphQL balance // default old-space cap (~4 GB) GC can't keep pace with the allocation rate and the // process dies with "JavaScript heap out of memory" before it can finish — and write // the cache that makes every later run cheap. Measured cold preprod shielded-sync -// high-water: ~8.4 GB. lib/heap-guard.ts re-execs sync commands with this headroom. +// high-water: ~8.4 GB. process/sync-heap.ts advises this headroom; mn's shell re-execs sync commands with it. // Note: the cap must sit comfortably *above* the high-water, not just at it — // crowding the limit makes V8 thrash on full GCs, which starves the sync loop // and trips the per-attempt timeout. A 12 GB cap timed out; 16 GB completes. diff --git a/packages/cli-core/src/lib/sdk-warnings.ts b/packages/cli-core/src/lib/sdk-warnings.ts index 91c11827..bdd370f7 100644 --- a/packages/cli-core/src/lib/sdk-warnings.ts +++ b/packages/cli-core/src/lib/sdk-warnings.ts @@ -1,12 +1,12 @@ // The SDK's transient errors (Wallet.Sync: Internal Server Error, …) surface -// as unhandled rejections and console.error calls, which the shell filters -// (sdk-noise.ts) while some call listens. A call that runs the SDK listens -// through its context (ctx.sdkWarnings) for its length, to show them as -// progress ("…, retrying") or only to keep them off the terminal; it never -// touches the process itself. +// as unhandled rejections and console.error calls, which the host's process +// guard (core's "./process") takes while some call listens. A call that runs +// the SDK listens through its context (ctx.sdkWarnings) for its length, to +// show them as progress ("…, retrying") or only to keep them off the +// terminal; it never touches the process itself. // // Each call's warnings are its own. The host keeps one router; each -// call it runs is opened on it, and the shell tags the noise raised while a +// call it runs is opened on it, and the guard tags the noise raised while a // call runs with that call's identity. A warning with an identity goes to // that call's newest listener, and to no other call. One without (raised // where the identity didn't carry) goes to the one call listening; with @@ -77,7 +77,7 @@ export function createSdkWarningRouter(): SdkWarningRouter { }; } -/** How a runner gives each call it runs its SDK warnings. The host's knows which call raised one (sdk-noise.ts). */ +/** How a runner gives each call it runs its SDK warnings. The host's process guard knows which call raised one (process/sdk-process-guard.ts). */ export interface SdkWarningCalls { /** Runs one call, its warnings given to `run`. */ run(run: (warnings: CallSdkWarnings) => Promise): Promise; diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index 8d81e08f..ede4d0f5 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -21,6 +21,7 @@ import { throwIfCancelled } from './errors.ts'; import { isColdStartRace, toEngineError } from './sdk-errors.ts'; import type { SwapLeg } from './swap-offer.ts'; import type { OpenOffer } from './open-offers.ts'; +import type { CallSdkWarnings } from './sdk-warnings.ts'; /** The calls a session makes, under one connection name for the connector's pending transactions. */ const SESSION_CONNECTION = 'wallet-session'; @@ -247,17 +248,45 @@ export interface OpenWalletSessionOptions { dustWaitMs?: number; /** Cancels the open: what was started is stopped. */ signal?: AbortSignal; - /** What the open is doing now, for a progress line. */ + /** What the open is doing now, for a progress line; with `sdkWarnings`, also the SDK's transient warnings, as `SDK: `. */ onMessage?: (message: string) => void; + /** + * Where the SDK's transient warnings go (a call's, from the host's process + * guard): the session listens from the open until close(), so the guard + * hands them to it rather than reporting or exiting. + */ + sdkWarnings?: CallSdkWarnings; } /** * Opens a seed's wallet on a network: synced, its Dust ready, with the - * network's engine from `options.engines`. + * network's engine from `options.engines`. With `sdkWarnings`, the session + * listens for the SDK's transient warnings from the open until close(). */ export async function openWalletSession(options: OpenWalletSessionOptions): Promise { - const { seed, network, root, signal } = options; + const { signal, onMessage } = options; throwIfCancelled(signal); + const stopListening = options.sdkWarnings?.listen(onMessage === undefined ? undefined : (_tag, message) => onMessage(`SDK: ${message}`)) ?? (() => {}); + try { + const session = await openSession(options); + return { + ...session, + async close() { + try { + await session.close(); + } finally { + stopListening(); + } + }, + }; + } catch (err) { + stopListening(); + throw err; + } +} + +async function openSession(options: OpenWalletSessionOptions): Promise { + const { seed, network, root, signal } = options; const networkConfig = options.networkConfig ?? resolveNetwork({ args: { command: 'wallet-session', subcommand: '', positionals: [], flags: { network } }, configDir: root }, options.settings ?? settingsFromEnvironment({})).config; const engine = await options.engines.load(sdkSetOf(network, root)); diff --git a/packages/cli-core/src/process.ts b/packages/cli-core/src/process.ts new file mode 100644 index 00000000..3f518ac8 --- /dev/null +++ b/packages/cli-core/src/process.ts @@ -0,0 +1,8 @@ +// @kuiralabs/midnight-cli-core/process: what a host does to its own process +// for the wallet SDK, and the only code in the packages that touches the +// process. Nothing here runs on import, and no package imports it: a host +// calls it. The guard against the SDK's transient rejections (and, as an +// option, its console noise), and the heap a cold wallet sync needs. + +export { installSdkProcessGuard, type SdkProcessGuard, type SdkProcessGuardOptions } from './process/sdk-process-guard.ts'; +export { type SyncHeapAdvice, syncHeapAdvice, syncHeapTargetMb, type SyncHeapTargetOptions } from './process/sync-heap.ts'; diff --git a/packages/cli-core/src/process/sdk-process-guard.ts b/packages/cli-core/src/process/sdk-process-guard.ts new file mode 100644 index 00000000..bd8f30c0 --- /dev/null +++ b/packages/cli-core/src/process/sdk-process-guard.ts @@ -0,0 +1,123 @@ +// The guard against the wallet SDK's transient rejections, for a host to +// install on its own process. No library installs it: only the host calls +// it, through core's "./process" entry point, which no package imports. +// +// During a sync the SDK lets transient failures (Wallet.Sync: Internal Server +// Error, a dropped indexer socket) escape as unhandled rejections while it +// retries the work itself. Node exits 1 on an unhandled rejection, so a +// program without the guard dies mid-sync. With it: +// +// - A transient Wallet.* rejection goes to the call listening for the SDK's +// warnings (a CallSdkWarnings from the guard's calls), and the run goes +// on. With no call listening, `outsideCalls` decides: 'report' hands it to +// `onWarning` and the run goes on; 'exit' prints it and exits 1, as Node +// does without the guard. Any other unhandled rejection is printed and +// exits 1. +// - With `console`, while a call listens, the SDK's Wallet.* traces on +// console.error go to that call too, and polkadot-js's RPC-CORE lines on +// console.warn and console.error (one per failed submit) are dropped. At +// any other time the console is untouched. +// +// Which call a warning belongs to: each call runs inside its own +// AsyncLocalStorage store, so a warning raised while it runs carries its +// identity, and the router hands it to that call alone (lib/sdk-warnings.ts). +// Measured on 31 Oct 2026 with two calls at once: on Node (v25) the identity +// survives the SDK's WebSocket callbacks (ws, polkadot-js, graphql-ws through +// the SDK's subscription client), Effect fibers, timers, RxJS, and reaches the +// unhandledRejection handler; under bun (1.3) it survives timers, RxJS and +// Effect fibers but is lost on everything resumed from a WebSocket. A warning +// that lost it is never given to the wrong call: the router gives it to the +// one call listening, or to none. + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls, type SdkWarningListener } from '../lib/sdk-warnings.ts'; + +export interface SdkProcessGuardOptions { + /** While a call listens, hand the SDK's Wallet.* console.error traces to it and drop polkadot-js's RPC-CORE lines. Off by default: the console is left alone. */ + readonly console?: boolean; + /** + * A transient Wallet.* rejection while no call listens: 'report' (the + * default) hands it to `onWarning` and the program goes on; 'exit' prints + * it and exits 1, as Node does without the guard. + */ + readonly outsideCalls?: 'exit' | 'report'; + /** Where 'report' sends a transient rejection no call listens for; a line on console.warn when not given. */ + readonly onWarning?: (tag: string, message: string) => void; +} + +export interface SdkProcessGuard { + /** The calls the host runs, each listening for its own SDK warnings: a host's `sdkWarnings`. */ + readonly calls: SdkWarningCalls; + /** Takes the guard off the process: its rejection handler goes and the console is given back. */ + uninstall(): void; +} + +/** The line a reported warning prints when the host gives no `onWarning`. */ +const reportOnConsole = (warn: (...args: unknown[]) => void): SdkWarningListener => + (tag, message) => warn(`${tag}: ${message} (a transient wallet SDK error; the SDK retries)`); + +/** + * Installs the guard on this process. Each call installs one more: a host + * calls it once, at start, before the first wallet sync. + */ +export function installSdkProcessGuard(options: SdkProcessGuardOptions = {}): SdkProcessGuard { + const outsideCalls = options.outsideCalls ?? 'report'; + const router = createSdkWarningRouter(); + const runningCall = new AsyncLocalStorage(); + const report = (tag: string, message: string): void => router.route(runningCall.getStore(), tag, message); + + const originalError = console.error; + const originalWarn = console.warn; + const onWarning = options.onWarning ?? reportOnConsole(originalWarn); + const isRpcNoise = (args: unknown[]) => args.some((a) => String(a).includes('RPC-CORE')); + + const onRejection = (reason: unknown): void => { + // A rejection that is only a string is never the SDK's: its errors are objects with a _tag. + const warning = typeof reason === 'string' ? null : sdkTransientWarning(reason); + if (warning !== null && router.isListening()) { + report(warning.tag, warning.message); + return; + } + if (warning !== null && outsideCalls === 'report') { + onWarning(warning.tag, warning.message); + return; + } + originalError('Unhandled rejection:', reason); + process.exit(1); + }; + process.on('unhandledRejection', onRejection); + + const patchedError = (...args: unknown[]) => { + if (!router.isListening()) return originalError(...args); + const warning = sdkTransientWarning(args[0]); + if (warning !== null) { + report(warning.tag, warning.message); + return; + } + if (isRpcNoise(args)) return; + originalError(...args); + }; + const patchedWarn = (...args: unknown[]) => { + if (router.isListening() && isRpcNoise(args)) return; + originalWarn(...args); + }; + if (options.console === true) { + console.error = patchedError; + console.warn = patchedWarn; + } + + return { + calls: { + run: (run) => { + const call = router.openCall(); + return runningCall.run(call.id, () => run(call.warnings)); + }, + }, + uninstall() { + process.off('unhandledRejection', onRejection); + // Given back only where nobody replaced them since. + if (console.error === patchedError) console.error = originalError; + if (console.warn === patchedWarn) console.warn = originalWarn; + }, + }; +} diff --git a/packages/cli-core/src/process/sync-heap.ts b/packages/cli-core/src/process/sync-heap.ts new file mode 100644 index 00000000..b56366ac --- /dev/null +++ b/packages/cli-core/src/process/sync-heap.ts @@ -0,0 +1,77 @@ +// The heap a cold wallet sync needs, for a host to start its process with. +// +// The first shielded or Dust sync against a hosted network streams the whole +// chain's history through the wallet SDK. Its live working set is small (about +// 300 MB), but the scan allocates a stream of short-lived objects (about +// 8.4 GB on preprod); under Node's default old-space limit (about 4 GB) the +// collector can't keep pace and the process dies with "JavaScript heap out of +// memory" before it writes the cache that makes every later sync cheap. +// +// The limit is fixed when the runtime starts, so a host either starts with it +// (NODE_OPTIONS) or re-runs itself with it before loading the SDK, as mn's +// shell does. This module only says what limit to ask for; it starts nothing. + +import v8 from 'node:v8'; +import os from 'node:os'; +import { SYNC_HEAP_MIN_GAIN_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_TARGET_MB } from '../lib/constants.ts'; + +const MB = 1024 * 1024; + +export interface SyncHeapTargetOptions { + /** The machine's memory, in MB. */ + readonly totalMb: number; + /** The runtime's old-space limit now, in MB. */ + readonly currentLimitMb: number; + /** The limit wanted, in MB; SYNC_HEAP_TARGET_MB when not given. */ + readonly desiredMb?: number; + /** The share of the machine's memory the limit may take; SYNC_HEAP_RAM_FRACTION when not given. */ + readonly ramFraction?: number; + /** How far above the current limit a new one has to be to be worth a restart, in MB; SYNC_HEAP_MIN_GAIN_MB when not given. */ + readonly minGainMb?: number; +} + +/** + * The old-space limit (MB) to start a syncing process with, or null when the + * current one will do: never more than `ramFraction` of the machine's memory, + * and never a limit only `minGainMb` or less above the current one. + */ +export function syncHeapTargetMb(opts: SyncHeapTargetOptions): number | null { + const desired = opts.desiredMb ?? SYNC_HEAP_TARGET_MB; + const ramFraction = opts.ramFraction ?? SYNC_HEAP_RAM_FRACTION; + const minGain = opts.minGainMb ?? SYNC_HEAP_MIN_GAIN_MB; + + if (!Number.isFinite(desired) || desired <= 0) return null; + if (!Number.isFinite(opts.totalMb) || opts.totalMb <= 0) return null; + + const ramCap = Math.floor(opts.totalMb * ramFraction); + const target = Math.min(Math.floor(desired), ramCap); + if (target <= opts.currentLimitMb + minGain) return null; + return target; +} + +/** The limit to start a syncing process with, and the NODE_OPTIONS that set it. */ +export interface SyncHeapAdvice { + /** The old-space limit, in MB. */ + readonly maxOldSpaceMb: number; + /** The flag that sets it, for NODE_OPTIONS or the runtime's arguments: `--max-old-space-size=`. */ + readonly nodeOptions: string; +} + +/** + * Whether this process's heap is too small for a cold wallet sync on this + * machine, and if so the limit to start it with; null when it will do. + * `desiredMb` replaces SYNC_HEAP_TARGET_MB (on a small machine, say). + * + * Null under bun: its heap is JavaScriptCore's, which neither NODE_OPTIONS nor + * --max-old-space-size sets (bun 1.3 reports the same V8 statistics with or + * without them), so there is no flag to advise. + */ +export function syncHeapAdvice(options: { readonly desiredMb?: number } = {}): SyncHeapAdvice | null { + if (process.versions.bun !== undefined) return null; + const target = syncHeapTargetMb({ + totalMb: Math.floor(os.totalmem() / MB), + currentLimitMb: Math.floor(v8.getHeapStatistics().heap_size_limit / MB), + desiredMb: options.desiredMb, + }); + return target === null ? null : { maxOldSpaceMb: target, nodeOptions: `--max-old-space-size=${target}` }; +} diff --git a/packages/engine-beta/src/__tests__/facade-stop.test.ts b/packages/engine-beta/src/__tests__/facade-stop.test.ts new file mode 100644 index 00000000..babea61f --- /dev/null +++ b/packages/engine-beta/src/__tests__/facade-stop.test.ts @@ -0,0 +1,6 @@ +// The beta engine's facade, stopped, leaves nothing that keeps a program's process up (test-support/facade-stop-suite.ts). + +import { resolve } from 'node:path'; +import { facadeStopSuite } from '../../../../test-support/facade-stop-suite.ts'; + +facadeStopSuite({ set: 'beta', facadeModule: resolve(import.meta.dirname, '..', 'facade.ts') }); diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts index e2ec3936..52deb33e 100644 --- a/packages/engine-beta/src/facade.ts +++ b/packages/engine-beta/src/facade.ts @@ -17,6 +17,7 @@ import { import * as ledger from '@midnightntwrk/ledger-v9'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk-abstractions'; import * as rx from 'rxjs'; +import { makeDefaultSubmissionService } from '@midnightntwrk/wallet-sdk-capabilities/submission'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; @@ -111,6 +112,7 @@ export async function buildFacade( // does that. const initFresh = () => WalletFacade.init({ configuration, + submissionService: (config) => submissionOnDemand(config.relayURL), shielded: (cfg) => ShieldedWallet(cfg).startWithSecretKeys(secretKeys.shieldedSecretKeys), unshielded: (cfg) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(keystore)), dust: (cfg) => DustWallet(cfg).startWithSecretKey(secretKeys.dustSecretKey, ledger.LedgerParameters.initialParameters().dust), @@ -133,6 +135,7 @@ export async function buildFacade( try { facade = await WalletFacade.init({ configuration, + submissionService: (config) => submissionOnDemand(config.relayURL), shielded: (cfg) => ShieldedWallet(cfg).restore(effectiveCache.shielded), unshielded: (cfg) => UnshieldedWallet(cfg).restore(effectiveCache.unshielded), dust: (cfg) => DustWallet(cfg).restore(effectiveCache.dust), @@ -152,6 +155,28 @@ export async function buildFacade( return { facade, keystore, secretKeys, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; } +/** What the facade submits through, as WalletFacade.init takes it. */ +type FacadeSubmission = Awaited[0]['submissionService']>>>; + +/** + * The SDK's submission service, made on the first submit instead of when the + * facade is built. The SDK's own opens its node client at once, and its close() + * waits for that client to be ready: against a node that doesn't answer (down, + * or a wrong URL) close() never returns and polkadot-js reconnects every 2.5 s + * for good, so a program that closed its wallet never exits. Made on demand, a + * facade that submitted nothing holds no node connection, and closes at once. + */ +export function submissionOnDemand(relayURL: URL): FacadeSubmission { + let service: FacadeSubmission | undefined; + const submitting = (): FacadeSubmission => (service ??= makeDefaultSubmissionService({ relayURL })); + const submitTransaction = (transaction: Parameters[0], waitForStatus?: 'Submitted' | 'InBlock' | 'Finalized') => + submitting().submitTransaction(transaction, waitForStatus); + return { + submitTransaction: submitTransaction as FacadeSubmission['submitTransaction'], + close: async () => { await service?.close(); }, + }; +} + /** * Start the facade's wallets and background sync, exactly once. * @@ -641,16 +666,25 @@ export async function quickSync(bundle: FacadeBundle, syncMode: SyncMode = 'full ); } +/** How long stopFacade waits for the SDK's wallets to stop. */ +const STOP_TIMEOUT_MS = 5_000; + /** * Clean shutdown of the wallet facade. */ export async function stopFacade(bundle: FacadeBundle): Promise { bundle.keepAlive?.unsubscribe(); // Timeout facade.stop() — wallets may hang if in a bad state (e.g. dust wallet stuck). - // Don't block the caller forever; let the old facade be GC'd. - await Promise.race([ - bundle.facade.stop(), - new Promise(resolve => setTimeout(resolve, 5_000)), - ]); + // Don't block the caller forever; let the old facade be GC'd. The wait is + // cleared once the facade stops, so it doesn't keep the process up 5 s more. + let timer: ReturnType | undefined; + try { + await Promise.race([ + bundle.facade.stop(), + new Promise((resolve) => { timer = setTimeout(resolve, STOP_TIMEOUT_MS); }), + ]); + } finally { + clearTimeout(timer); + } } diff --git a/packages/engine-beta/src/transfer.ts b/packages/engine-beta/src/transfer.ts index 7c1a24d1..50bd7cf7 100644 --- a/packages/engine-beta/src/transfer.ts +++ b/packages/engine-beta/src/transfer.ts @@ -105,7 +105,7 @@ async function submitDustRegistration( * Each retry rebuilds the transaction with a newer timestamp, giving a * larger time delta and thus a larger allow_fee_payment. * - * The shell keeps the RPC noise off the terminal (sdk-noise.ts). + * The host's process guard keeps the RPC noise off the terminal (core's "./process", its console option). */ export async function registerNightUtxos( bundle: FacadeBundle, @@ -181,7 +181,7 @@ export async function registerNightUtxos( * outputs) can be registered later via `midnight dust register`. * * Used by: executeTransfer (transfer/airdrop commands), dustRegister command. - * The shell keeps the RPC noise off the terminal (sdk-noise.ts). + * The host's process guard keeps the RPC noise off the terminal (core's "./process", its console option). */ export async function ensureDust( bundle: FacadeBundle, diff --git a/packages/engine-rc/src/__tests__/facade-stop.test.ts b/packages/engine-rc/src/__tests__/facade-stop.test.ts new file mode 100644 index 00000000..ce0b515a --- /dev/null +++ b/packages/engine-rc/src/__tests__/facade-stop.test.ts @@ -0,0 +1,6 @@ +// The rc engine's facade, stopped, leaves nothing that keeps a program's process up (test-support/facade-stop-suite.ts). + +import { resolve } from 'node:path'; +import { facadeStopSuite } from '../../../../test-support/facade-stop-suite.ts'; + +facadeStopSuite({ set: 'rc', facadeModule: resolve(import.meta.dirname, '..', 'facade.ts') }); diff --git a/packages/engine-rc/src/__tests__/wallet-session.test.ts b/packages/engine-rc/src/__tests__/wallet-session.test.ts index 9b6265c5..de6ce04f 100644 --- a/packages/engine-rc/src/__tests__/wallet-session.test.ts +++ b/packages/engine-rc/src/__tests__/wallet-session.test.ts @@ -1,11 +1,18 @@ // The wallet session over the rc engine's DApp connector, its facade stubbed // at the SDK boundary: each operation answers in the session's own types, and -// closing reverts what was built but never submitted. +// closing reverts what was built but never submitted. A program opens one with +// openWalletSession, through its host's engine, listening for the SDK's +// warnings from the open until close(). -import { describe, it, expect, vi, beforeAll } from 'vitest'; +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; import * as rx from 'rxjs'; import { DustAddress, MidnightBech32m, ShieldedAddress, UnshieldedAddress } from '@midnightntwrk/wallet-sdk/address-format'; -import { sessionOver, type WalletSession, DustRequiredError, TransactionRefusedError, classifyError } from '@kuiralabs/midnight-cli-core'; +import { sessionOver, type WalletSession, DustRequiredError, TransactionRefusedError, classifyError, createHost, createSdkWarningRouter, openWalletSession, type Engine, type OpenWalletSessionOptions } from '@kuiralabs/midnight-cli-core'; +import type { OpenedConnector } from '@kuiralabs/midnight-cli-core/engine'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createRcEngine } from '../index.ts'; import type { TransactionDetail } from '@kuiralabs/midnight-cli-core/engine'; import { deriveShieldedAddress, deriveUnshieldedAddress } from '../derive-address.ts'; import { NO_TERMINAL, TEST_NETWORK_CONFIG, connectorStub } from '../../../../test-support/connector-stub.ts'; @@ -267,3 +274,95 @@ describe("a program's wallet session, in the error-code parity table", () => { expect(classifyError(err!, CORE_CODES)).toStrictEqual({ errorCode: 'STALE_UTXO', exitCode: 6 }); }); }); + +// What a program calls: the session opened through its host's engine. The rc +// engine is real but for its wallet's openConnector, which syncs a facade: here +// it gives the engine's own DApp connector over the facade stubbed at the SDK +// boundary, as the tests above build it. +describe('openWalletSession', () => { + const SEED = Buffer.from('00'.repeat(31) + '07', 'hex'); + let root: string; + beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'mn-open-session-')); }); + afterAll(() => rmSync(root, { recursive: true, force: true })); + + /** A host's engines over the rc engine, its openConnector standing in; what it was asked, and how often its connector stopped. */ + function rcEngines(open: (options: Parameters[0]) => Promise = async () => openedOverStub()) { + const asked: Parameters[0][] = []; + const host = createHost({ + paths: { stateRoot: root, home: root }, + engineLoader: async (_set, loading) => { + const engine = createRcEngine(loading); + return { ...engine, wallet: { ...engine.wallet, openConnector: (options) => { asked.push(options); return open(options); } } }; + }, + }); + return { engines: host.engines, asked }; + } + let stops = 0; + function openedOverStub(): OpenedConnector { + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ unshieldedBalances: { [NIGHT_RAW]: 5n }, dustBalance: 1n })) }); + (bundle.facade as unknown as { revert: () => Promise }).revert = async () => {}; + const connector = createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); + return { connector, stop: async () => { stops += 1; connector.dispose(); } }; + } + const options = (engines: OpenWalletSessionOptions['engines'], more: Partial = {}): OpenWalletSessionOptions => ({ + seed: SEED, network: 'undeployed', root, notice: NO_TERMINAL.notice, engines, networkConfig: TEST_NETWORK_CONFIG, ...more, + }); + + it("opens the seed's wallet through the network's engine and stops it on close", async () => { + const { engines, asked } = rcEngines(); + const before = stops; + const session = await openWalletSession(options(engines, { dustWaitMs: 1234 })); + expect(session.network).toBe('undeployed'); + expect(await session.balances()).toEqual({ unshielded: { [NIGHT_RAW]: 5n }, shielded: {}, dust: 1n }); + expect(asked).toHaveLength(1); + expect(asked[0]).toMatchObject({ seed: SEED, root, network: 'undeployed', networkConfig: TEST_NETWORK_CONFIG, address: deriveUnshieldedAddress(SEED, 'undeployed'), syncMode: 'full', dustWaitMs: 1234 }); + await session.close(); + expect(stops).toBe(before + 1); + }); + + it("listens for the SDK's warnings from the open until close, as progress lines", async () => { + const router = createSdkWarningRouter(); + const call = router.openCall(); + const said: string[] = []; + let listeningWhileOpening = false; + const { engines } = rcEngines(async () => { + listeningWhileOpening = router.isListening(); + router.route(call.id, 'Wallet.Sync', 'Internal Server Error'); + return openedOverStub(); + }); + const session = await openWalletSession(options(engines, { sdkWarnings: call.warnings, onMessage: (line) => said.push(line) })); + expect(listeningWhileOpening).toBe(true); + router.route(call.id, 'Wallet.Indexer', 'socket closed'); + expect(router.isListening()).toBe(true); + await session.close(); + expect(router.isListening()).toBe(false); + router.route(call.id, 'Wallet.Sync', 'after close'); + expect(said.filter((line) => line.startsWith('SDK: '))).toEqual(['SDK: Internal Server Error', 'SDK: socket closed']); + }); + + it('listens with no listener when given no progress callback: the warnings are only taken', async () => { + const router = createSdkWarningRouter(); + const call = router.openCall(); + const session = await openWalletSession(options(rcEngines().engines, { sdkWarnings: call.warnings })); + expect(router.isListening()).toBe(true); + await session.close(); + expect(router.isListening()).toBe(false); + }); + + it('stops listening when the open fails, and says why it failed', async () => { + const router = createSdkWarningRouter(); + const call = router.openCall(); + const { engines } = rcEngines(async () => { throw new Error('the indexer refused'); }); + await expect(openWalletSession(options(engines, { sdkWarnings: call.warnings }))).rejects.toThrow('the indexer refused'); + expect(router.isListening()).toBe(false); + }); + + it('refuses a cancelled open before anything listens or opens', async () => { + const router = createSdkWarningRouter(); + const call = router.openCall(); + const { engines, asked } = rcEngines(); + await expect(openWalletSession(options(engines, { sdkWarnings: call.warnings, signal: AbortSignal.abort() }))).rejects.toMatchObject({ name: 'CancelledError' }); + expect(router.isListening()).toBe(false); + expect(asked).toEqual([]); + }); +}); diff --git a/packages/engine-rc/src/facade.ts b/packages/engine-rc/src/facade.ts index acb83845..9b076d94 100644 --- a/packages/engine-rc/src/facade.ts +++ b/packages/engine-rc/src/facade.ts @@ -18,6 +18,7 @@ import { type WalletSeeds } from '@midnightntwrk/wallet-sdk/hd'; import * as ledger from '@midnightntwrk/ledger-v9'; import { InMemoryTransactionHistoryStorage } from '@midnightntwrk/wallet-sdk'; import * as rx from 'rxjs'; +import { makeDefaultSubmissionService } from '@midnightntwrk/wallet-sdk/capabilities/submission'; import { FORK_SCHEDULE } from './fork-schedule.ts'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; @@ -118,6 +119,7 @@ export async function buildFacade( // chain is on. It doesn't start syncing; startFacade does that. const initFresh = () => WalletFacade.init({ configuration, + submissionService: (config) => submissionOnDemand(config.relayURL), shielded: async (cfg) => (shielded = await ShieldedWallet(cfg).startWithSeed(seeds.shielded)), unshielded: (cfg) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(keystore)), dust: async (cfg) => (dust = await DustWallet(cfg).startWithSeed(seeds.dust)), @@ -140,6 +142,7 @@ export async function buildFacade( try { facade = await WalletFacade.init({ configuration, + submissionService: (config) => submissionOnDemand(config.relayURL), shielded: (cfg) => (shielded = ShieldedWallet(cfg).restore(effectiveCache.shielded)), unshielded: (cfg) => UnshieldedWallet(cfg).restore(effectiveCache.unshielded), dust: (cfg) => (dust = DustWallet(cfg).restore(effectiveCache.dust)), @@ -162,6 +165,28 @@ export async function buildFacade( return { facade, keystore, seeds, seedStartable: { shielded, dust }, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; } +/** What the facade submits through, as WalletFacade.init takes it. */ +type FacadeSubmission = Awaited[0]['submissionService']>>>; + +/** + * The SDK's submission service, made on the first submit instead of when the + * facade is built. The SDK's own opens its node client at once, and its close() + * waits for that client to be ready: against a node that doesn't answer (down, + * or a wrong URL) close() never returns and polkadot-js reconnects every 2.5 s + * for good, so a program that closed its wallet never exits. Made on demand, a + * facade that submitted nothing holds no node connection, and closes at once. + */ +export function submissionOnDemand(relayURL: URL): FacadeSubmission { + let service: FacadeSubmission | undefined; + const submitting = (): FacadeSubmission => (service ??= makeDefaultSubmissionService({ relayURL })); + const submitTransaction = (transaction: Parameters[0], waitForStatus?: 'Submitted' | 'InBlock' | 'Finalized') => + submitting().submitTransaction(transaction, waitForStatus); + return { + submitTransaction: submitTransaction as FacadeSubmission['submitTransaction'], + close: async () => { await service?.close(); }, + }; +} + /** * Start the facade's wallets and background sync, exactly once. * @@ -672,16 +697,25 @@ export async function quickSync(bundle: FacadeBundle, syncMode: SyncMode = 'full ); } +/** How long stopFacade waits for the SDK's wallets to stop. */ +const STOP_TIMEOUT_MS = 5_000; + /** * Clean shutdown of the wallet facade. */ export async function stopFacade(bundle: FacadeBundle): Promise { bundle.keepAlive?.unsubscribe(); // Timeout facade.stop() — wallets may hang if in a bad state (e.g. dust wallet stuck). - // Don't block the caller forever; let the old facade be GC'd. - await Promise.race([ - bundle.facade.stop(), - new Promise(resolve => setTimeout(resolve, 5_000)), - ]); + // Don't block the caller forever; let the old facade be GC'd. The wait is + // cleared once the facade stops, so it doesn't keep the process up 5 s more. + let timer: ReturnType | undefined; + try { + await Promise.race([ + bundle.facade.stop(), + new Promise((resolve) => { timer = setTimeout(resolve, STOP_TIMEOUT_MS); }), + ]); + } finally { + clearTimeout(timer); + } } diff --git a/packages/engine-rc/src/transfer.ts b/packages/engine-rc/src/transfer.ts index 10136b34..f8bcb214 100644 --- a/packages/engine-rc/src/transfer.ts +++ b/packages/engine-rc/src/transfer.ts @@ -105,7 +105,7 @@ async function submitDustRegistration( * Each retry rebuilds the transaction with a newer timestamp, giving a * larger time delta and thus a larger allow_fee_payment. * - * The shell keeps the RPC noise off the terminal (sdk-noise.ts). + * The host's process guard keeps the RPC noise off the terminal (core's "./process", its console option). */ export async function registerNightUtxos( bundle: FacadeBundle, @@ -181,7 +181,7 @@ export async function registerNightUtxos( * outputs) can be registered later via `midnight dust register`. * * Used by: executeTransfer (transfer/airdrop commands), dustRegister command. - * The shell keeps the RPC noise off the terminal (sdk-noise.ts). + * The host's process guard keeps the RPC noise off the terminal (core's "./process", its console option). */ export async function ensureDust( bundle: FacadeBundle, diff --git a/scripts/check-layering.d.mts b/scripts/check-layering.d.mts index e4c32a14..0b7df021 100644 --- a/scripts/check-layering.d.mts +++ b/scripts/check-layering.d.mts @@ -3,6 +3,8 @@ export function sourceFiles(dir?: string): string[]; export function homeOf(file: string): string | undefined; export function guidanceRule(fromRel: string, toRel: string): string | undefined; export function importRule(fromRel: string, toRel: string): string | undefined; +/** The rule an import from `file` (in package `home`) of `modules` breaks by reaching core's host-called process code, or undefined. */ +export function processCodeRule(file: string, home: string | undefined, modules: { file: string; typeOnly: boolean }[]): string | undefined; export function accountImportRule(home: string, specifier: string, typeOnly: boolean): string | undefined; export function findLayeringProblems(): { unhomed: string[]; violations: { home: string; rule: string; where: string; specifier: string }[] }; /** The imports of a test file that break a rule: a test imports its own package relatively, every other by an entry point. */ diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 85a4c83e..91d3e57f 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -9,6 +9,10 @@ // and the MCP server dispatch to one. A package's codes file is data, not a // command: a package below lends its sets of codes to the definitions above. // +// Core's process code (packages/cli-core/src/process/, its "./process" entry +// point) is host-called: only the shell imports it, and no package source does, +// by name or by path; a host calls it on its own process. +// // A workspace package is imported by its entry points only: an import of // `@kuiralabs//` resolves through that package's exports map, // and a subpath the map lacks is a deep import, refused. An import of an entry @@ -25,7 +29,7 @@ // // Usage: node scripts/check-layering.mjs // Imported, it exports sourceFiles and homeOf: which package each file of src/ is in; -// importRule and guidanceRule: the rule an import breaks; findLayeringProblems, +// importRule, guidanceRule and processCodeRule: the rule an import breaks; findLayeringProblems, // which the suite runs, and testProblems, one test file's; importsOf and // importedModules, a file's imports and the modules they bring in // (scripts/code-reach.mjs walks them); and the workspace packages' entry @@ -34,7 +38,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { codeOnly } from './check-process-safety.mjs'; +import { codeOnly, CORE_PROCESS_DIR } from './check-process-safety.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const SRC = join(ROOT, 'src'); @@ -60,7 +64,7 @@ const HOMES = [ // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], // pkg reads mn's own package.json: its name, version and repository. - ['shell', /^lib\/(pkg|heap-guard|node-version|intro-marker|output-redaction|run-command|sdk-noise|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|code-tables)\.ts$/], + ['shell', /^lib\/(pkg|heap-guard|node-version|intro-marker|output-redaction|run-command|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|code-tables)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], @@ -75,6 +79,8 @@ const HOMES = [ ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], + // What a host calls on its own process: the SDK rejection guard, the sync heap advice. + ['core', /^process\//], ['dev', /^ui\/(test-create-prompt|dev-keys)\.ts$/], ['chain', /^commands\/(status|tx)(\.definition)?\.ts$/], @@ -467,6 +473,15 @@ export function importedModules(file, { specifier, typeOnly, names }) { return { modules: [...modules].map(([each, typesAlone]) => ({ file: each, typeOnly: typesAlone })) }; } +/** Whether a file is core's host-called process code: its process directory, or the "./process" entry point listing it. */ +const isProcessCode = (file) => file.startsWith(CORE_PROCESS_DIR + '/') || file === `${CORE_PROCESS_DIR}.ts`; + +/** The rule an import from `file` (whose package is `home`) of `modules` breaks by reaching core's process code, or undefined. */ +export function processCodeRule(file, home, modules) { + if (home === 'shell' || isProcessCode(file)) return undefined; + return modules.some((module) => isProcessCode(module.file)) ? `${home} → core's process code (only a host calls it, through "./process")` : undefined; +} + /** The refusal of a deep import into `pkg`, naming its entry points. */ const deepImportRule = (pkg, entries) => `deep import into ${pkg} (its entry points: ${entries.join(', ')})`; @@ -490,6 +505,12 @@ function sourceProblems(file) { continue; } if (resolved !== undefined) { + // No package reaches core's process code, not even through a barrel of its own. + const processRule = processCodeRule(file, home, resolved.modules); + if (processRule !== undefined) { + violations.push({ home, rule: processRule, where, specifier }); + continue; + } // A barrel only lists its own package's modules for the packages above; it calls nothing. if (barrelExports(file) !== undefined) continue; const rules = new Set(resolved.modules.map((module) => importRule(rel, relOf(module.file))).filter((rule) => rule !== undefined)); diff --git a/scripts/check-process-safety.d.mts b/scripts/check-process-safety.d.mts index 8801a3c0..093be329 100644 --- a/scripts/check-process-safety.d.mts +++ b/scripts/check-process-safety.d.mts @@ -1,4 +1,6 @@ // Types for what scripts/check-process-safety.mjs exports when imported. +/** Core's host-called process directory: what only a host calls, on its own process. */ +export const CORE_PROCESS_DIR: string; export const ALLOWED: Record; export const ALLOWED_STATE: Record>; export const ALLOWED_SETTERS: Record>; diff --git a/scripts/check-process-safety.mjs b/scripts/check-process-safety.mjs index b27c4ca9..a532b27c 100644 --- a/scripts/check-process-safety.mjs +++ b/scripts/check-process-safety.mjs @@ -2,7 +2,11 @@ // Checks that library code leaves the host process alone: no writing to the terminal, exiting, installing process handlers, // patching console, changing directory, opening a prompt, reading the // environment, or computing a path from the home directory. Commands, ui/, the shell and the MCP server may; so may the -// modules marked below as shell concerns. Commands may not write to the +// modules marked below as shell concerns. Core's process directory +// (packages/cli-core/src/process/, its "./process" entry point) is host-called: +// it may install a process handler, patch the console, write to the terminal +// and exit, because only a host calls it, on its own process (no package +// imports it: scripts/check-layering.mjs). Commands may not write to the // terminal either: their text goes through their call's output // (ctx.output.stdout / stderr), which the CLI writes to the process's streams // and the MCP server to its stderr. String and template-literal @@ -15,9 +19,9 @@ // empty object to fill); what is shared on purpose is allowlisted by name, // with its reason; // - only the shell sets the process's exit code; a handler returns its own; -// - only the shell's noise filter (lib/sdk-noise.ts) may keep ambient per-call -// storage (AsyncLocalStorage, async_hooks); everything else is passed the -// call's context explicitly; +// - only core's host-called process directory (the SDK process guard) may +// keep ambient per-call storage (AsyncLocalStorage, async_hooks); +// everything else is passed the call's context explicitly; // - library, ui and command code exports no setter of host state: no // function named set…Source, set…Sink, setPrompter or setEngineLoader, and // no exported function that assigns a module-level `let` or `var`. What a @@ -37,6 +41,12 @@ import { homeOf, relOf, sourceFiles } from './check-layering.mjs'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const SRC = join(ROOT, 'src'); +// Core's host-called code: what a host calls on its own process, never a library. +export const CORE_PROCESS_DIR = join(ROOT, 'packages', 'cli-core', 'src', 'process'); +const isHostCalled = (file) => file.startsWith(CORE_PROCESS_DIR + '/'); +// What host-called code may do to the process, the host having asked it to. +const HOST_CALLED_RULES = new Set(['writes to the terminal', 'exits', 'installs a process handler', 'patches console or stdout']); + const RULES = [ ['writes to the terminal', /\bprocess\.(stdout|stderr)\.write\s*\(|\bconsole\.(log|error|warn|info|debug)\s*\(/], ['exits', /\bprocess\.exit\s*\(/], @@ -62,14 +72,14 @@ const STALE_STATE = 'allowlists module state it no longer keeps'; const SETTER = 'exports a setter of host state'; const STALE_SETTER = 'allowlists a setter it no longer exports'; const AMBIENT = 'keeps ambient per-call storage'; -const notNoiseFilter = (rel) => rel !== 'lib/sdk-noise.ts'; +const notHostCalled = (_rel, file) => !isHostCalled(file); // [rule, pattern, the files it applies to, whether it reads the raw source (an import's specifier)]. const CALL_RULES = [ // Only the shell turns a handler's exit code into the process's. ['sets the process exit code', /\bprocess\.exitCode\s*(=[^=]|\?\?=|\|\|=)/, (_rel, file) => homeOf(file) !== 'shell', false], - // Ambient per-call storage is module state in disguise: only the shell's noise filter may attribute the SDK's noise that way. - [AMBIENT, /\bAsyncLocalStorage\b/, notNoiseFilter, false], - [AMBIENT, /\bfrom\s+['"](node:)?async_hooks['"]|\brequire\(\s*['"](node:)?async_hooks['"]\s*\)/, notNoiseFilter, true], + // Ambient per-call storage is module state in disguise: only the host-called process guard may attribute the SDK's noise that way. + [AMBIENT, /\bAsyncLocalStorage\b/, notHostCalled, false], + [AMBIENT, /\bfrom\s+['"](node:)?async_hooks['"]|\brequire\(\s*['"](node:)?async_hooks['"]\s*\)/, notHostCalled, true], ]; // Shell concerns by design: what they do to the process is their job. @@ -343,7 +353,10 @@ export function findViolations(files = sourceFiles(), allowed = ALLOWED, allowed }); }; if (isLibrary(rel, file)) { - for (const [rule, pattern] of RULES) scanRule(rule, pattern, RAW_RULES.has(rule)); + for (const [rule, pattern] of RULES) { + if (isHostCalled(file) && HOST_CALLED_RULES.has(rule)) continue; + scanRule(rule, pattern, RAW_RULES.has(rule)); + } } if (isCommand(rel)) { for (const [rule, pattern] of COMMAND_RULES) scanRule(rule, pattern, false); diff --git a/src/__tests__/entry-points.test.ts b/src/__tests__/entry-points.test.ts index 8f86ecaf..3738ff65 100644 --- a/src/__tests__/entry-points.test.ts +++ b/src/__tests__/entry-points.test.ts @@ -12,7 +12,7 @@ const PACKAGES = join(import.meta.dirname, '..', '..', 'packages'); /** The agreed entry points of each public package, by folder under packages/. */ const ENTRY_POINTS: Record = { - 'cli-core': ['.', './engine', './ui', './commands'], + 'cli-core': ['.', './engine', './ui', './commands', './process'], chain: ['.', './commands'], 'engine-rc': ['.'], 'engine-beta': ['.'], diff --git a/src/__tests__/heap-guard.test.ts b/src/__tests__/heap-guard.test.ts index 11711acf..7dc7b597 100644 --- a/src/__tests__/heap-guard.test.ts +++ b/src/__tests__/heap-guard.test.ts @@ -1,55 +1,4 @@ import { describe, it, expect } from 'vitest'; -import { computeHeapTargetMb } from '../lib/heap-guard.ts'; -import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB } from '@kuiralabs/midnight-cli-core'; - -describe('computeHeapTargetMb', () => { - // The OOM repro: a 128 GB box with Node's default ~4.3 GB old-space cap. - it('bumps to the desired target when RAM and current limit allow', () => { - expect(computeHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288 })) - .toBe(SYNC_HEAP_TARGET_MB); - }); - - it('returns null when the current limit already has enough headroom', () => { - // e.g. the user already raised the heap via NODE_OPTIONS — don't re-exec. - expect(computeHeapTargetMb({ totalMb: 131072, currentLimitMb: 16384 })).toBeNull(); - }); - - it('caps the target at the RAM fraction on small machines', () => { - // 8 GB machine: 70% = 5734 MB, below the 12 GB desired. - expect(computeHeapTargetMb({ totalMb: 8192, currentLimitMb: 4288 })) - .toBe(Math.floor(8192 * SYNC_HEAP_RAM_FRACTION)); - }); - - it('returns null when the RAM-capped target is not a worthwhile gain', () => { - // 6 GB machine: 70% = 4300 MB, only ~12 MB over the current 4288 — below the - // min-gain threshold, so re-exec isn't worth it. - expect(computeHeapTargetMb({ totalMb: 6144, currentLimitMb: 4288 })).toBeNull(); - }); - - it('respects the min-gain threshold exactly at the boundary', () => { - const current = 4288; - // target would be current + minGain exactly → not a *worthwhile* gain (<=). - const totalMb = Math.ceil((current + SYNC_HEAP_MIN_GAIN_MB) / SYNC_HEAP_RAM_FRACTION); - expect(computeHeapTargetMb({ totalMb, currentLimitMb: current })).toBeNull(); - // one MB more of RAM tips it over. - expect(computeHeapTargetMb({ totalMb: totalMb + 2, currentLimitMb: current })).not.toBeNull(); - }); - - it('honors an explicit desired override', () => { - expect(computeHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288, desiredMb: 8192 })) - .toBe(8192); - }); - - it('rejects a non-positive or NaN desired override', () => { - expect(computeHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288, desiredMb: 0 })).toBeNull(); - expect(computeHeapTargetMb({ totalMb: 131072, currentLimitMb: 4288, desiredMb: NaN })).toBeNull(); - }); - - it('returns null for bogus total memory', () => { - expect(computeHeapTargetMb({ totalMb: 0, currentLimitMb: 4288 })).toBeNull(); - expect(computeHeapTargetMb({ totalMb: NaN, currentLimitMb: 4288 })).toBeNull(); - }); -}); describe('tieChildLifetime', () => { // The bug: the re-exec parent IGNORED signals, so `kill ` orphaned the diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index d7a277d5..c021049f 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { accountImportRule, findLayeringProblems, importRule, importedModules, testProblems } from '../../scripts/check-layering.mjs'; +import { accountImportRule, findLayeringProblems, importRule, importedModules, processCodeRule, testProblems } from '../../scripts/check-layering.mjs'; const ROOT = join(import.meta.dirname, '..', '..'); const FIXTURES = join(import.meta.dirname, 'fixtures', 'layering'); @@ -80,6 +80,27 @@ describe('the layering', () => { expect(accountImportRule('core', '@kuiralabs/midnight-account', false)).toBe('core → account chain'); }); + it("lets only the shell reach core's process code, by name or by path, and no package even through a barrel", () => { + const CORE = join(ROOT, 'packages', 'cli-core', 'src'); + const reached = (file: string, specifier: string) => importedModules(file, { specifier, typeOnly: false, names: null })!.modules!; + const byName = (file: string) => reached(file, '@kuiralabs/midnight-cli-core/process'); + // The shell installs the guard and takes the heap advice. + expect(processCodeRule(join(ROOT, 'src', 'lib', 'cli-host.ts'), 'shell', byName(join(ROOT, 'src', 'lib', 'cli-host.ts')))).toBeUndefined(); + // A package by name, an engine among them. + const facade = join(ROOT, 'packages', 'wallet', 'src', 'lib', 'facade.ts'); + expect(processCodeRule(facade, 'wallet', byName(facade))).toBe(`wallet → core's process code (only a host calls it, through "./process")`); + const engine = join(ROOT, 'packages', 'engine-rc', 'src', 'wallet.ts'); + expect(processCodeRule(engine, 'engine', byName(engine))).toBe(`engine → core's process code (only a host calls it, through "./process")`); + // Core's own library by path, and core's "." barrel re-exporting it. + const host = join(CORE, 'lib', 'host.ts'); + expect(processCodeRule(host, 'core', reached(host, '../process/sdk-process-guard.ts'))).toBe(`core → core's process code (only a host calls it, through "./process")`); + const index = join(CORE, 'index.ts'); + expect(processCodeRule(index, 'core', reached(index, './process/sync-heap.ts'))).toBe(`core → core's process code (only a host calls it, through "./process")`); + // The entry point listing it, and the process code's own imports. + const entry = join(CORE, 'process.ts'); + expect(processCodeRule(entry, 'core', reached(entry, './process/sdk-process-guard.ts'))).toBeUndefined(); + }); + it('lets only an engine import the SDK', () => { // findLayeringProblems above finds none elsewhere; core, chain and every package are held to it alike. expect(importRule('lib/wallet-create.ts', 'engine/rc/derivation.ts')).toBe('wallet → engine (reach it through lib/installed-engines.ts)'); @@ -89,7 +110,7 @@ describe('the layering', () => { describe('a workspace package imported by its entry points', () => { it('refuses a deep import across packages, naming the entry points', () => { expect(testProblems(join(FIXTURES, 'deep-import.ts')).map((v) => `${v.rule}: ${v.where} ${v.specifier}`)).toStrictEqual([ - 'deep import into @kuiralabs/midnight-cli-core (its entry points: ., ./engine, ./ui, ./commands): src/__tests__/fixtures/layering/deep-import.ts:5 @kuiralabs/midnight-cli-core/lib/errors', + 'deep import into @kuiralabs/midnight-cli-core (its entry points: ., ./engine, ./ui, ./commands, ./process): src/__tests__/fixtures/layering/deep-import.ts:5 @kuiralabs/midnight-cli-core/lib/errors', ]); }); diff --git a/src/__tests__/process-safety.test.ts b/src/__tests__/process-safety.test.ts index ebbf85d3..7c60c311 100644 --- a/src/__tests__/process-safety.test.ts +++ b/src/__tests__/process-safety.test.ts @@ -1,15 +1,14 @@ // Libraries leave the host process alone. The check finds each // kind of break in a module planted for it, skips strings and comments, and -// finds nothing in src/ beyond what its allowlist names. The SDK's noise is -// filtered by the shell: a transient Wallet.* rejection reaches the library -// listening for it and the run goes on; any other rejection still exits 1. +// finds nothing in src/ beyond what its allowlist names. The guard that +// filters the SDK's noise is core's host-called process code, tested with it +// (packages/cli-core/src/__tests__/sdk-process-guard.test.ts). import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { spawnSync } from 'node:child_process'; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, relative, resolve } from 'node:path'; -import { findViolations } from '../../scripts/check-process-safety.mjs'; +import { CORE_PROCESS_DIR, findViolations } from '../../scripts/check-process-safety.mjs'; const ROOT = resolve(import.meta.dirname, '..', '..'); let dir: string; @@ -194,10 +193,38 @@ describe("the process-safety check keeps calls' state out of modules", () => { expect(found(quiet)).toEqual([]); }); - it('lets the shell set the exit code and its noise filter keep ambient storage', () => { - const shell = findViolations([join(ROOT, 'src/wallet.ts'), join(ROOT, 'src/lib/sdk-noise.ts')]); + it("lets the shell set the exit code and core's host-called process guard keep ambient storage", () => { + const shell = findViolations([join(ROOT, 'src/wallet.ts'), join(ROOT, 'packages/cli-core/src/process/sdk-process-guard.ts')]); expect(shell).toEqual([]); }); + + it("lets core's process directory touch the process as a host asks it to, and refuses the same code anywhere else", () => { + const touches = [ + "import { AsyncLocalStorage } from 'node:async_hooks';", + "process.on('unhandledRejection', () => {});", + 'console.error = () => {};', + "process.stderr.write('hi');", + 'process.exit(1);', + 'const v = process.env.HOME;', + ]; + // The same code in a process/ folder of anything but core is a library's. + mkdirSync(join(dir, 'process')); + const elsewhere = join(dir, 'process', 'guard.ts'); + writeFileSync(elsewhere, touches.join('\n')); + expect(findViolations([elsewhere], {}, {}, dir).map((v) => `${v.line} ${v.rule}`)).toEqual([ + '4 writes to the terminal', + '5 exits', + '2 installs a process handler', + '3 patches console or stdout', + '6 reads the environment', + '1 keeps ambient per-call storage', + ]); + // Core's process code does each of these but read the environment, and passes. + const guard = join(CORE_PROCESS_DIR, 'sdk-process-guard.ts'); + const source = readFileSync(guard, 'utf8'); + for (const done of [/process\.on\(/, /process\.exit\(/, /console\.error = /, /AsyncLocalStorage/]) expect(source).toMatch(done); + expect(findViolations([guard, join(CORE_PROCESS_DIR, 'sync-heap.ts')])).toEqual([]); + }); }); // What a library needs from its host comes in through the host it is passed, never a module-level setter. @@ -277,195 +304,3 @@ describe('the process-safety check finds a library exporting a setter of host st expect(setters(plant('lib/engine.ts', ['export const NONE = 1;']))).toEqual(['0 allowlists a setter it no longer exports claimSdkSet']); }); }); - -describe('the shell filters the SDK noise', () => { - const run = (body: string) => { - const script = join(dir, 'noise.mjs'); - writeFileSync(script, [ - `const { installSdkNoiseFilters } = await import(${JSON.stringify(join(ROOT, 'src/lib/sdk-noise.ts'))});`, - `const { WebSocket, WebSocketServer } = await import(${JSON.stringify(join(ROOT, 'node_modules/ws/wrapper.mjs'))});`, - 'const calls = installSdkNoiseFilters();', - // A call that starts listening and stays open, as a library inside it does. What - // the script raises at its top level comes from outside any call: it carries no identity. - 'const listen = (listener) => calls.run(async (warnings) => warnings.listen(listener));', - body, - ].join('\n')); - return spawnSync(process.execPath, ['--import', 'tsx', script], { cwd: ROOT, encoding: 'utf8', timeout: 60_000 }); - }; - - it('hands a transient Wallet.* rejection to the listening library and goes on', () => { - const result = run([ - "await listen((tag, message) => console.log('warned', tag, message));", - "Promise.reject(Object.assign(new Error('Internal Server Error'), { _tag: 'Wallet.Sync' }));", - "console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", - "setTimeout(() => console.log('still running'), 50);", - ].join('\n')); - expect(result.status).toBe(0); - expect(result.stdout).toBe('warned Wallet.Sync Internal Server Error\nstill running\n'); - expect(result.stderr).not.toContain('RPC-CORE'); - }); - - it("hands the SDK's Wallet.* console.error traces, object or string, to the listener, and prints anything else", () => { - const result = run([ - "await listen((tag, message) => console.log('warned', tag, message));", - "console.error({ _tag: 'Wallet.Sync', message: 'Internal Server Error' });", - "console.error('Wallet.Sync: Internal Server Error\\n at somewhere');", - "console.error('a real problem');", - ].join('\n')); - expect(result.status).toBe(0); - expect(result.stdout).toBe('warned Wallet.Sync Internal Server Error\nwarned Wallet.Sync transient error\n'); - expect(result.stderr).toBe('a real problem\n'); - }); - - it('touches nothing while no call listens: SDK traces and RPC noise print as they would without the filters', () => { - const result = run([ - "console.error({ _tag: 'Wallet.Sync', message: 'Internal Server Error' });", - "console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", - "const stop = await listen(undefined);", - "console.warn('RPC-CORE: kept off while listening');", - "stop();", - ].join('\n')); - expect(result.status).toBe(0); - expect(result.stderr).toContain('Wallet.Sync'); - expect(result.stderr).toContain('RPC-CORE: submitAndWatchExtrinsic'); - expect(result.stderr).not.toContain('kept off while listening'); - }); - - it('exits 1 on a Wallet.* rejection while no call listens, as before the filters', () => { - const result = run("Promise.reject(Object.assign(new Error('Internal Server Error'), { _tag: 'Wallet.Sync' }));\nsetTimeout(() => console.log('still running'), 500);"); - expect(result.status).toBe(1); - expect(result.stdout).toBe(''); - }); - - it('still exits 1 on a rejection that is only a string, even one starting Wallet.', () => { - const result = run("await listen(() => console.log('warned'));\nPromise.reject('Wallet.Sync: not an SDK error object');\nsetTimeout(() => console.log('still running'), 500);"); - expect(result.status).toBe(1); - expect(result.stdout).toBe(''); - }); - - it('still exits 1 on any other unhandled rejection', () => { - const result = run("Promise.reject(new Error('a real failure'));\nsetTimeout(() => console.log('still running'), 500);"); - expect(result.status).toBe(1); - expect(result.stderr).toContain('a real failure'); - expect(result.stdout).not.toContain('still running'); - }); -}); - -// Each call's SDK warnings are its own. Regression: one listener -// stack for the process, whose newest listener got every warning, so two -// calls at once in the MCP server got each other's. -describe("the shell gives each call its own SDK warnings", () => { - const run = (body: string) => { - const script = join(dir, 'calls.mjs'); - writeFileSync(script, [ - `const { installSdkNoiseFilters } = await import(${JSON.stringify(join(ROOT, 'src/lib/sdk-noise.ts'))});`, - `const { WebSocket, WebSocketServer } = await import(${JSON.stringify(join(ROOT, 'node_modules/ws/wrapper.mjs'))});`, - 'const calls = installSdkNoiseFilters();', - 'const listen = (listener) => calls.run(async (warnings) => warnings.listen(listener));', - "const sdkError = (message, tag = 'Wallet.Sync') => Object.assign(new Error(message), { _tag: tag });", - 'const said = [];', - body, - ].join('\n')); - return spawnSync(process.execPath, ['--import', 'tsx', script], { cwd: ROOT, encoding: 'utf8', timeout: 60_000 }); - }; - - it('two calls at once: what each raises from its timers and its WebSocket callbacks reaches it alone, and none reaches the terminal', () => { - const result = run([ - // A server outside both calls: it answers each socket from its own callbacks, a little later. - 'const server = new WebSocketServer({ port: 0 });', - "await new Promise((resolve) => server.once('listening', resolve));", - "server.on('connection', (socket) => socket.on('message', (m) => setTimeout(() => socket.send(String(m)), 5)));", - 'const call = (name) => calls.run(async (warnings) => {', - ' const stop = warnings.listen((tag, message) => said.push(`${name} got ${tag} ${message}`));', - ' await new Promise((done) => {', - ' setTimeout(() => Promise.reject(sdkError(`${name}: timer rejection`)), 10);', - " setTimeout(() => console.error({ _tag: 'Wallet.Sync', message: `${name}: timer trace` }), 15);", - " setInterval(function tick() { console.error({ _tag: 'Wallet.Sync', message: `${name}: interval trace` }); clearInterval(this); }, 20);", - ' const socket = new WebSocket(`ws://127.0.0.1:${server.address().port}`);', - " socket.on('open', () => socket.send(name));", - " socket.on('message', () => {", - " console.error({ _tag: 'Wallet.Sync', message: `${name}: socket trace` });", - " Promise.reject(sdkError(`${name}: socket rejection`, 'Wallet.Indexer'));", - " console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", - ' socket.close();', - ' setTimeout(done, 40);', - ' });', - ' });', - ' stop();', - '});', - "await Promise.all([call('a'), call('b')]);", - 'server.close();', - "console.log(said.sort().join('\\n'));", - ].join('\n')); - expect(result.status).toBe(0); - expect(result.stdout.trim().split('\n')).toEqual([ - 'a got Wallet.Indexer a: socket rejection', - 'a got Wallet.Sync a: interval trace', - 'a got Wallet.Sync a: socket trace', - 'a got Wallet.Sync a: timer rejection', - 'a got Wallet.Sync a: timer trace', - 'b got Wallet.Indexer b: socket rejection', - 'b got Wallet.Sync b: interval trace', - 'b got Wallet.Sync b: socket trace', - 'b got Wallet.Sync b: timer rejection', - 'b got Wallet.Sync b: timer trace', - ]); - expect(result.stderr).toBe(''); - }); - - it("goes to the newest listener of the call that raised it, and to no other call's", () => { - const result = run([ - "await listen((tag, message) => said.push(`other call: ${message}`));", - 'await calls.run(async (warnings) => {', - " warnings.listen((tag, message) => said.push(`outer: ${message}`));", - " const stopInner = warnings.listen((tag, message) => said.push(`inner: ${message}`));", - " console.error({ _tag: 'Wallet.Sync', message: 'first' });", - ' stopInner();', - " console.error({ _tag: 'Wallet.Sync', message: 'second' });", - '});', - 'console.log(JSON.stringify(said));', - ].join('\n')); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual(['inner: first', 'outer: second']); - }); - - it("a call's warning after it stopped listening goes to no other call, and stays off the terminal while one listens", () => { - const result = run([ - "await listen((tag, message) => said.push(`other call: ${message}`));", - 'await calls.run(async (warnings) => {', - ' warnings.listen(undefined)();', - " console.error({ _tag: 'Wallet.Sync', message: 'after it stopped' });", - " await new Promise((resolve) => { Promise.reject(sdkError('rejected after it stopped')); setTimeout(resolve, 20); });", - '});', - 'console.log(JSON.stringify(said));', - ].join('\n')); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual([]); - expect(result.stderr).toBe(''); - }); - - it('a warning from outside any call goes to the one call listening', () => { - const result = run([ - "await listen((tag, message) => said.push(`the call: ${message}`));", - "console.error({ _tag: 'Wallet.Sync', message: 'from nowhere' });", - "Promise.reject(sdkError('rejected from nowhere'));", - 'setTimeout(() => console.log(JSON.stringify(said)), 50);', - ].join('\n')); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual(['the call: from nowhere', 'the call: rejected from nowhere']); - }); - - it('a warning from outside any call while several listen goes to none of them, and stays off the terminal', () => { - const result = run([ - "await listen((tag, message) => said.push(`a: ${message}`));", - "await listen((tag, message) => said.push(`b: ${message}`));", - "console.error({ _tag: 'Wallet.Sync', message: 'from nowhere' });", - "Promise.reject(sdkError('rejected from nowhere'));", - "console.warn('RPC-CORE: submitAndWatchExtrinsic: Custom error: 138');", - 'setTimeout(() => console.log(JSON.stringify(said)), 50);', - ].join('\n')); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual([]); - expect(result.stderr).toBe(''); - }); -}); diff --git a/src/lib/cli-host.ts b/src/lib/cli-host.ts index 41481212..51d3399a 100644 --- a/src/lib/cli-host.ts +++ b/src/lib/cli-host.ts @@ -1,7 +1,9 @@ // A shell concern: the host the CLI and the MCP server each build at start, // which their calls pass to the libraries. A consumer builds its own. -// - the filters for the SDK's noise, acting while a call listens, and the -// calls it runs, whose SDK warnings go to the call that raised them; +// - the guard against the SDK's transient rejections, with its console +// filters, acting while a call listens (a rejection outside any call +// exits 1), and the calls it runs, whose SDK warnings go to the call that +// raised them; // - a notice sink: stderr; // - settings, read from the environment as each is needed; // - the state root, ~/.midnight, read as each path is built; @@ -10,18 +12,18 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; -import { installSdkNoiseFilters } from './sdk-noise.ts'; +import { installSdkProcessGuard } from '@kuiralabs/midnight-cli-core/process'; import { settingsFromEnvironment, type Prompter, MIDNIGHT_DIR, createHost, type Host } from '@kuiralabs/midnight-cli-core'; import { loadInstalledEngine } from './installed-engines.ts'; -/** The CLI's host, or the MCP server's (`prompter` null: no terminal there). */ +/** The CLI's host, or the MCP server's (`prompter` null: no terminal there). Made once per process: each installs a process guard of its own. */ export function createCliHost({ prompter }: { prompter: Prompter | null }): Host { return createHost({ settings: () => settingsFromEnvironment(process.env), paths: () => ({ stateRoot: join(homedir(), MIDNIGHT_DIR), home: homedir() }), notice: (line) => process.stderr.write(line + '\n'), prompter, - sdkWarnings: installSdkNoiseFilters(), + sdkWarnings: installSdkProcessGuard({ console: true, outsideCalls: 'exit' }).calls, engineLoader: loadInstalledEngine, }); } diff --git a/src/lib/heap-guard.ts b/src/lib/heap-guard.ts index 6d0662f2..985eacce 100644 --- a/src/lib/heap-guard.ts +++ b/src/lib/heap-guard.ts @@ -1,24 +1,20 @@ -// Cold-sync heap headroom guard. +// Cold-sync heap headroom guard: mn's re-exec. // -// The first shielded/dust sync against a hosted network (preprod/preview) streams -// the whole chain history through the wallet SDK. The live working set is small -// (~300 MB), but the scan churns through a firehose of short-lived JS objects; -// under Node's default old-space cap (~4 GB) GC can't keep pace with the -// allocation rate and the process dies with "JavaScript heap out of memory" -// before it can finish — and write the cache that makes every later run cheap. -// -// Fix: before any SDK/WASM module loads, re-exec the process with a larger -// `--max-old-space-size`. Because the CLI dispatches command handlers via dynamic -// import, calling this from the entry point ahead of dispatch means the parent -// re-execs before the SDK is ever loaded — no double load. It is a no-op when the -// heap is already large enough (e.g. the user set NODE_OPTIONS) or when we're -// already running as the re-exec'd child. +// A cold shielded or Dust sync against a hosted network overflows Node's +// default old-space limit (core's process/sync-heap.ts says why). The limit is +// fixed at start, so before any SDK/WASM module loads mn re-execs itself with +// the `--max-old-space-size` core's syncHeapTargetMb gives. Because the CLI +// dispatches command handlers via dynamic import, calling this from the entry +// point ahead of dispatch means the parent re-execs before the SDK is ever +// loaded — no double load. It is a no-op when the heap is already large enough +// (e.g. the user set NODE_OPTIONS) or when we're already running as the +// re-exec'd child. import v8 from 'node:v8'; import os from 'node:os'; import { spawn } from 'node:child_process'; -import { SYNC_HEAP_TARGET_MB, SYNC_HEAP_RAM_FRACTION, SYNC_HEAP_MIN_GAIN_MB } from '@kuiralabs/midnight-cli-core'; +import { syncHeapTargetMb } from '@kuiralabs/midnight-cli-core/process'; /** Set on the re-exec'd child so it doesn't recurse. */ const BUMP_ENV = 'MN_HEAP_BUMPED'; @@ -26,34 +22,6 @@ const BUMP_ENV = 'MN_HEAP_BUMPED'; const OVERRIDE_ENV = 'MN_MAX_OLD_SPACE_MB'; const MB = 1024 * 1024; -/** - * Decide the old-space cap (in MB) to re-exec with, or `null` when a bump isn't - * worthwhile. Pure — every input is passed in, so it's unit-testable without a - * real process. - * - * - never exceed `ramFraction` of physical RAM (avoid thrashing small machines) - * - never downgrade below, or only trivially above, the current limit - */ -export function computeHeapTargetMb(opts: { - totalMb: number; - currentLimitMb: number; - desiredMb?: number; - ramFraction?: number; - minGainMb?: number; -}): number | null { - const desired = opts.desiredMb ?? SYNC_HEAP_TARGET_MB; - const ramFraction = opts.ramFraction ?? SYNC_HEAP_RAM_FRACTION; - const minGain = opts.minGainMb ?? SYNC_HEAP_MIN_GAIN_MB; - - if (!Number.isFinite(desired) || desired <= 0) return null; - if (!Number.isFinite(opts.totalMb) || opts.totalMb <= 0) return null; - - const ramCap = Math.floor(opts.totalMb * ramFraction); - const target = Math.min(Math.floor(desired), ramCap); - if (target <= opts.currentLimitMb + minGain) return null; - return target; -} - /** * Re-exec the current process with more old-space headroom when a cold sync * would otherwise overflow Node's default heap. No-op when not needed. When a @@ -79,7 +47,9 @@ export async function ensureHeapForSync(): Promise { const overrideRaw = process.env[OVERRIDE_ENV]; const desiredMb = overrideRaw !== undefined ? Number(overrideRaw) : undefined; - const target = computeHeapTargetMb({ + // Read here rather than through syncHeapAdvice, which advises nothing under + // bun: mn re-execs under whichever runtime runs it, as it always has. + const target = syncHeapTargetMb({ totalMb: Math.floor(os.totalmem() / MB), currentLimitMb: Math.floor(v8.getHeapStatistics().heap_size_limit / MB), desiredMb, diff --git a/src/lib/sdk-noise.ts b/src/lib/sdk-noise.ts deleted file mode 100644 index 174fbda4..00000000 --- a/src/lib/sdk-noise.ts +++ /dev/null @@ -1,76 +0,0 @@ -// A shell concern: the process-wide filters for the SDK's noise, installed -// once by the CLI and the MCP server at start. They act only while a call is -// listening (its context's sdkWarnings), which is where the suppression they -// replace used to be switched on; at any other time the console and -// unhandled rejections behave as they would without them (an unhandled -// rejection is printed and exits 1). Libraries never install them. -// -// - A transient Wallet.* rejection is retried by the SDK: it goes to the -// listening call, and the run goes on. Any other unhandled rejection is -// printed and exits 1, as Node does. -// - The SDK's Wallet.* stack traces on console.error, and polkadot-js's -// RPC-CORE lines on console.warn and console.error (one per failed -// submit), are kept off the terminal. -// -// Which call a warning belongs to: each call runs inside its own -// AsyncLocalStorage store, the one ambient per-call storage the process-safety -// check allows, so a warning raised while it runs carries its identity, and -// the host's router hands it to that call alone (lib/sdk-warnings.ts). -// Measured on 31 Oct 2026 with two calls at once: on Node (v25) the identity -// survives the SDK's WebSocket callbacks (ws, polkadot-js, graphql-ws through -// the SDK's subscription client), Effect fibers, timers, RxJS, and reaches the -// unhandledRejection handler; under bun (1.3) it survives timers, RxJS and -// Effect fibers but is lost on everything resumed from a WebSocket. A warning -// that lost it is never given to the wrong call: the router gives it to the -// one call listening, or to none. - -import { AsyncLocalStorage } from 'node:async_hooks'; -import { createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls } from '@kuiralabs/midnight-cli-core'; - -let installed: SdkWarningCalls | null = null; - -/** Installs the filters, once; the calls the host runs, whose SDK warnings go to the call that raised them. */ -export function installSdkNoiseFilters(): SdkWarningCalls { - if (installed !== null) return installed; - - const router = createSdkWarningRouter(); - const runningCall = new AsyncLocalStorage(); - const report = (tag: string, message: string): void => router.route(runningCall.getStore(), tag, message); - - const originalError = console.error; - const originalWarn = console.warn; - const isRpcNoise = (args: unknown[]) => args.some((a) => String(a).includes('RPC-CORE')); - - process.on('unhandledRejection', (reason) => { - const warning = router.isListening() ? sdkTransientWarning(reason) : null; - if (warning !== null && typeof reason !== 'string') { - report(warning.tag, warning.message); - return; - } - originalError('Unhandled rejection:', reason); - process.exit(1); - }); - - console.error = (...args: unknown[]) => { - if (!router.isListening()) return originalError(...args); - const warning = sdkTransientWarning(args[0]); - if (warning !== null) { - report(warning.tag, warning.message); - return; - } - if (isRpcNoise(args)) return; - originalError(...args); - }; - console.warn = (...args: unknown[]) => { - if (router.isListening() && isRpcNoise(args)) return; - originalWarn(...args); - }; - - installed = { - run: (run) => { - const call = router.openCall(); - return runningCall.run(call.id, () => run(call.warnings)); - }, - }; - return installed; -} diff --git a/test-support/facade-stop-suite.ts b/test-support/facade-stop-suite.ts new file mode 100644 index 00000000..0da19298 --- /dev/null +++ b/test-support/facade-stop-suite.ts @@ -0,0 +1,113 @@ +// A stopped wallet facade leaves nothing that keeps the process up: a program +// that closed its wallet ends by itself, without process.exit. Each engine +// runs this suite with its own facade module. +// +// The program runs in a child process (what keeps a process up shows only from +// outside it) against stand-ins in this one: a silent indexer, and a node that +// refuses every connection or takes it and never answers. It builds the +// engine's facade, starts its sync (which never completes against silence), +// stops it, and returns. +// +// Regression: the SDK's submission service opened its node client when the +// facade was built, and its close() waited for that client to be ready, so +// against such a node stop never finished, polkadot-js reconnected every 2.5 s +// for good, and the program never ended. And stop's 5 s wait was never +// cleared, which kept even a clean stop's process up 5 s more. + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { spawn } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import { closedPort } from './closed-port.ts'; +import { startSilentNetwork, type SilentNetwork } from './stand-in-indexer.ts'; + +const ROOT = resolve(import.meta.dirname, '..'); +/** How long a stopped program may take to end by itself: well under the 5 s wait stop used to leave behind. */ +const ENDS_WITHIN_MS = 2_500; +/** When the child is killed as hung: it never ended by itself. */ +const HUNG_AFTER_MS = 30_000; + +/** What the child program says as it ends. */ +interface Ended { + /** How its sync ended: the error's name. */ + synced: string; + /** How long stopFacade took, and how long after stopping began the process ended. */ + stoppedMs: number; + exitedMs: number; +} + +/** The program: build, start and stop the facade of `facadeModule` against the network in NETWORK, then return. */ +const program = (facadeModule: string): string => ` +import { writeSync } from 'node:fs'; +const { buildFacade, startAndSyncFacade, stopFacade } = await import(${JSON.stringify(facadeModule)}); +const bundle = await buildFacade(Buffer.alloc(32, 7), JSON.parse(process.env.NETWORK), process.env.STATE_ROOT, () => {}); +let synced = 'synced'; +try { + await startAndSyncFacade(bundle, { syncMode: 'full', timeoutMs: 1000 }); +} catch (err) { + synced = err.name; +} +const stopping = Date.now(); +await stopFacade(bundle); +const stoppedMs = Date.now() - stopping; +process.on('exit', () => writeSync(1, JSON.stringify({ synced, stoppedMs, exitedMs: Date.now() - stopping }) + '\\n')); +`; + +/** Runs the program to its end; killed after HUNG_AFTER_MS when it doesn't end by itself. */ +function runProgram(script: string, network: NetworkConfig, stateRoot: string): Promise<{ code: number | null; ended: Ended | undefined; stderr: string }> { + return new Promise((done) => { + const child = spawn(process.execPath, ['--import', 'tsx', script], { + cwd: ROOT, + env: { ...process.env, NETWORK: JSON.stringify(network), STATE_ROOT: stateRoot }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + const hung = setTimeout(() => child.kill('SIGKILL'), HUNG_AFTER_MS); + child.on('exit', (code) => { + clearTimeout(hung); + const line = stdout.trim().split('\n').at(-1); + done({ code, ended: line?.startsWith('{') ? JSON.parse(line) as Ended : undefined, stderr }); + }); + }); +} + +export function facadeStopSuite(engine: { set: string; facadeModule: string }): void { + describe(`the ${engine.set} engine's facade, stopped, leaves nothing that keeps the process up`, () => { + let dir: string; + let silent: SilentNetwork; + beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), `mn-facade-stop-${engine.set}-`)); + writeFileSync(join(dir, 'program.mjs'), program(engine.facadeModule)); + silent = await startSilentNetwork(); + }); + afterEach(async () => { + await silent.close(); + rmSync(dir, { recursive: true, force: true }); + }); + + const network = (node: string): NetworkConfig => ({ networkId: 'Undeployed', indexer: silent.indexer, indexerWS: silent.indexerWS, node, proofServer: 'http://127.0.0.1:9' }); + + it.each([ + ['refuses every connection', async () => `ws://127.0.0.1:${await closedPort()}`], + ['takes the connection and never answers', async () => silent.node], + ])('a program ends by itself when the node %s, with every socket it opened closed', async (_how, node) => { + const { code, ended, stderr } = await runProgram(join(dir, 'program.mjs'), network(await node()), join(dir, 'state')); + expect(code, stderr).toBe(0); + expect(ended).toBeDefined(); + // The sync really ran against the stand-in, and never completed there. + expect(ended!.synced).toBe('SyncTimeoutError'); + expect(silent.opened.filter((path) => path === '/api/v4/graphql/ws').length).toBeGreaterThan(0); + expect(ended!.stoppedMs).toBeLessThan(ENDS_WITHIN_MS); + expect(ended!.exitedMs).toBeLessThan(ENDS_WITHIN_MS); + // A facade that submitted nothing never connected to the node. + expect(silent.opened).not.toContain('/node'); + await silent.allClosed(); + expect(silent.open()).toBe(0); + }); + }); +} diff --git a/test-support/stand-in-indexer.ts b/test-support/stand-in-indexer.ts index 9e25f2a5..fbae56e3 100644 --- a/test-support/stand-in-indexer.ts +++ b/test-support/stand-in-indexer.ts @@ -10,6 +10,10 @@ // - An indexer of a ledger-8 chain: its HTTP GraphQL endpoint answers every // query with a protocol version below the ledger-9 fork, which mn refuses // before a wallet syncs (lib/ledger-guard.ts). +// - A silent network: an indexer and a node on one port that take every +// connection and never answer (the indexer acknowledges graphql-transport-ws +// and sends no event; the node takes JSON-RPC and replies to none), counting +// the WebSockets a wallet opens and how many it has closed. import { createServer, type Server, type Socket } from 'node:net'; import { createServer as createHttpServer } from 'node:http'; @@ -148,3 +152,64 @@ export async function startLedger8Indexer(): Promise { }), }; } + +/** An indexer and a node that take every connection and never answer. */ +export interface SilentNetwork { + /** The indexer's HTTP and WebSocket URLs, and the node's, as a network config takes them. */ + readonly indexer: string; + readonly indexerWS: string; + readonly node: string; + /** The WebSockets opened to it, by path, and how many of them are still open. */ + readonly opened: string[]; + open(): number; + /** Resolves once every WebSocket opened to it has closed. */ + allClosed(): Promise; + close(): Promise; +} + +/** A silent network on 127.0.0.1: the indexer at /api/v4/graphql(/ws), the node at /node. */ +export async function startSilentNetwork(): Promise { + const opened: string[] = []; + let open = 0; + let wakeWhenClosed: Array<() => void> = []; + const server = createHttpServer((req, res) => { + req.resume(); + req.on('end', () => { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ data: null })); + }); + }); + const sockets = new WebSocketServer({ server, handleProtocols: (protocols) => (protocols.has('graphql-transport-ws') ? 'graphql-transport-ws' : false) }); + sockets.on('connection', (ws: WebSocket, req) => { + opened.push(req.url ?? ''); + open += 1; + ws.on('close', () => { + open -= 1; + if (open === 0) for (const wake of wakeWhenClosed.splice(0)) wake(); + }); + ws.on('message', (raw) => { + const message = JSON.parse(raw.toString()) as { type?: string }; + if (message.type === 'connection_init') ws.send(JSON.stringify({ type: 'connection_ack' })); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + const base = `127.0.0.1:${port}`; + return { + indexer: `http://${base}/api/v4/graphql`, + indexerWS: `ws://${base}/api/v4/graphql/ws`, + node: `ws://${base}/node`, + opened, + open: () => open, + allClosed: () => new Promise((resolve) => { + if (open === 0) resolve(); + else wakeWhenClosed = [...wakeWhenClosed, resolve]; + }), + close: () => new Promise((resolve) => { + for (const client of sockets.clients) client.terminate(); + sockets.close(); + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} From d72727c45d1e2aa0c1155d0f9bbdb79edc53e7f6 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 07:31:51 -0800 Subject: [PATCH 76/88] Pin account-chain 0.3.0-rc.2: grant works on stagenet (SL, part 2) Both engines pin @kuiralabs/midnight-account-chain 0.3.0-rc.2, whose stagenet build ships its proving keys (release build-a5c87559dc483e58 on kuiralabs/midnight-account-artifacts). The beta engine keeps its own nested copy (npm dedupes it away on install; the lockfile entry is restored and each engine's load refuses a shared copy). Suite 3000; fresh install: each engine's copy resolves its own ledger and runtimes. Live on stagenet (beta engine), wallet stage2: grant deploy activated, status and list answer, the artefacts fetched are the stagenet build's. --- package-lock.json | 16 ++++++++-------- packages/engine-beta/package.json | 2 +- packages/engine-rc/package.json | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package-lock.json b/package-lock.json index 55f12947..706824f7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -620,9 +620,9 @@ } }, "node_modules/@kuiralabs/midnight-account-chain": { - "version": "0.3.0-rc.1", - "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.1.tgz", - "integrity": "sha512-Xr7eVun90jzhnRl8ZnEwKRo3AliUNmgUBjFXHrS7e9hqcsjSpeVUgZbeefT0oxfsvftk2FHBMCKBG9PPMzMg2w==", + "version": "0.3.0-rc.2", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.2.tgz", + "integrity": "sha512-Cu4G3p0g4JcEOCZtM6JwMsugqwtJmzaFz4HFB1//lOJjqYoqd1XYyNwUryLX1SvusPx9OjxQZvqCgDxcY66jDQ==", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", @@ -5820,7 +5820,7 @@ "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", @@ -5868,9 +5868,9 @@ } }, "packages/engine-beta/node_modules/@kuiralabs/midnight-account-chain": { - "version": "0.3.0-rc.1", - "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.1.tgz", - "integrity": "sha512-Xr7eVun90jzhnRl8ZnEwKRo3AliUNmgUBjFXHrS7e9hqcsjSpeVUgZbeefT0oxfsvftk2FHBMCKBG9PPMzMg2w==", + "version": "0.3.0-rc.2", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.2.tgz", + "integrity": "sha512-Cu4G3p0g4JcEOCZtM6JwMsugqwtJmzaFz4HFB1//lOJjqYoqd1XYyNwUryLX1SvusPx9OjxQZvqCgDxcY66jDQ==", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", @@ -6328,7 +6328,7 @@ "version": "0.1.0-rc.1", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index 4b0280d9..18610a78 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -31,7 +31,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index b96cce02..98ff2d5b 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -31,7 +31,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.1", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", "@kuiralabs/midnight-chain": "0.1.0-rc.1", "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", From b217530e304b8a55b090c48eecc8960ca31cc35c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 07:48:49 -0800 Subject: [PATCH 77/88] mn grant deposit of any shielded token, and its shielded sync (Y62) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grant deposit takes --token (the raw shielded token type, 64 hex, as mn balance lists it): the amount is then in the token's smallest unit, read exactly as a bigint, and the account package's deposit gets the type's 32 bytes as its color. Without --token it is NIGHT, exactly as before. The pre-check reads the chosen token's shielded balance and names it when short. MCP's midnight_grant_deposit takes an optional token. Fix: a deposit now asks its wallet for the shielded side synced, as swap does. On stagenet the wallet skips the shielded sync by default, so a deposit read 0 of every shielded token and refused (regression test fails without the fix). Suite 3021; live on stagenet: 5 of test token bb2e…8cdb deposited into stage2's account (block 1165106), which then holds 5. --- docs/SKILL.md | 2 +- .../grant/src/__tests__/grant-request.test.ts | 22 +++ .../grant/src/commands/grant.definition.ts | 25 ++- packages/grant/src/commands/grant.guidance.ts | 9 +- packages/grant/src/commands/grant.ts | 27 ++- packages/grant/src/lib/grant/fee-wallet.ts | 19 ++- packages/grant/src/lib/grant/request.ts | 39 ++++- src/__tests__/command-flags.test.ts | 2 +- src/__tests__/grant-deposit-command.test.ts | 157 ++++++++++++++++++ src/__tests__/mcp-server-confirmation.test.ts | 15 ++ 10 files changed, 286 insertions(+), 31 deletions(-) create mode 100644 src/__tests__/grant-deposit-command.test.ts diff --git a/docs/SKILL.md b/docs/SKILL.md index 68b7b78d..9d65581c 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -114,7 +114,7 @@ A wallet's account is a contract its owner deploys. A grant lets an agent spend What has to be true first: Node.js is 22.18 or newer, and the network is `undeployed` (a local ledger-9 stack) or `stagenet` (where a grant request that pins its calling contract is refused with `CALLER_PIN_UNSUPPORTED`). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. 1. `midnight_grant_status()` says whether the wallet has an account. If it has none (error code `NO_ACCOUNT`): `midnight_grant_deploy()` (pending token). Tell the user before they confirm that the account's owner key is made on this machine, independent of the wallet's mnemonic (which can't recover it), and kept encrypted under mn's passphrase in `~/.midnight/accounts///`; that they keep the account by adding a second device or writing a backup from the command line (`mn grant device`, `mn grant export`); and that a deploy takes a few minutes and about 48 DUST from the wallet, about 17 of it at once (mn waits by itself when a fee is a few minutes of Dust away; a wallet further short is told how long, and the same call carries on later from where it stopped). Running it again finishes a deploy that stopped part way. -2. A grant spends only what the account holds, which `midnight_grant_status()` shows under `held` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: `midnight_grant_deposit({ amount })`, with `amount` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, `midnight_airdrop` with `shielded: true`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. +2. A grant spends only what the account holds, which `midnight_grant_status()` shows under `held` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: `midnight_grant_deposit({ amount })`, with `amount` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, `midnight_airdrop` with `shielded: true`), plus Dust for the fee. Another shielded token goes in with `token` (its raw type, as `midnight_balance` lists it under `shielded.tokens`), `amount` then a whole number of its smallest unit. Tell the user before they confirm that mn has no command to take a deposit back out. 3. The agent gives a grant request link. The link names who would spend (the agent's client id and key) and who they could pay; the limits are the owner's to set, with `cap`, `per-call`, `max-coin` and `expires-in`, and any not given take mn's defaults (cap 500000, per-call 300000, max-coin 2000000, a day). Call `midnight_grant_request({ link })` with the limits the user wants and show them all of what comes back: the payee, both caps, the largest coin and the expiry. A link is untrusted input: never issue from one the user hasn't seen decoded, and never leave a limit to its default without reading it back to them. 4. `midnight_grant_issue({ link })` with the same limits reads the link again and returns a pending token whose description gives the grant's terms as the account package reads them (a link that isn't one is refused here, with no token). Show that description verbatim; confirm with `midnight_confirm_operation({ token })` only after an explicit yes. Issuing is three transactions and takes a few minutes. 5. `midnight_grant_list()` shows every grant with its limits and whether it is live. `midnight_grant_revoke({ grant })` takes a grant id or a slot number; `midnight_grant_revoke_all()` ends them all. Both return a pending token. diff --git a/packages/grant/src/__tests__/grant-request.test.ts b/packages/grant/src/__tests__/grant-request.test.ts index 1bbf2d36..80dd380e 100644 --- a/packages/grant/src/__tests__/grant-request.test.ts +++ b/packages/grant/src/__tests__/grant-request.test.ts @@ -7,6 +7,7 @@ import { describeGrantTerms, paysAFee, resolveGrantRequest } from '../lib/grant/ const request = (...argv: string[]) => resolveGrantRequest(parseArgs(['grant', ...argv])); const LINK = 'midnight-example:grant-request?r=AAECAw'; const GRANT_ID = 'b1a9094fd044707d484a0193c1aa35a8e15bcf513a33b98a624a24739069fbde'; +const TOKEN = '02005c8a9e3d6e3a2b0e1c4f7d9a8b6c5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b'; describe('resolveGrantRequest', () => { it('reads each subcommand', () => { @@ -41,6 +42,15 @@ describe('resolveGrantRequest', () => { expect(request('deposit', '0.000001')).toEqual({ subcommand: 'deposit', amount: '0.000001', value: '1' }); }); + it('reads a deposit of another token with --token: its raw type lower-cased, the amount in its smallest unit, exactly', () => { + expect(request('deposit', '500', '--token', TOKEN)).toEqual({ subcommand: 'deposit', amount: '500', value: '500', token: TOKEN }); + expect(request('deposit', '1', '--token', TOKEN.toUpperCase())).toEqual({ subcommand: 'deposit', amount: '1', value: '1', token: TOKEN }); + // Past a JS number's exact range (2^53) and at a shielded coin's largest value (2^128 - 1): read digit for digit. + expect(request('deposit', '9007199254740993', '--token', TOKEN)).toMatchObject({ value: '9007199254740993' }); + expect(request('deposit', '340282366920938463463374607431768211455', '--token', TOKEN)).toMatchObject({ value: '340282366920938463463374607431768211455' }); + expect(paysAFee(request('deposit', '500', '--token', TOKEN))).toBe(true); + }); + it('reads an issue: the link, the limits given, and whether it is confirmed', () => { expect(request('issue', LINK)).toEqual({ subcommand: 'issue', link: LINK, limits: {}, confirmed: false }); expect(request('issue', LINK, '--cap', '500000', '--per-call', '300000', '--max-coin', '2000000', '--expires-in', '3600', '--yes')).toEqual({ @@ -66,6 +76,18 @@ describe('resolveGrantRequest', () => { [['deposit', '1.0000001'], 'NIGHT has 6 decimals, this has 7'], [['deposit', 'all'], 'Invalid amount: "all"'], [['deposit', '2', '--yes'], '--yes only applies to: midnight grant issue'], + [['deposit', '5', '--token', TOKEN.slice(1)], `--token must be a token type, 64 hex characters, not "${TOKEN.slice(1)}"`], + [['deposit', '5', '--token', `${TOKEN.slice(1)}g`], '--token must be a token type, 64 hex characters'], + [['deposit', '5', '--token', `0x${TOKEN}`], '--token must be a token type, 64 hex characters'], + [['deposit', '5', '--token'], '--token needs a value'], + [['deposit', '5', '--token', '00'.repeat(32)], '--token names NIGHT, which a deposit takes without it'], + [['deposit', '--token', TOKEN], 'Missing the amount of the token to deposit, in its smallest unit.'], + [['deposit', '5', '6', '--token', TOKEN], 'midnight grant deposit takes one amount of the token; unexpected: 6'], + [['deposit', '1.5', '--token', TOKEN], 'With --token the amount is a whole number of the token\'s smallest unit, above 0, not "1.5"'], + [['deposit', '0', '--token', TOKEN], 'above 0, not "0"'], + [['deposit', '-3', '--token', TOKEN], 'above 0, not "-3"'], + [['deposit', '1e6', '--token', TOKEN], 'above 0, not "1e6"'], + [['status', '--token', TOKEN], '--token only applies to: midnight grant deposit'], [['revoke'], 'Missing the grant to revoke.'], [['revoke', 'the-first-one'], 'A grant is named by its id (64 hex characters) or its slot (a number); got "the-first-one"'], [['status', '--yes'], '--yes only applies to: midnight grant issue'], diff --git a/packages/grant/src/commands/grant.definition.ts b/packages/grant/src/commands/grant.definition.ts index 95640111..85048b09 100644 --- a/packages/grant/src/commands/grant.definition.ts +++ b/packages/grant/src/commands/grant.definition.ts @@ -73,6 +73,17 @@ export const grantDefinition: CommandDefinition = { help: ['--per-call issue: the most one payment may be'], agent: { type: 'string', description: 'Most one payment may be' }, }, + { + name: 'token', + takesValue: true, + subcommands: ['deposit'], + help: [ + '--token deposit: the shielded token to deposit, by its raw type (64 hex', + ' characters, as balance lists it); the amount is then a whole number', + ' of the token\'s smallest unit. Without it: NIGHT, the amount in NIGHT', + ], + agent: { type: 'string', description: 'Shielded token to deposit, raw type (64 hex, as balance lists it); amount then in its smallest unit. Omit for NIGHT' }, + }, { name: 'wallet', takesValue: true, @@ -114,6 +125,7 @@ export const grantDefinition: CommandDefinition = { flags: [ 'deploy Deploy this wallet\'s account and activate its owner key', 'deposit Move NIGHT of this wallet\'s shielded NIGHT into its account', + ' (with --token, of that shielded token, in its smallest unit)', 'status The account, its owner key and what it holds', 'list Every grant on the account', 'issue Show the grant an agent\'s request link would get; issue it with --yes', @@ -131,6 +143,7 @@ export const grantDefinition: CommandDefinition = { { flag: 'per-call' }, { flag: 'max-coin' }, { flag: 'expires-in' }, + { flag: 'token' }, { flag: 'wallet' }, { flag: 'network' }, { flag: 'node' }, @@ -141,6 +154,7 @@ export const grantDefinition: CommandDefinition = { examples: [ 'midnight grant deploy', 'midnight grant deposit 2', + 'midnight grant deposit 500 --token ', 'midnight grant status', 'midnight grant issue \'\'', 'midnight grant issue \'\' --cap 500000 --yes', @@ -161,7 +175,8 @@ export const grantDefinition: CommandDefinition = { request: 'Who would spend, who they can pay, and the limits the grant gets (issue)', grantId: 'The issued grant\'s id (issue with --yes)', revoked: 'The revoked grant\'s id (revoke)', - amount: 'The NIGHT deposited, as given (deposit)', + amount: 'The amount deposited, as given: NIGHT, or with --token the token\'s smallest unit (deposit)', + token: 'The raw type of the token deposited, when it is not NIGHT (deposit with --token)', value: 'The same in the token\'s smallest unit, as status and --cap count it (deposit)', txHash: 'The deposit\'s transaction (deposit)', blockHeight: 'The block it landed in (deposit)', @@ -227,10 +242,11 @@ export const grantDefinition: CommandDefinition = { }, { name: 'midnight_grant_deposit', - description: 'Move shielded NIGHT from the wallet into its account, where a grant lets an agent spend it (returns pending token). The wallet needs that much shielded NIGHT, plus Dust for the fee. mn has no command to take it back out.', + description: 'Move shielded NIGHT, or another shielded token with token, from the wallet into its account, where a grant lets an agent spend it (returns pending token). The wallet needs that much of it shielded, plus Dust for the fee. mn has no command to take it back out.', annotations: { destructiveHint: true, openWorldHint: true }, params: [ - { name: 'amount', schema: { type: 'string', description: 'NIGHT to deposit, e.g. "2" (up to 6 decimals)' } }, + { name: 'amount', schema: { type: 'string', description: 'NIGHT to deposit, e.g. "2" (up to 6 decimals); with token, a whole number of its smallest unit' } }, + { flag: 'token' }, { flag: 'wallet' }, { flag: 'network' }, ], @@ -241,7 +257,8 @@ export const grantDefinition: CommandDefinition = { async check(params, call) { const { request, walletName, target, account } = await checkGrant(params, call); if (request.subcommand !== 'deposit' || account === null) throw new Error('A deposit was prepared as something else'); - return `Deposit ${request.amount} shielded NIGHT (${request.value} in the smallest unit) from wallet ${walletName} into its account ${account.address} on ${target.network}`; + const what = request.token === undefined ? `${request.amount} shielded NIGHT (${request.value} in the smallest unit)` : `${request.value} of shielded token ${request.token} (in its smallest unit)`; + return `Deposit ${what} from wallet ${walletName} into its account ${account.address} on ${target.network}`; }, }, order: 32, diff --git a/packages/grant/src/commands/grant.guidance.ts b/packages/grant/src/commands/grant.guidance.ts index 451ec74d..4bba51dc 100644 --- a/packages/grant/src/commands/grant.guidance.ts +++ b/packages/grant/src/commands/grant.guidance.ts @@ -51,13 +51,16 @@ that calls it (a request that names one is refused, CALLER_PIN_UNSUPPORTED). (~/.midnight/accounts///) encrypted under mn's passphrase. - midnight grant deposit [--json] - → { address, amount, value, txHash, blockHeight, network, wallet, ownerKey } + midnight grant deposit [--token ] [--json] + → { address, amount, value, token?, txHash, blockHeight, network, wallet, ownerKey } Moves NIGHT (up to 6 decimals) of the wallet's shielded NIGHT into its account, where grants spend from; status then shows it held. The wallet needs that much shielded NIGHT (on a local chain: airdrop --shielded) and Dust for the fee. Anyone may deposit, so the owner key signs nothing. mn has no command to take it back out. + With --token (a raw shielded token type, 64 hex, as balance + lists it under shielded.tokens) it moves that token instead, + a whole number of its smallest unit; the wallet needs that much of it. midnight grant status [--json] → { account, device: { arm, useCounter }, devices, authNonce, encKey, grants, held } @@ -153,7 +156,7 @@ A wallet's account is a contract its owner deploys. A grant lets an agent spend What has to be true first: Node.js is 22.18 or newer, and the network is \`undeployed\` (a local ledger-9 stack) or \`stagenet\` (where a grant request that pins its calling contract is refused with \`CALLER_PIN_UNSUPPORTED\`). The first grant tool also needs to reach github.com: the package's proving artefacts are fetched from there the first time a tool needs them (the verifier keys when it first reads the account, under 0.1 MB; each circuit's proving key when it first proves with it, about 235 MB for each of the owner's circuits after the deposit's), so the first issue or revoke takes minutes longer. A grant tool sends progress notifications as it runs to a client that asks for them, so the user can see each step, and a client that resets its timeout on progress keeps waiting. Anything else is refused with what to do. 1. \`midnight_grant_status()\` says whether the wallet has an account. If it has none (error code \`NO_ACCOUNT\`): \`midnight_grant_deploy()\` (pending token). Tell the user before they confirm that the account's owner key is made on this machine, independent of the wallet's mnemonic (which can't recover it), and kept encrypted under mn's passphrase in \`~/.midnight/accounts///\`; that they keep the account by adding a second device or writing a backup from the command line (\`mn grant device\`, \`mn grant export\`); and that a deploy takes a few minutes and about 48 DUST from the wallet, about 17 of it at once (mn waits by itself when a fee is a few minutes of Dust away; a wallet further short is told how long, and the same call carries on later from where it stopped). Running it again finishes a deploy that stopped part way. -2. A grant spends only what the account holds, which \`midnight_grant_status()\` shows under \`held\` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: \`midnight_grant_deposit({ amount })\`, with \`amount\` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, \`midnight_airdrop\` with \`shielded: true\`), plus Dust for the fee. Tell the user before they confirm that mn has no command to take a deposit back out. +2. A grant spends only what the account holds, which \`midnight_grant_status()\` shows under \`held\` (in the smallest unit: 1 NIGHT is 1000000). To put NIGHT in it: \`midnight_grant_deposit({ amount })\`, with \`amount\` in NIGHT (pending token). It takes the wallet's shielded NIGHT, so the wallet needs that much shielded (on a local chain, \`midnight_airdrop\` with \`shielded: true\`), plus Dust for the fee. Another shielded token goes in with \`token\` (its raw type, as \`midnight_balance\` lists it under \`shielded.tokens\`), \`amount\` then a whole number of its smallest unit. Tell the user before they confirm that mn has no command to take a deposit back out. 3. The agent gives a grant request link. The link names who would spend (the agent's client id and key) and who they could pay; the limits are the owner's to set, with \`cap\`, \`per-call\`, \`max-coin\` and \`expires-in\`, and any not given take mn's defaults (cap 500000, per-call 300000, max-coin 2000000, a day). Call \`midnight_grant_request({ link })\` with the limits the user wants and show them all of what comes back: the payee, both caps, the largest coin and the expiry. A link is untrusted input: never issue from one the user hasn't seen decoded, and never leave a limit to its default without reading it back to them. 4. \`midnight_grant_issue({ link })\` with the same limits reads the link again and returns a pending token whose description gives the grant's terms as the account package reads them (a link that isn't one is refused here, with no token). Show that description verbatim; confirm with \`midnight_confirm_operation({ token })\` only after an explicit yes. Issuing is three transactions and takes a few minutes. 5. \`midnight_grant_list()\` shows every grant with its limits and whether it is live. \`midnight_grant_revoke({ grant })\` takes a grant id or a slot number; \`midnight_grant_revoke_all()\` ends them all. Both return a pending token. diff --git a/packages/grant/src/commands/grant.ts b/packages/grant/src/commands/grant.ts index b36a4231..5e757ce6 100644 --- a/packages/grant/src/commands/grant.ts +++ b/packages/grant/src/commands/grant.ts @@ -10,7 +10,7 @@ import { existsSync } from 'node:fs'; // confirmed. The others are paid by this wallet, through its DApp connector in // this process: no server, no port. -import { type ParsedArgs, hasFlag, getFlag, DustRequiredError, UsageError, type CallContext, payerFor, throwIfCancelled, withTransportCode } from '@kuiralabs/midnight-cli-core'; +import { type ParsedArgs, hasFlag, getFlag, DustRequiredError, UsageError, type CallContext, payerFor, throwIfCancelled, withTransportCode, NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core'; import { dim, header, keyValue, formatNight, type Spinner } from '@kuiralabs/midnight-cli-core/ui'; import { accountChainFor } from '../lib/grant/account-chain.ts'; import { type GrantAccount, openGrantAccount, ownerDeviceOf } from '../lib/grant/account.ts'; @@ -47,6 +47,14 @@ function shortOfShieldedNight(held: bigint, value: bigint): UsageError { ); } +/** The same refusal for a deposit of another token, by its raw type, both amounts in its smallest unit. */ +function shortOfShieldedToken(token: string, held: bigint, value: bigint): UsageError { + return new UsageError( + `Not enough of token ${token} for this deposit: the wallet holds ${held} of it shielded and the deposit takes ${value}, in the token's smallest unit. ` + + 'midnight balance lists the wallet\'s shielded tokens by their raw type, with what it holds of each.', + ); +} + export default async function grantCommand(args: ParsedArgs, ctx: CallContext): Promise { const { request, target, walletName, recordsDir, account } = await prepareGrant(args, ctx.config.paths.stateRoot, ctx.host); const jsonMode = hasFlag(args, 'json'); @@ -64,7 +72,7 @@ export default async function grantCommand(args: ParsedArgs, ctx: CallContext): // Reading the account or a request submits nothing: a wallet with no Dust can still do it, and none is opened. const payer = paysAFee(request) ? payerFor(`grant ${request.subcommand}`, ctx) : undefined; const funds = payer ? await payer.assertCanPay(target, walletFlag, spinnerFor('Checking wallet...'), ctx.signal) : undefined; - const paying = payer ? await openPayingWallet(payer, target, (await accountChainFor(ctx.host.engines, target.network)).connector, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal) : undefined; + const paying = payer ? await openPayingWallet(payer, target, (await accountChainFor(ctx.host.engines, target.network)).connector, walletFlag, spinnerFor('Opening the wallet...'), ctx.sdkWarnings, ctx.signal, request.subcommand === 'deposit' ? { shielded: true } : undefined) : undefined; try { await runOwned(request, { target, walletName, recordsDir, account, jsonMode, paying, funds, spinnerFor }, ctx); } finally { @@ -183,17 +191,22 @@ async function runOwned(request: GrantRequest, { target, walletName, recordsDir, const { connectOver, depositShielded } = owned.chain.deposit; if (account === null) throw new Error('A deposit was prepared without an account'); const wallet = await payingWallet(); + const { token } = request; const value = BigInt(request.value); - const held = await wallet.shieldedNight(); - if (held < value) throw shortOfShieldedNight(held, value); + const held = await wallet.shieldedBalance(token ?? NATIVE_TOKEN_TYPE); + if (held < value) throw token === undefined ? shortOfShieldedNight(held, value) : shortOfShieldedToken(token, held, value); const connection = await connectOver(owned.context, account.address, wallet.feeWallet, owned.location, async () => {}); - const { result } = await depositShielded(connection, value); - const outcome = { address: account.address, value: request.value, txHash: result.public.txHash, blockHeight: Number(result.public.blockHeight) }; + // NIGHT is the package's default color; another token's color is its raw type's 32 bytes. + const { result } = await (token === undefined ? depositShielded(connection, value) : depositShielded(connection, value, new Uint8Array(Buffer.from(token, 'hex')))); + const outcome = { address: account.address, value: request.value, ...(token === undefined ? {} : { token }), txHash: result.public.txHash, blockHeight: Number(result.public.blockHeight) }; spinner.stop('Deposited'); if (jsonMode) { ctx.output.result({ ...common, amount: request.amount, ...outcome }); } else { - ctx.output.stderr('\n' + keyValue('Deposited', `${request.amount} NIGHT (${outcome.value} in the smallest unit, as status and --cap count)`) + '\n'); + const deposited = token === undefined + ? `${request.amount} NIGHT (${outcome.value} in the smallest unit, as status and --cap count)` + : `${request.amount} of token ${token}, in its smallest unit`; + ctx.output.stderr('\n' + keyValue('Deposited', deposited) + '\n'); ctx.output.stderr(keyValue('Block', String(outcome.blockHeight)) + '\n'); ctx.output.stderr(keyValue('Transaction', outcome.txHash) + '\n'); ctx.output.stderr('\n' + dim(' Next: midnight grant status') + '\n\n'); diff --git a/packages/grant/src/lib/grant/fee-wallet.ts b/packages/grant/src/lib/grant/fee-wallet.ts index 4f4172a8..26cb654b 100644 --- a/packages/grant/src/lib/grant/fee-wallet.ts +++ b/packages/grant/src/lib/grant/fee-wallet.ts @@ -3,30 +3,33 @@ import type { FeeWallet } from '@kuiralabs/midnight-account-chain/owner'; import type { AccountChain } from './account-chain.ts'; -import { NATIVE_TOKEN_TYPE, type Payer, type PayingTarget, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; +import { type ConnectOptions, type Payer, type PayingTarget, type CallSdkWarnings } from '@kuiralabs/midnight-cli-core'; import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; /** A fee wallet in this process, and how to stop it. */ export interface PayingWallet { feeWallet: FeeWallet; - /** The shielded NIGHT the synced wallet holds, in the smallest unit. */ - shieldedNight: () => Promise; + /** What the synced wallet holds shielded of the token whose raw type is `tokenType`, in its smallest unit. */ + shieldedBalance: (tokenType: string) => Promise; stop: () => Promise; } -/** The payer's wallet for `target`, as the fee wallet of the account package's `connector` (the network engine's), keeping the SDK's warnings to the paying call's `sdkWarnings`. Stopping it stops the wallet. */ -export async function openPayingWallet(payer: Payer, target: PayingTarget, connector: AccountChain['connector'], wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined): Promise { +/** + * The payer's wallet for `target`, as the fee wallet of the account package's `connector` (the network engine's), keeping the SDK's warnings to the paying call's `sdkWarnings`. Stopping it stops the wallet. + * `options` asks for the shielded side to be synced, which a deposit spends from (stagenet skips it otherwise). + */ +export async function openPayingWallet(payer: Payer, target: PayingTarget, connector: AccountChain['connector'], wallet: string | undefined, progress: Spinner, sdkWarnings: CallSdkWarnings, signal: AbortSignal | undefined, options?: ConnectOptions): Promise { const { feeWalletOver } = connector; - const session = await payer.connect(target, wallet, progress, sdkWarnings, signal); + const session = await payer.connect(target, wallet, progress, sdkWarnings, signal, options); try { const feeWallet = await feeWalletOver({ getShieldedAddresses: () => session.addresses(), balanceUnsealedTransaction: async (tx) => ({ tx: await session.balanceTransaction(tx) }), submitTransaction: (tx) => session.submit(tx), }); - const shieldedNight = async (): Promise => (await session.balances()).shielded[NATIVE_TOKEN_TYPE] ?? 0n; + const shieldedBalance = async (tokenType: string): Promise => (await session.balances()).shielded[tokenType] ?? 0n; progress.stop('Wallet ready'); - return { feeWallet, shieldedNight, stop: () => session.close() }; + return { feeWallet, shieldedBalance, stop: () => session.close() }; } catch (err) { await session.close(); throw err; diff --git a/packages/grant/src/lib/grant/request.ts b/packages/grant/src/lib/grant/request.ts index 34692287..6af3823f 100644 --- a/packages/grant/src/lib/grant/request.ts +++ b/packages/grant/src/lib/grant/request.ts @@ -3,7 +3,7 @@ // server before it issues a confirmation token. import { parseDeviceCode } from './device-code.ts'; -import { type ParsedArgs, getFlag, hasFlag, UsageError, parseAmount } from '@kuiralabs/midnight-cli-core'; +import { type ParsedArgs, getFlag, hasFlag, UsageError, parseAmount, NATIVE_TOKEN_TYPE } from '@kuiralabs/midnight-cli-core'; export const GRANT_SUBCOMMANDS = ['deploy', 'deposit', 'status', 'list', 'issue', 'revoke', 'revoke-all', 'export', 'import', 'device'] as const; @@ -14,8 +14,12 @@ export type GrantSubcommand = typeof GRANT_SUBCOMMANDS[number]; export type GrantRequest = | { subcommand: 'deploy' } - /** `amount` as given, in NIGHT; `value` the same in the smallest unit, as decimal text. */ - | { subcommand: 'deposit'; amount: string; value: string } + /** + * `amount` as given: in NIGHT, or with `token` in that token's smallest unit; + * `value` the same in the smallest unit, as decimal text. `token` is the raw + * shielded token type (64 hex, lower-cased), absent for NIGHT. + */ + | { subcommand: 'deposit'; amount: string; value: string; token?: string } | { subcommand: 'status' } | { subcommand: 'list' } | { subcommand: 'issue'; link: string; limits: GrantLimits; confirmed: boolean } @@ -47,7 +51,7 @@ const LIMIT_FLAGS = [['cap', 'cap'], ['per-call', 'perCall'], ['max-coin', 'maxC export const GRANT_USAGE = `Usage: midnight grant <${GRANT_SUBCOMMANDS.join('|')}>\n\n` + ` deploy Deploy this wallet's account, which holds what an agent may spend\n` + - ` deposit Move shielded NIGHT from this wallet into its account\n` + + ` deposit Move shielded NIGHT, or another shielded token, from this wallet into its account\n` + ` status The account, its owner key and what it holds\n` + ` list Every grant on the account\n` + ` issue Show a grant request (an agent's link); issue it with --yes\n` + @@ -62,6 +66,19 @@ export function isGrantSubcommand(value: string | undefined): value is GrantSubc return (GRANT_SUBCOMMANDS as readonly string[]).includes(value ?? ''); } +/** A raw shielded token type for --token: 64 hex characters, as `mn balance` lists it under shielded.tokens. NIGHT's own (all zeros) is refused: NIGHT is the default and counts in NIGHT, not its smallest unit. */ +function depositTokenOf(token: string): string { + if (!/^[0-9a-fA-F]{64}$/.test(token)) throw new UsageError(`--token must be a token type, 64 hex characters, not "${token}"`); + if (token === NATIVE_TOKEN_TYPE) throw new UsageError('--token names NIGHT, which a deposit takes without it: leave --token out and give the amount in NIGHT'); + return token.toLowerCase(); +} + +/** A deposit's amount of a token other than NIGHT: a whole number of its smallest unit, read exactly. */ +function tokenValueOf(amount: string): bigint { + if (!/^[1-9][0-9]*$/.test(amount)) throw new UsageError(`With --token the amount is a whole number of the token's smallest unit, above 0, not "${amount}"`); + return BigInt(amount); +} + /** A grant's id (32 bytes of hex) or its slot number. */ const GRANT_TARGET = /^(?:[0-9a-fA-F]{64}|\d+)$/; @@ -85,15 +102,23 @@ export function resolveGrantRequest(args: ParsedArgs): GrantRequest { onlyFor(args, subcommand, [...LIMIT_FLAGS.map(([flag]) => flag), 'yes'], ['issue']); onlyFor(args, subcommand, ['backup'], ['device']); + onlyFor(args, subcommand, ['token'], ['deposit']); switch (subcommand) { case 'deploy': positionalsFor(args, subcommand, 0, 'no argument'); return { subcommand }; case 'deposit': { - const [amount] = positionalsFor(args, subcommand, 1, 'one amount of NIGHT'); - if (amount === undefined) throw new UsageError('Missing the amount of NIGHT to deposit.\nUsage: midnight grant deposit '); - return { subcommand, amount, value: parseAmount(amount).toString() }; + const flag = getFlag(args, 'token'); + if (flag === undefined) { + const [amount] = positionalsFor(args, subcommand, 1, 'one amount of NIGHT'); + if (amount === undefined) throw new UsageError('Missing the amount of NIGHT to deposit.\nUsage: midnight grant deposit '); + return { subcommand, amount, value: parseAmount(amount).toString() }; + } + const token = depositTokenOf(flag); + const [amount] = positionalsFor(args, subcommand, 1, 'one amount of the token'); + if (amount === undefined) throw new UsageError('Missing the amount of the token to deposit, in its smallest unit.\nUsage: midnight grant deposit --token '); + return { subcommand, amount, value: tokenValueOf(amount).toString(), token }; } case 'status': case 'list': diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 0ced72ac..09068783 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -101,7 +101,7 @@ describe('the accepted flags match the code', () => { 'resolvePayingTarget(': ['network', 'node', 'indexer-ws', 'proof-server'], 'networkChoiceFromArgs(': ['network', 'node', 'indexer-ws', 'proof-server'], // Reads the request's flags, and the network and endpoints. - 'prepareGrant(': ['backup', 'cap', 'expires-in', 'max-coin', 'per-call', 'yes', 'network', 'node', 'indexer-ws', 'proof-server', 'wallet'], + 'prepareGrant(': ['backup', 'cap', 'expires-in', 'max-coin', 'per-call', 'token', 'yes', 'network', 'node', 'indexer-ws', 'proof-server', 'wallet'], // The swap request's terms and expiry, and the network and endpoints. 'prepareMake(': ['give', 'give-token', 'want', 'want-token', 'expires-in', 'out', 'network', 'node', 'indexer-ws', 'proof-server'], 'prepareTake(': ['give', 'give-token', 'want', 'want-token', 'network', 'node', 'indexer-ws', 'proof-server'], diff --git a/src/__tests__/grant-deposit-command.test.ts b/src/__tests__/grant-deposit-command.test.ts new file mode 100644 index 00000000..0fe2c85a --- /dev/null +++ b/src/__tests__/grant-deposit-command.test.ts @@ -0,0 +1,157 @@ +// `grant deposit` through the command as the shell runs it, up to the account +// package's deposit: which balance the pre-check reads, what it refuses with, +// and what the deposit is called with, for NIGHT and for another token. Nothing +// reaches a chain: the payer stands in for the wallet session (it opens no +// wallet), and the network's engine is the one mn ships, with only the account +// package's deposit entry point standing in, where the package would reach the +// indexer and the proof server. The state root is the test's own, never ~/.midnight. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as fs from 'node:fs'; +import { tmpdir } from 'node:os'; +import * as path from 'node:path'; +import { createHost, parseArgs, NATIVE_TOKEN_TYPE, UsageError, type Host, type Payer, type WalletSession } from '@kuiralabs/midnight-cli-core'; +import { grantDefinition } from '@kuiralabs/midnight-grant/commands'; +import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; +import { loadInstalledEngine } from '../../test-support/test-host.ts'; +import { stateRootIn } from '../../test-support/state-root-in.ts'; +import { cliCall } from './helpers/cli-call.ts'; + +// The handler, as the shell loads it. +const { default: grantCommand } = await grantDefinition.load(); + +const ACCOUNT = '5e'.repeat(32); +const TOKEN = '02005c8a9e3d6e3a2b0e1c4f7d9a8b6c5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b'; +const TX_HASH = 'c4'.repeat(32); +const ENDPOINTS = ['--network', 'undeployed', '--node', 'ws://localhost:29944', '--indexer-ws', 'ws://localhost:28088/api/v4/graphql/ws', '--proof-server', 'http://localhost:26300']; + +/** One call of the account package's depositShielded: every argument after the connection, as given. */ +type DepositCall = unknown[]; + +let home: string; +let io: CapturedOutput; +let deposits: DepositCall[]; +let connections: number; + +beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'mn-grant-deposit-'))); + // An account an earlier mn wrote in plain text for alice: opened without a passphrase. + const records = path.join(stateRootIn(home), 'accounts', 'undeployed', 'alice'); + fs.mkdirSync(records, { recursive: true, mode: 0o700 }); + fs.writeFileSync(path.join(records, 'owner.json'), JSON.stringify({ contractAddress: ACCOUNT, deviceArm: 'k1', deviceSk: '4f'.repeat(32), bootSalt: '3a'.repeat(32), encryptionSecret: '2b'.repeat(32) }), { mode: 0o600 }); + io = captureOutput(); + deposits = []; + connections = 0; +}); + +afterEach(() => { + io.restore(); + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A host on the test's state root whose engines are mn's own, the account package's deposit entry point recording its calls. */ +function hostRecordingDeposits(): Host { + return createHost({ + paths: { stateRoot: stateRootIn(home), home }, + engineLoader: async (set, loading) => { + const engine = await loadInstalledEngine(set, loading); + return { + ...engine, + account: async () => ({ + ...(await engine.account()), + deposit: { + connectOver: async () => { connections += 1; return {}; }, + depositShielded: async (_connection: unknown, ...rest: unknown[]) => { + deposits.push(rest); + return { coin: {}, result: { public: { txHash: TX_HASH, blockHeight: 42n } } }; + }, + }, + }), + }; + }, + }); +} + +/** A payer whose wallet holds `shielded` (raw token type to smallest units) and Dust to pay with; its session reads balances and addresses, nothing else. */ +function payerHolding(shielded: Record): Payer { + const unused = async (): Promise => { throw new Error('not used by a deposit before the account package submits'); }; + const session: WalletSession = { + network: 'undeployed', + addresses: async () => ({ unshielded: 'mn_addr_undeployed1alice', shielded: 'mn_shield-addr_undeployed1alice', shieldedCoinPublicKey: '11'.repeat(32), shieldedEncryptionPublicKey: '22'.repeat(32), dust: 'mn_dust_undeployed1alice' }), + balances: async () => ({ unshielded: {}, shielded, dust: 10n ** 18n }), + balanceTransaction: unused, + swap: unused, + makeOffer: unused, + takeOffer: unused, + cancelOffers: unused, + sign: unused, + submit: unused, + readTransaction: unused, + close: async () => {}, + }; + return { + assertCanPay: async () => ({ nightBalance: 10n ** 12n, dustBalance: 10n ** 18n }), + serve: unused, + connect: async (_target, _wallet, _progress, _sdkWarnings, _signal, options) => { connectOptions.push(options); return session; }, + }; +} + +/** What each connect was asked for: a deposit spends shielded coins, so it asks for the shielded side synced (stagenet skips it otherwise). */ +const connectOptions: unknown[] = []; + +const deposit = (payer: Payer, ...argv: string[]) => + cliCall(grantCommand, parseArgs(['grant', 'deposit', ...argv, '--wallet', 'alice', ...ENDPOINTS, '--json']), { host: hostRecordingDeposits(), payer }); + +/** The JSON result the call wrote to stdout. */ +const resultLine = (): Record => JSON.parse(io.stdout().trim().split('\n').at(-1)!) as Record; + +describe('grant deposit --token', () => { + it('asks its wallet for the shielded side synced: the coins it deposits are shielded (regression: stagenet read 0)', async () => { + connectOptions.length = 0; + await deposit(payerHolding({ [NATIVE_TOKEN_TYPE]: 0n, [TOKEN]: 10n }), '5', '--token', TOKEN); + expect(connectOptions).toEqual([{ shielded: true }]); + }); + + it('deposits the token: the account package gets the value exactly and the raw type\'s 32 bytes as the color', async () => { + const value = 340282366920938463463374607431768211455n; + await deposit(payerHolding({ [NATIVE_TOKEN_TYPE]: 0n, [TOKEN]: value }), value.toString(), '--token', TOKEN.toUpperCase()); + + expect(deposits).toEqual([[value, new Uint8Array(Buffer.from(TOKEN, 'hex'))]]); + expect(resultLine()).toMatchObject({ subcommand: 'deposit', address: ACCOUNT, amount: value.toString(), value: value.toString(), token: TOKEN, txHash: TX_HASH, blockHeight: 42 }); + }); + + it('refuses before anything is built when the wallet holds less of the token, naming it and both amounts', async () => { + // Plenty of shielded NIGHT: the check reads the token's balance, not NIGHT's. + const outcome = deposit(payerHolding({ [NATIVE_TOKEN_TYPE]: 10n ** 12n, [TOKEN]: 499n }), '500', '--token', TOKEN); + + await expect(outcome).rejects.toThrow(UsageError); + await expect(outcome).rejects.toThrow(`Not enough of token ${TOKEN} for this deposit: the wallet holds 499 of it shielded and the deposit takes 500, in the token's smallest unit.`); + expect(connections).toBe(0); + expect(deposits).toEqual([]); + }); + + it('refuses a token the wallet holds none of', async () => { + await expect(deposit(payerHolding({ [NATIVE_TOKEN_TYPE]: 10n ** 12n }), '1', '--token', TOKEN)).rejects.toThrow(`the wallet holds 0 of it shielded and the deposit takes 1,`); + expect(deposits).toEqual([]); + }); +}); + +describe('grant deposit of NIGHT, without --token', () => { + it('calls the deposit with the value alone, the package\'s default color (NIGHT), and names no token', async () => { + await deposit(payerHolding({ [NATIVE_TOKEN_TYPE]: 2_000_000n, [TOKEN]: 10n ** 9n }), '2'); + + expect(deposits).toEqual([[2_000_000n]]); + const result = resultLine(); + expect(result).toMatchObject({ subcommand: 'deposit', address: ACCOUNT, amount: '2', value: '2000000', txHash: TX_HASH, blockHeight: 42 }); + expect(result).not.toHaveProperty('token'); + }); + + it('refuses on the shielded NIGHT, in NIGHT, however much of another token the wallet holds', async () => { + const outcome = deposit(payerHolding({ [NATIVE_TOKEN_TYPE]: 1_500_000n, [TOKEN]: 10n ** 9n }), '2'); + + await expect(outcome).rejects.toThrow(UsageError); + await expect(outcome).rejects.toThrow('Not enough shielded NIGHT for this deposit: the wallet holds 1.500000 NIGHT shielded and the deposit takes 2.000000 NIGHT.'); + expect(connections).toBe(0); + expect(deposits).toEqual([]); + }); +}); diff --git a/src/__tests__/mcp-server-confirmation.test.ts b/src/__tests__/mcp-server-confirmation.test.ts index 6e5366da..655ef23e 100644 --- a/src/__tests__/mcp-server-confirmation.test.ts +++ b/src/__tests__/mcp-server-confirmation.test.ts @@ -141,6 +141,21 @@ describe('midnight_grant_deposit', () => { expect(JSON.parse(fs.readFileSync(path.join(recordsDir, 'owner.json'), 'utf8'))).toEqual(OWNER_RECORD); }, 60_000); + it('names the token, by its raw type, and the amount in its smallest unit when one is given', async () => { + const token = '02005c8a9e3d6e3a2b0e1c4f7d9a8b6c5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b'; + const pending = await call('midnight_grant_deposit', { amount: '9007199254740993', token, wallet: 'alice', network: 'undeployed', ...ENDPOINTS }); + + expect(pending.error, String(pending.message)).toBeUndefined(); + expect(pending.description).toBe(`Deposit 9007199254740993 of shielded token ${token} (in its smallest unit) from wallet alice into its account ${ACCOUNT} on undeployed${VIA}`); + expect(fs.readdirSync(recordsDir)).toEqual(['owner.json']); + }, 60_000); + + it('refuses a token that is not a raw token type before any token is given', async () => { + const refused = await call('midnight_grant_deposit', { amount: '5', token: 'night', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }); + expect(refused).toMatchObject({ error: true, code: 'INVALID_ARGS' }); + expect(refused.token).toBeUndefined(); + }, 60_000); + it('refuses a deposit that can\'t run before any token is given', async () => { const refused = await call('midnight_grant_deposit', { amount: '1.0000001', wallet: 'alice', network: 'undeployed', ...ENDPOINTS }); expect(refused).toMatchObject({ error: true, code: 'INVALID_ARGS' }); From 8fe90ef77d11c1661cf403a1d97873ef46cd42f0 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 08:07:55 -0800 Subject: [PATCH 78/88] release 0.6.0-rc.13 mn grant on stagenet, grant deposit of any shielded token, mn split into packages with named entry points and library functions, error codes owned per package, the host passed in, and engines that let a program end. Every @kuiralabs workspace package moves to the shared 0.1.0-rc.2; mn to 0.6.0-rc.13. --- CHANGELOG.md | 36 +++++++++++++ package-lock.json | 84 +++++++++++++++---------------- package.json | 20 ++++---- packages/chain/package.json | 4 +- packages/cli-core/package.json | 2 +- packages/connect/package.json | 8 +-- packages/contract/package.json | 8 +-- packages/dev/package.json | 12 ++--- packages/engine-beta/package.json | 6 +-- packages/engine-rc/package.json | 6 +-- packages/grant/package.json | 10 ++-- packages/wallet/package.json | 6 +-- 12 files changed, 119 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8349215a..f9774c2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,42 @@ All notable changes to midnight-wallet-cli will be documented in this file. ## [Unreleased] +## [0.6.0-rc.13] - 2026-11-04 + +### Added + +- **`mn grant` on stagenet.** Grants now work on both SDK sets. Each engine carries its own copy of `@kuiralabs/midnight-account-chain` 0.3.0-rc.2, and grant uses the loaded engine's copy: the stagenet build on stagenet (no caller pin), the full build on ledger-9 local chains. On stagenet, a request that names a caller is refused before any transaction (`CALLER_PIN_UNSUPPORTED`, exit 2). +- **`mn grant deposit --token `** deposits any shielded token into the account. Give the raw type as `mn balance` lists it, and the amount in the token's smallest unit. Without `--token` it deposits NIGHT, as before. +- **Programs can use mn's packages directly.** mn is split into packages, each with named entry points: + - core: `.`, `./engine`, `./ui`, `./commands`, `./process` + - chain and every domain package: `.` and `./commands` + - each engine: `.` + - the domain packages: `@kuiralabs/midnight-wallet` (with swap), `-contract`, `-connect`, `-dev` and `-grant` + + A program creates a host with `createHost` (its own state folder, settings, notices and engine) and passes it in. Two hosts in one process don't mix. Each command's work is a library function: `readWalletBalance`, `transferNight`, `airdropNight`, `registerDust`, `deployContract`, `makeSwapOffer`, `takeSwapOffer`, `transactionStatus` and the rest. Each takes plain values, and amounts are exact bigints. `openWalletSession` is exported again. `installSdkProcessGuard` and `syncHeapAdvice` give a program what mn's shell does for its own process; see "Your process" in core's README. +- **Error codes are owned per package and classified by code alone**, never by message text. Each command's help, the manuals and the MCP tool descriptions list the codes it can end with. New codes: `NO_STATE_ROOT`, `NO_PAYER`, `NO_NODE_RUNTIME`, `COMMAND_FAILED`, `CALLER_PIN_UNSUPPORTED`. + +### Changed + +- **Error codes that changed:** + - A missing passphrase reports `PASSPHRASE_REQUIRED` on the CLI too; it used to report `INVALID_ARGS`. + - A wallet with no NIGHT reports `INSUFFICIENT_BALANCE`. + - An unreachable indexer, node or proof server reports `NETWORK_ERROR`, whatever its message says. + - A ZK proof that times out reports `PROOF_TIMEOUT`. + - A contract script's refused transaction reports `TX_REJECTED` (or the stale-UTXO or Dust-proof code). + - Errors that only matched a code by accident of wording now report `UNKNOWN`. + - Bad-argument errors print as "Usage". +- **Exact amounts:** amounts are exact end to end, and an amount too large for a JS number is no longer refused. + +### Fixed + +- **Programs end after `close()`:** a program ends after `session.close()`. The engines open their node submission client only on the first submit, so a session that never submitted no longer keeps reconnecting to an unreachable node. +- **Shielded deposits on stagenet:** a grant deposit syncs the wallet's shielded side, as swaps do. On stagenet it used to see no shielded coins. + +### Packages + +- Every `@kuiralabs` workspace package now shares one version, `0.1.0-rc.2`. The existing ones are core, chain, engine-rc and engine-beta. The new ones are wallet, connect, contract, dev and grant. Both engines pin `@kuiralabs/midnight-account-chain` 0.3.0-rc.2. + ## [0.6.0-rc.12] - 2026-11-03 ### Added diff --git a/package-lock.json b/package-lock.json index 706824f7..c6216d8f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.12", + "version": "0.6.0-rc.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.12", + "version": "0.6.0-rc.13", "license": "Apache-2.0", "workspaces": [ "packages/connector", @@ -21,15 +21,15 @@ "packages/grant" ], "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-connect": "0.1.0-rc.1", - "@kuiralabs/midnight-contract": "0.1.0-rc.1", - "@kuiralabs/midnight-dev": "0.1.0-rc.1", - "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", - "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", - "@kuiralabs/midnight-grant": "0.1.0-rc.1", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-connect": "0.1.0-rc.2", + "@kuiralabs/midnight-contract": "0.1.0-rc.2", + "@kuiralabs/midnight-dev": "0.1.0-rc.2", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.2", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.2", + "@kuiralabs/midnight-grant": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2", "@modelcontextprotocol/sdk": "^1.27.1" }, "bin": { @@ -5732,10 +5732,10 @@ }, "packages/chain": { "name": "@kuiralabs/midnight-chain", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "ws": "^8.19.0" }, "engines": { @@ -5744,7 +5744,7 @@ }, "packages/cli-core": { "name": "@kuiralabs/midnight-cli-core", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "engines": { "node": ">=22" @@ -5752,12 +5752,12 @@ }, "packages/connect": { "name": "@kuiralabs/midnight-connect", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2", "ws": "^8.19.0" }, "engines": { @@ -5789,12 +5789,12 @@ }, "packages/contract": { "name": "@kuiralabs/midnight-contract", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2" }, "engines": { "node": ">=22" @@ -5802,14 +5802,14 @@ }, "packages/dev": { "name": "@kuiralabs/midnight-dev", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-connect": "0.1.0-rc.1", - "@kuiralabs/midnight-contract": "0.1.0-rc.1", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-connect": "0.1.0-rc.2", + "@kuiralabs/midnight-contract": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2" }, "engines": { "node": ">=22" @@ -5817,12 +5817,12 @@ }, "packages/engine-beta": { "name": "@kuiralabs/midnight-engine-beta", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", @@ -6325,12 +6325,12 @@ }, "packages/engine-rc": { "name": "@kuiralabs/midnight-engine-rc", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", @@ -6356,14 +6356,14 @@ }, "packages/grant": { "name": "@kuiralabs/midnight-grant", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-contract": "0.1.0-rc.1", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-contract": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2" }, "engines": { "node": ">=22" @@ -6371,11 +6371,11 @@ }, "packages/wallet": { "name": "@kuiralabs/midnight-wallet", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@scure/bip39": "^2.0.1" }, "engines": { diff --git a/package.json b/package.json index 22ba1041..a67aed70 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.12", + "version": "0.6.0-rc.13", "type": "module", "description": "Git-style CLI wallet for the Midnight blockchain", "license": "Apache-2.0", @@ -70,15 +70,15 @@ "readme-commands": "tsx --conditions=midnight-cli-source scripts/write-readme-commands.ts" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-connect": "0.1.0-rc.1", - "@kuiralabs/midnight-contract": "0.1.0-rc.1", - "@kuiralabs/midnight-dev": "0.1.0-rc.1", - "@kuiralabs/midnight-engine-beta": "0.1.0-rc.1", - "@kuiralabs/midnight-engine-rc": "0.1.0-rc.1", - "@kuiralabs/midnight-grant": "0.1.0-rc.1", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-connect": "0.1.0-rc.2", + "@kuiralabs/midnight-contract": "0.1.0-rc.2", + "@kuiralabs/midnight-dev": "0.1.0-rc.2", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.2", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.2", + "@kuiralabs/midnight-grant": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2", "@modelcontextprotocol/sdk": "^1.27.1" }, "devDependencies": { diff --git a/packages/chain/package.json b/packages/chain/package.json index 31ff0d73..0c57888a 100644 --- a/packages/chain/package.json +++ b/packages/chain/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-chain", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "Read-only network access for the Midnight CLI packages: node, indexer and proof-server readiness, chain id, tip, events and the ledger-version guard", "license": "Apache-2.0", @@ -35,7 +35,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "ws": "^8.19.0" } } diff --git a/packages/cli-core/package.json b/packages/cli-core/package.json index c665560b..33620c5d 100644 --- a/packages/cli-core/package.json +++ b/packages/cli-core/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-cli-core", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.2", "type": "module", "description": "The base of the Midnight CLI packages: arguments, typed errors and exit codes, JSON output, config, the state root, network endpoints, terminal formatting, the command registry contract, the payer and the SDK engine interface", "license": "Apache-2.0", diff --git a/packages/connect/package.json b/packages/connect/package.json index 05c37b03..58213493 100644 --- a/packages/connect/package.json +++ b/packages/connect/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-connect", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "mn serve for the Midnight CLI packages: the DApp connector API over a local WebSocket JSON-RPC server, the serve manager that starts or reuses one, and the payer that pays a command through it", "license": "Apache-2.0", @@ -35,9 +35,9 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2", "ws": "^8.19.0" } } diff --git a/packages/contract/package.json b/packages/contract/package.json index d60fe981..ef7ef31b 100644 --- a/packages/contract/package.json +++ b/packages/contract/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-contract", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "Contracts for the Midnight CLI packages: deploying, calling and reading a Compact contract from its dApp folder through mn serve, the requests a deploy or call is built from, a compiled contract's circuits and witnesses, and the chain's block limits", "license": "Apache-2.0", @@ -35,8 +35,8 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2" } } diff --git a/packages/dev/package.json b/packages/dev/package.json index bd81f5e7..3fe93155 100644 --- a/packages/dev/package.json +++ b/packages/dev/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-dev", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "Development for the Midnight CLI packages: mn dev (compile, deploy and test a dApp as its files change, on dev wallets), mn test (prepare, run and scaffold a dApp's test suites) and mn localnet (a local network in Docker)", "license": "Apache-2.0", @@ -35,10 +35,10 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-connect": "0.1.0-rc.1", - "@kuiralabs/midnight-contract": "0.1.0-rc.1", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-connect": "0.1.0-rc.2", + "@kuiralabs/midnight-contract": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2" } } diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index 18610a78..db5b9172 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-engine-beta", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK 5.0 beta split packages, ledger 9 rc.3, midnight-js 5 beta): everything the CLI does with that SDK set, behind the engine interface", "license": "Apache-2.0", @@ -32,8 +32,8 @@ }, "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index 98ff2d5b..ce302930 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-engine-rc", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, ledger 9 rc, midnight-js 5 rc): everything the CLI does with that SDK set, behind the engine interface", "license": "Apache-2.0", @@ -32,8 +32,8 @@ }, "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", diff --git a/packages/grant/package.json b/packages/grant/package.json index 38e291ca..b26139b7 100644 --- a/packages/grant/package.json +++ b/packages/grant/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-grant", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "Grants for the Midnight CLI packages: mn grant (the wallet owner's account and the grants that let an agent spend from it, its owner devices and backups) over @kuiralabs/midnight-account-chain, and the protector wallet protect seals the accounts' records with", "license": "Apache-2.0", @@ -37,9 +37,9 @@ }, "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.0", - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", - "@kuiralabs/midnight-contract": "0.1.0-rc.1", - "@kuiralabs/midnight-wallet": "0.1.0-rc.1" + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-contract": "0.1.0-rc.2", + "@kuiralabs/midnight-wallet": "0.1.0-rc.2" } } diff --git a/packages/wallet/package.json b/packages/wallet/package.json index c4f66820..e424f750 100644 --- a/packages/wallet/package.json +++ b/packages/wallet/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-wallet", - "version": "0.1.0-rc.1", + "version": "0.1.0-rc.2", "type": "module", "description": "Wallets for the Midnight CLI packages: mn's passphrase and sealed wallet files, seeds, balances, NIGHT transfers and airdrops, Dust registration, and swap offers", "license": "Apache-2.0", @@ -35,8 +35,8 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.1", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.0", + "@kuiralabs/midnight-chain": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@scure/bip39": "^2.0.1" } } From a0a0992e9afa408b078d0e0ffceef6e491b71d6a Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 14:45:28 -0800 Subject: [PATCH 79/88] Mounting commands from core: runCommand, captureCommand, toolDescription (3H, part 1) A program that mounts our commands in its own command line or MCP server had to copy mn's glue. core now exports it (Y63): - runCommand(definition, args, run): what mn's shell does around a handler. It refuses an unavailable command, writes its notice, loads its handler, gives the payer or protectors (a value or a loader) only when the definition asks, and runs it as one call of the host. - captureCommand(definition, args, run): the MCP form, in --json and agent-slim mode. The result is kept per call, the person's text goes to run.text, and a non-zero exit becomes COMMAND_FAILED. - toolDescription(registry, tool): a tool's description with its codes. listedNames moves to agent-guidance. mn's dispatch and MCP tools now call these, and src/lib/run-command.ts is gone. The generic tests moved to core. Behaviour snapshot unchanged against rc.13 (new baseline recorded); suite green. --- packages/cli-core/api-report.md | 17 + .../src/__tests__/run-command.test.ts | 337 ++++++++++++++++++ packages/cli-core/src/index.ts | 5 +- packages/cli-core/src/lib/agent-guidance.ts | 5 + packages/cli-core/src/lib/call-context.ts | 4 +- packages/cli-core/src/lib/run-command.ts | 109 ++++++ scripts/check-layering.mjs | 4 +- src/__tests__/command-registry.test.ts | 45 +-- src/__tests__/helpers/own-call.ts | 11 +- src/__tests__/host-paths.test.ts | 21 +- src/__tests__/json-fields.test.ts | 6 +- src/__tests__/layering.test.ts | 4 +- src/__tests__/run-command.test.ts | 226 +----------- src/__tests__/two-hosts.test.ts | 4 +- src/__tests__/verbose-per-call.test.ts | 13 +- src/lib/code-tables.ts | 7 +- src/lib/command-dispatch.ts | 43 +-- src/lib/mcp/registry-tools.ts | 29 +- src/lib/run-command.ts | 83 ----- src/mcp-server.ts | 3 +- src/wallet.ts | 4 +- 21 files changed, 548 insertions(+), 432 deletions(-) create mode 100644 packages/cli-core/src/__tests__/run-command.test.ts create mode 100644 packages/cli-core/src/lib/run-command.ts delete mode 100644 src/lib/run-command.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 545eb9f6..40267625 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -17,6 +17,7 @@ export interface GuidancePiece { readonly body: string; } export type GuidanceText = 'agent-manual' | 'skill-core' | 'skill-full'; +export declare function listedNames(names: readonly string[]): string; export declare function manualCodeRow(definition: CodeDefinition): string; export interface PackageGuidance { readonly pieces: readonly GuidancePiece[]; @@ -711,6 +712,22 @@ export declare function resolveNetwork(ctx: NetworkResolutionContext, settings: config: NetworkConfig; }; export declare function resolveNetworkName(ctx: NetworkResolutionContext): NetworkName; +export declare function captureCommand(definition: RunnableDefinition, args: ParsedArgs, run: CommandRun & { + readonly text: (text: string) => void; +}): Promise>; +export interface CommandRun { + readonly host: Host; + readonly signal?: AbortSignal; + readonly onProgress?: (message: string) => void; + readonly payer?: Provided; + readonly protectors?: Provided; +} +export type Provided = T | (() => Promise); +export declare function runCommand(definition: RunnableDefinition, args: ParsedArgs, run: CommandRun & { + readonly output: CallOutput; +}): Promise; +export type RunnableDefinition = Pick; +export declare function toolDescription(registry: Pick, tool: RegisteredTool): string; export interface CallSdkWarnings { listen(listener: SdkWarningListener | undefined): () => void; } diff --git a/packages/cli-core/src/__tests__/run-command.test.ts b/packages/cli-core/src/__tests__/run-command.test.ts new file mode 100644 index 00000000..b1fd479a --- /dev/null +++ b/packages/cli-core/src/__tests__/run-command.test.ts @@ -0,0 +1,337 @@ +// Running a command from its definition (src/lib/run-command.ts), as a +// program that mounts our commands does: runCommand for a command line, +// captureCommand for an MCP tool, toolDescription for the tool's listing. The +// commands here are the test's own; mn's shell and MCP server run theirs +// through the same two functions, and their tests check the installed ones. + +import { describe, expect, it } from 'vitest'; +import { captureCommand, runCommand, toolDescription, type CommandRun, type RunnableDefinition } from '../lib/run-command.ts'; +import { listedNames } from '../lib/agent-guidance.ts'; +import { createCommandRegistry, type CommandDefinition } from '../lib/command-definition.ts'; +import type { CallContext, CommandHandler, CommandOutcome } from '../lib/call-context.ts'; +import { SecondResultError } from '../lib/call-context.ts'; +import { CancelledError, CommandFailedError } from '../lib/errors.ts'; +import { parseArgs, type ParsedArgs } from '../lib/argv.ts'; +import type { Payer } from '../lib/payer.ts'; +import type { Spinner } from '../ui/spinner.ts'; +import { testHost } from '../../../../test-support/test-host.ts'; + +/** A definition whose handler is `handler`, with what the shell does around it. */ +const definitionOf = (handler: CommandHandler, shell: CommandDefinition['shell'] = {}): RunnableDefinition => ({ shell, load: async () => ({ default: handler }) }); + +const noArgs = (): ParsedArgs => ({ command: 'x', subcommand: undefined, positionals: [], flags: {} }); + +/** A capture run on a test host, its text for the person kept in `text`. */ +function captureRun(run: Partial = {}): CommandRun & { text: (t: string) => void; said: string[] } { + const said: string[] = []; + return { host: testHost(), ...run, said, text: (t) => { said.push(t); } }; +} + +describe('runCommand', () => { + // Test commands whose handlers record the context they were given. + const received: { args: ParsedArgs; ctx: CallContext }[] = []; + const loaded: string[] = []; + const results: unknown[] = []; + const notices: string[] = []; + const payer = { name: 'test payer' } as unknown as Payer; + const protector = { name: 'test protector' }; + const command = (name: string, shell: CommandDefinition['shell'], outcome?: CommandOutcome): RunnableDefinition => ({ + shell, + load: async () => { + loaded.push(name); + return { default: async (args, ctx) => { received.push({ args, ctx }); ctx.output.result({ ran: name }); return outcome; } }; + }, + }); + const controller = new AbortController(); + const output = { + result: (data: Readonly>) => { results.push(data); }, + stdout: () => {}, + stderr: (text: string) => { notices.push(text); }, + }; + const given = { host: testHost(), signal: controller.signal, output, payer, protectors: [protector] }; + const run = async (definition: RunnableDefinition, argv: string[] = ['x', '--json'], call: Parameters[2] = given) => { + received.length = 0; loaded.length = 0; results.length = 0; notices.length = 0; + const args = parseArgs(argv); + const outcome = await runCommand(definition, args, call); + return { args, call: received[0]!, outcome }; + }; + + it('gives the handler its call\'s signal and output, and the payer and protectors only when the definition asks', async () => { + const plain = await run(command('plain', {})); + expect(plain.call.args).toBe(plain.args); + expect(plain.call.ctx.signal).toBe(controller.signal); + expect(plain.call.ctx.payer).toBeUndefined(); + expect(plain.call.ctx.protectors).toBeUndefined(); + expect(results).toStrictEqual([{ ran: 'plain' }]); + const paying = await run(command('paying', { payer: true })); + expect(paying.call.ctx.payer).toBe(payer); + expect(paying.call.ctx.protectors).toBeUndefined(); + const protecting = await run(command('protecting', { protectors: true })); + expect(protecting.call.ctx.payer).toBeUndefined(); + expect(protecting.call.ctx.protectors).toStrictEqual([protector]); + }); + + it('calls a payer or protectors loader only for a command whose definition asks for it', async () => { + const asked: string[] = []; + const loaders = { ...given, payer: async () => { asked.push('payer'); return payer; }, protectors: async () => { asked.push('protectors'); return [protector]; } }; + await run(command('plain', {}), ['x'], loaders); + expect(asked).toStrictEqual([]); + const paying = await run(command('paying', { payer: true }), ['x'], loaders); + expect(paying.call.ctx.payer).toBe(payer); + const protecting = await run(command('protecting', { protectors: true }), ['x'], loaders); + expect(protecting.call.ctx.protectors).toStrictEqual([protector]); + expect(asked).toStrictEqual(['payer', 'protectors']); + }); + + it('runs a command that asks for a payer without one when none is given: the handler says what it needs', async () => { + const paying = await run(command('paying', { payer: true }), ['x'], { host: testHost(), output }); + expect(paying.call.ctx.payer).toBeUndefined(); + }); + + it('gives the handler the configuration the host gives when the call starts, and --verbose', async () => { + const { ctx } = (await run(command('plain', {}))).call; + expect(ctx.config.paths).toStrictEqual(given.host.paths()); + expect(ctx.config.settings).toStrictEqual(given.host.settings()); + expect(ctx.diagnostics.isVerbose).toBe(false); + expect((await run(command('plain', {}), ['x', '--verbose'])).call.ctx.diagnostics.isVerbose).toBe(true); + }); + + it('gives every handler a signal, one never cancelled when the run gives none', async () => { + const { ctx } = (await run(command('plain', {}), ['x'], { host: testHost(), output })).call; + expect(ctx.signal).toBeInstanceOf(AbortSignal); + expect(ctx.signal.aborted).toBe(false); + }); + + it('returns the exit code the handler gives', async () => { + expect((await run(command('failing', {}, { exitCode: 3 }))).outcome).toStrictEqual({ exitCode: 3 }); + expect((await run(command('plain', {}))).outcome).toBeUndefined(); + }); + + it('never starts a call already cancelled: CancelledError, the handler not run', async () => { + const cancelled = new AbortController(); + cancelled.abort(); + await expect(run(command('plain', {}), ['x'], { ...given, signal: cancelled.signal })).rejects.toBeInstanceOf(CancelledError); + expect(received).toStrictEqual([]); + expect(results).toStrictEqual([]); + }); + + it('writes a notice to the output\'s stderr before the handler loads', async () => { + await run(command('noticed', { notice: 'deprecated\n' })); + expect(notices).toStrictEqual(['deprecated\n']); + expect(loaded).toStrictEqual(['noticed']); + expect(results).toStrictEqual([{ ran: 'noticed' }]); + }); + + it('refuses an unavailable command with its message, loading nothing', async () => { + await expect(run(command('refused', { unavailable: 'not now' }))).rejects.toThrow(new Error('not now')); + expect(loaded).toStrictEqual([]); + }); + + it('sends what the command\'s spinners say to onProgress', async () => { + const said: string[] = []; + await runCommand(definitionOf(async (_args, ctx) => { ctx.progress.start('Syncing...').stop('Synced'); }), noArgs(), { host: testHost(), output, onProgress: (m) => said.push(m) }); + expect(said).toStrictEqual(['Syncing...', 'Synced']); + }); +}); + +describe('captureCommand', () => { + it('fails a command that returns a non-zero exit code, with the result it wrote, and passes one that returns 0', async () => { + const failing = definitionOf(async (_args, ctx) => { ctx.output.result({ overall: 'fail' }); return { exitCode: 1 }; }); + const err = await captureCommand(failing, parseArgs(['test', 'run']), captureRun()).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CommandFailedError); + expect((err as CommandFailedError).code).toBe('COMMAND_FAILED'); + expect((err as CommandFailedError).exitCode).toBe(1); + expect((err as CommandFailedError).result).toStrictEqual({ overall: 'fail' }); + + const passing = definitionOf(async (_args, ctx) => { ctx.output.result({ overall: 'pass' }); return { exitCode: 0 }; }); + expect(await captureCommand(passing, parseArgs(['test', 'run']), captureRun())).toStrictEqual({ overall: 'pass' }); + }); + + it('returns {} for a command that wrote no result', async () => { + expect(await captureCommand(definitionOf(async () => {}), noArgs(), captureRun())).toStrictEqual({}); + }); + + it('refuses an unavailable command, and sends a notice to the run\'s text', async () => { + await expect(captureCommand(definitionOf(async () => {}, { unavailable: 'not now' }), noArgs(), captureRun())).rejects.toThrow('not now'); + const run = captureRun(); + await captureCommand(definitionOf(async () => {}, { notice: 'deprecated\n' }), noArgs(), run); + expect(run.said).toStrictEqual(['deprecated\n']); + }); + + describe('agent-slim mode', () => { + const captureArgs = (sink: { args?: ParsedArgs }) => definitionOf(async (a: ParsedArgs) => { sink.args = a; }); + + it('sets json: true and _minimal: true by default', async () => { + const sink: { args?: ParsedArgs } = {}; + await captureCommand(captureArgs(sink), noArgs(), captureRun()); + expect(sink.args?.flags.json).toBe(true); + expect(sink.args?.flags._minimal).toBe(true); + }); + + it('does not override an explicitly-set _minimal flag', async () => { + const sink: { args?: ParsedArgs } = {}; + await captureCommand(captureArgs(sink), { ...noArgs(), flags: { _minimal: true, _full: true } }, captureRun()); + expect(sink.args?.flags._minimal).toBe(true); + expect(sink.args?.flags._full).toBe(true); + }); + }); + + describe('progress and cancellation', () => { + it('sends what a command\'s spinner says to onProgress, a --json command\'s silent spinner too', async () => { + const said: string[] = []; + await captureCommand(definitionOf(async (_args, ctx) => { + const quiet = ctx.progress.silent(); + quiet.update('Starting mn serve...'); + quiet.stop('mn serve ready (port 9932)'); + const shown = ctx.progress.start('Checking balance on undeployed...'); + shown.update('Syncing transactions... 40%'); + shown.log('fetching keys/deposit_shielded.prover (11 MB), once, from github.com'); + shown.stop('Synced 3 transactions'); + }), noArgs(), captureRun({ onProgress: (message) => said.push(message) })); + expect(said).toEqual([ + 'Starting mn serve...', + 'mn serve ready (port 9932)', + 'Checking balance on undeployed...', + 'Syncing transactions... 40%', + 'fetching keys/deposit_shielded.prover (11 MB), once, from github.com', + 'Synced 3 transactions', + ]); + }); + + it('sends nothing once the run is over, even when it failed', async () => { + const said: string[] = []; + let left: Spinner | undefined; + await expect(captureCommand(definitionOf(async (_args, ctx) => { + left = ctx.progress.silent(); + throw new Error('refused'); + }), noArgs(), captureRun({ onProgress: (message) => said.push(message) }))).rejects.toThrow('refused'); + left?.update('said after the run'); + expect(said).toEqual([]); + }); + + it('tells the command which of its spinners runs now, and none once it stops', async () => { + await captureCommand(definitionOf(async (_args, ctx) => { + expect(ctx.progress.active()).toBeNull(); + const spinner = ctx.progress.start('Syncing wallet...'); + expect(ctx.progress.active()).toBe(spinner); + spinner.stop('Wallet synced'); + expect(ctx.progress.active()).toBeNull(); + }), noArgs(), captureRun()); + }); + + it('hands the command the run\'s signal', async () => { + const controller = new AbortController(); + let seen: AbortSignal | undefined; + await captureCommand(definitionOf(async (_args, ctx) => { seen = ctx.signal; }), noArgs(), captureRun({ signal: controller.signal })); + expect(seen).toBe(controller.signal); + }); + + it('never starts a call already cancelled: CancelledError, the command not run', async () => { + const controller = new AbortController(); + controller.abort(); + let ran = false; + const err = await captureCommand(definitionOf(async () => { ran = true; }), noArgs(), captureRun({ signal: controller.signal })).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CancelledError); + expect(ran).toBe(false); + }); + }); + + // Regression: the capture target was one module global. Two calls + // in one server that overlapped shared it: the first to finish cleared it, + // and the other's result fell through to stdout, the MCP protocol channel, + // while its call returned {}. + describe('two calls at once', () => { + const gate = () => { + let open!: () => void; + const opened = new Promise((resolve) => { open = resolve; }); + return { open, opened }; + }; + + it('each keeps its own result when they finish in the opposite order they started', async () => { + const first = gate(); + const second = gate(); + const a = captureCommand(definitionOf(async (_args, ctx) => { await first.opened; ctx.output.result({ call: 'a' }); }), noArgs(), captureRun()); + const b = captureCommand(definitionOf(async (_args, ctx) => { await second.opened; ctx.output.result({ call: 'b' }); }), noArgs(), captureRun()); + second.open(); + expect(await b).toEqual({ call: 'b' }); + first.open(); + expect(await a).toEqual({ call: 'a' }); + }); + + // Regression: the progress target and the active spinner were + // module globals. The second call to start took the target, so what the + // first call's spinners said went to the second call's client, and the + // first call's went nowhere once the second ended. + it('each keeps its own progress: what one call\'s spinners say never reaches the other\'s client', async () => { + const first = gate(); + const second = gate(); + const saidA: string[] = []; + const saidB: string[] = []; + let activeInA: Spinner | null | undefined; + const a = captureCommand(definitionOf(async (_args, ctx) => { + const spinner = ctx.progress.silent(); + spinner.update('a: before b starts'); + await first.opened; + spinner.update('a: while b runs'); + activeInA = ctx.progress.active(); + spinner.stop('a: done'); + }), noArgs(), captureRun({ onProgress: (message) => saidA.push(message) })); + const b = captureCommand(definitionOf(async (_args, ctx) => { + const spinner = ctx.progress.start('b: started'); + first.open(); + await second.opened; + spinner.stop('b: done'); + }), noArgs(), captureRun({ onProgress: (message) => saidB.push(message) })); + await new Promise((resolve) => setTimeout(resolve, 10)); + second.open(); + await Promise.all([a, b]); + expect(saidA).toEqual(['a: before b starts', 'a: while b runs', 'a: done']); + expect(saidB).toEqual(['b: started', 'b: done']); + expect(activeInA).toBeNull(); + }); + + it('keeps a result as it was written: a change the command makes after is not seen', async () => { + const result = await captureCommand(definitionOf(async (_args, ctx) => { + const data: Record = { balance: '1' }; + ctx.output.result(data); + data.balance = '2'; + }), noArgs(), captureRun()); + expect(result).toEqual({ balance: '1' }); + }); + + it('refuses a second result in one call', async () => { + await expect(captureCommand(definitionOf(async (_args, ctx) => { + ctx.output.result({ call: 'first' }); + ctx.output.result({ call: 'second' }); + }), noArgs(), captureRun())).rejects.toThrow(SecondResultError); + }); + + it('sends the command\'s text for the person to the run\'s text, its stdout and stderr alike', async () => { + const run = captureRun(); + await captureCommand(definitionOf(async (_args, ctx) => { + ctx.output.stdout('shown\n'); + ctx.output.stderr('chrome\n'); + ctx.output.result({ ok: true }); + }), noArgs(), run); + expect(run.said).toStrictEqual(['shown\n', 'chrome\n']); + }); + }); +}); + +describe('toolDescription', () => { + // A tool whose command declares codes is checked with mn's installed tools (src/__tests__/mcp-registry-tools.test.ts). + it('is the definition\'s description when the command declares no codes', () => { + const registry = createCommandRegistry([{ + name: 'thing', order: 1, flags: [], needsWalletSdk: false, shell: {}, errors: { codes: [] }, + load: async () => ({ default: async () => {} }), + mcp: { tools: [{ name: 'thing_show', description: 'Show a thing.', params: [], argv: { flags: [] }, order: 1 }] }, + }], []); + expect(toolDescription(registry, registry.tools[0]!)).toBe('Show a thing.'); + }); + + it('names sets in a sentence', () => { + expect(listedNames(['network'])).toBe('network'); + expect(listedNames(['network', 'wallet'])).toBe('network and wallet'); + expect(listedNames(['network', 'wallet', 'engine'])).toBe('network, wallet and engine'); + }); +}); diff --git a/packages/cli-core/src/index.ts b/packages/cli-core/src/index.ts index 01d4fbc1..db67279b 100644 --- a/packages/cli-core/src/index.ts +++ b/packages/cli-core/src/index.ts @@ -9,7 +9,7 @@ export { assembleGuidance, codeGuidancePieces, GuidanceError, type GuidancePiece, type GuidanceText, - manualCodeRow, type PackageGuidance, sectionsWithAdded, skillCodeRow, type ToolsTableRow, wrapWords + listedNames, manualCodeRow, type PackageGuidance, sectionsWithAdded, skillCodeRow, type ToolsTableRow, wrapWords } from './lib/agent-guidance.ts'; export { nightAmountJson, nightAmountText, nightToMicro, parseAmount } from './lib/amount.ts'; export { describeApprovalPolicy } from './lib/approval.ts'; @@ -101,6 +101,9 @@ export { type ProgressEvent, type ProgressListener, type ProgressSteps, progress export { type Prompter } from './lib/prompter.ts'; export { clearDustDirectCache, clearNativeDustCheckpoint, clearShieldedDirectCache } from './lib/reader-cache-files.ts'; export { type NetworkSettings, resolveBlockfrostProjectId, resolveNetwork, resolveNetworkName } from './lib/resolve-network.ts'; +export { + captureCommand, type CommandRun, type Provided, runCommand, type RunnableDefinition, toolDescription +} from './lib/run-command.ts'; export { type CallSdkWarnings, createSdkWarningRouter, sdkTransientWarning, type SdkWarningCalls, withCallSdkWarnings diff --git a/packages/cli-core/src/lib/agent-guidance.ts b/packages/cli-core/src/lib/agent-guidance.ts index b5d3e1e6..b80b7f50 100644 --- a/packages/cli-core/src/lib/agent-guidance.ts +++ b/packages/cli-core/src/lib/agent-guidance.ts @@ -181,3 +181,8 @@ export function codeGuidancePieces(codes: readonly CodeDefinition[]): GuidancePi ] satisfies GuidancePiece[]; }); } + +/** Names in a sentence: "network", "network and wallet", "network, wallet and engine". */ +export function listedNames(names: readonly string[]): string { + return names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`; +} diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index 4129d400..053aa21b 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -8,8 +8,8 @@ // call that raised it (core's "./process", process/sdk-process-guard.ts). // // The CLI builds one from the process's streams, its signal and --verbose -// (lib/command-dispatch.ts); the MCP server builds one per request -// (lib/run-command.ts). +// (runCommand, lib/run-command.ts); the MCP server builds one per request +// (captureCommand, the same module). import { isVerbose, type ParsedArgs } from './argv.ts'; import { CancelledError } from './errors.ts'; diff --git a/packages/cli-core/src/lib/run-command.ts b/packages/cli-core/src/lib/run-command.ts new file mode 100644 index 00000000..13b92c00 --- /dev/null +++ b/packages/cli-core/src/lib/run-command.ts @@ -0,0 +1,109 @@ +// Running a command from its definition, as a program that mounts our +// commands does: in its own command line (`runCommand`, the output the +// program gives) or as an MCP tool (`captureCommand`, the result kept as +// JSON). Both do what mn's shell and MCP server do around a handler: refuse a +// command its definition marks unavailable, write its notice, load its +// handler, give it the payer or protectors only when its definition asks for +// them, and run it as one call of the host, with SDK warnings of its own. + +import { listedNames } from './agent-guidance.ts'; +import { MINIMAL_FLAG, type ParsedArgs } from './argv.ts'; +import { createCallContext, runHandler, type CallOutput, type CommandOutcome } from './call-context.ts'; +import type { CommandDefinition, CommandRegistry, RegisteredTool } from './command-definition.ts'; +import { commandOwnCodes, declaredSets } from './command-definition.ts'; +import { CommandFailedError } from './errors.ts'; +import type { Host } from './host.ts'; +import type { Payer } from './payer.ts'; + +/** A value, or what loads it: a loader is called only for a command whose definition asks for it. */ +export type Provided = T | (() => Promise); + +/** What a program gives a command it runs. */ +export interface CommandRun { + /** The host the command runs in: its state root, settings, engines and the rest. */ + readonly host: Host; + /** Cancels the command; a call already cancelled never starts. None: it runs to the end. */ + readonly signal?: AbortSignal; + /** Each message the command's spinners say while it runs, in --json mode too. */ + readonly onProgress?: (message: string) => void; + /** What a command whose definition asks for a payer pays with (contract, swap, grant, dev). */ + readonly payer?: Provided; + /** What `wallet protect` seals besides the wallets (grant's `accountProtector`). */ + readonly protectors?: Provided; +} + +/** The part of a definition a run reads: what the shell does around the handler, and the handler. */ +export type RunnableDefinition = Pick; + +const provided = async (value: Provided): Promise => (typeof value === 'function' ? (value as () => Promise)() : value); + +/** + * Runs the command `definition` defines with `args`, its output going to + * `run.output`; returns the exit code its handler gives, for the caller to + * act on. Refuses a command its definition marks unavailable, and writes its + * notice to the output's stderr before the handler loads. + */ +export async function runCommand(definition: RunnableDefinition, args: ParsedArgs, run: CommandRun & { readonly output: CallOutput }): Promise { + const { payer, protectors, notice, unavailable } = definition.shell; + if (unavailable !== undefined) throw new Error(unavailable); + if (notice !== undefined) run.output.stderr(notice); + const { default: handler } = await definition.load(); + const given = { + ...(payer === true && run.payer !== undefined ? { payer: await provided(run.payer) } : {}), + ...(protectors === true && run.protectors !== undefined ? { protectors: await provided(run.protectors) } : {}), + }; + return run.host.sdkWarnings.run((sdkWarnings) => runHandler(handler, args, createCallContext({ + host: run.host, + args, + signal: run.signal ?? new AbortController().signal, + output: run.output, + sdkWarnings, + ...(run.onProgress === undefined ? {} : { onProgress: run.onProgress }), + ...given, + }))); +} + +/** + * Runs the command as an MCP tool runs it: in --json mode, agent-slim unless + * `args` says otherwise (`_minimal`, `_full`), and returns its JSON result + * ({} when it wrote none), as it was when written. The result is this call's + * alone, so calls that overlap never see each other's. The command's text for + * the person goes to `run.text` (a server's stderr, never its protocol + * channel). Progress reaches `run.onProgress` while the command runs and never + * after. Throws what the command throws, and CommandFailedError, carrying the + * result, when it ends with a non-zero exit code. + */ +export async function captureCommand(definition: RunnableDefinition, args: ParsedArgs, run: CommandRun & { readonly text: (text: string) => void }): Promise> { + let result: Record = {}; + const output: CallOutput = { + // Read back as JSON, as a server sends it: what was written then, nothing the handler changes after. + result: (data) => { result = JSON.parse(JSON.stringify(data)) as Record; }, + stdout: run.text, + stderr: run.text, + }; + args.flags.json = true; + if (!(MINIMAL_FLAG in args.flags)) args.flags[MINIMAL_FLAG] = true; + // The call's own progress, closed when it ends: a spinner it left running says nothing after. + let running = true; + const onProgress = run.onProgress; + const report = onProgress === undefined ? undefined : (message: string): void => { if (running) onProgress(message); }; + try { + const outcome = await runCommand(definition, args, { ...run, output, ...(report === undefined ? {} : { onProgress: report }) }); + if (outcome !== undefined && outcome.exitCode !== 0) throw new CommandFailedError(args.command ?? 'the command', outcome.exitCode, result); + return result; + } finally { + running = false; + } +} + +/** + * A tool's description as an MCP server lists it: its definition's, then the + * codes its command can end with: its own, and the sets it declares by name. + */ +export function toolDescription(registry: Pick, tool: RegisteredTool): string { + const own = commandOwnCodes(registry, tool.command).map((definition) => definition.code); + const sets = declaredSets(tool.command).map((set) => set.name); + if (own.length === 0 && sets.length === 0) return tool.description; + const named = sets.length === 0 ? '' : `the ${listedNames(sets)} codes (see the skill)`; + return `${tool.description} Errors: ${own.join(', ')}${own.length > 0 && named !== '' ? '; and ' : ''}${named}.`; +} diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index 91d3e57f..b1bfb239 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -64,7 +64,7 @@ const HOMES = [ // help plays the shell's intro, and manual builds the full manual; both render the installed registry. ['shell', /^commands\/(help|manual)(\.definition)?\.ts$/], // pkg reads mn's own package.json: its name, version and repository. - ['shell', /^lib\/(pkg|heap-guard|node-version|intro-marker|output-redaction|run-command|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|code-tables)\.ts$/], + ['shell', /^lib\/(pkg|heap-guard|node-version|intro-marker|output-redaction|cli-host|installed-commands|installed-engines|command-dispatch|agent-manual|readme-commands|package-readmes|code-tables)\.ts$/], ['shell', /^ui\/(animate|art)\.ts$/], ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], @@ -77,7 +77,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|verbose|error-trim|command-flags|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|verbose|error-trim|command-flags|run-command|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], // What a host calls on its own process: the SDK rejection guard, the sync heap advice. ['core', /^process\//], diff --git a/src/__tests__/command-registry.test.ts b/src/__tests__/command-registry.test.ts index 99a82c4f..18778625 100644 --- a/src/__tests__/command-registry.test.ts +++ b/src/__tests__/command-registry.test.ts @@ -90,8 +90,8 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => signal: controller.signal, output, host: testHost(), - loadPayer: async () => payer, - loadProtectors: async () => [protector], + payer: async () => payer, + protectors: async () => [protector], }; const run = async (name: string, given: ShellProvisions = provisions) => { received.length = 0; notices.length = 0; loaded.length = 0; results.length = 0; @@ -100,7 +100,8 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => return { args, call: received[0]!, outcome }; }; - it('gives every handler its call\'s signal and output, and the payer and protectors only when the definition asks', async () => { + // How a command is run from its definition (notice, refusal, cancellation, exit code) is core's runCommand, tested there. + it('gives every handler its call\'s signal and output, and the shell\'s payer and protectors only when the definition asks', async () => { const plain = await run('plain'); expect(plain.call.args).toBe(plain.args); expect(plain.call.ctx.signal).toBe(controller.signal); @@ -117,44 +118,6 @@ describe('the dispatch (src/lib/command-dispatch.ts, from the registry)', () => expect(protecting.call.ctx.protectors).toStrictEqual([protector]); }); - it('gives the handler the configuration the host gives when the call starts, and --verbose', async () => { - const { ctx } = (await run('plain')).call; - expect(ctx.config.paths).toStrictEqual(provisions.host.paths()); - expect(ctx.config.settings).toStrictEqual(provisions.host.settings()); - expect(ctx.diagnostics.isVerbose).toBe(false); - received.length = 0; - await dispatchCommand(testRegistry, 'plain', parseArgs(['plain', '--verbose']), provisions); - expect(received[0]!.ctx.diagnostics.isVerbose).toBe(true); - }); - - it('returns the exit code the handler gives, for the shell to set', async () => { - expect((await run('failing')).outcome).toStrictEqual({ exitCode: 3 }); - expect((await run('plain')).outcome).toBeUndefined(); - }); - - it('never starts a call already cancelled: CANCELLED, the handler not run', async () => { - const cancelled = new AbortController(); - cancelled.abort(); - const err = await run('plain', { ...provisions, signal: cancelled.signal }).catch((e: unknown) => e); - expect(err).toBeInstanceOf(CancelledError); - expect(classifyError(err as Error, installedCommands)).toStrictEqual({ exitCode: EXIT_CANCELLED, errorCode: 'CANCELLED' }); - expect(received).toStrictEqual([]); - expect(results).toStrictEqual([]); - }); - - it('writes a notice before the handler loads', async () => { - await run('noticed'); - expect(notices).toStrictEqual(['deprecated\n']); - expect(results).toStrictEqual([{ ran: 'noticed' }]); - expect(loaded).toStrictEqual(['noticed']); - }); - - it('refuses an unavailable command with its message, loading nothing', async () => { - loaded.length = 0; - await expect(dispatchCommand(testRegistry, 'refused', parseArgs(['refused']), provisions)).rejects.toThrow(new Error('not now')); - expect(loaded).toStrictEqual([]); - }); - it('refuses status, as the switch did, without loading it', async () => { const err = await dispatchCommand(registry, 'status', parseArgs(['status']), provisions).catch((e: unknown) => e); expect(err).toBeInstanceOf(Error); diff --git a/src/__tests__/helpers/own-call.ts b/src/__tests__/helpers/own-call.ts index 8ea35392..0f1e5ed2 100644 --- a/src/__tests__/helpers/own-call.ts +++ b/src/__tests__/helpers/own-call.ts @@ -1,9 +1,12 @@ // A command run with SDK warnings of its own, for tests that run one command -// outside any host: no host's filters report to it. +// outside any host: no host's filters report to it. Its text for the person +// goes to the process's stderr, as the MCP server's does. -import type { CommandRun } from '../../lib/run-command.ts'; +import type { CommandRun } from '@kuiralabs/midnight-cli-core'; import { testHost } from '../../../test-support/test-host.ts'; -export function ownCall(run: Omit & { host?: CommandRun['host'] } = {}): CommandRun { - return { ...run, host: run.host ?? testHost() }; +export type OwnCall = CommandRun & { readonly text: (text: string) => void }; + +export function ownCall(run: Omit & { host?: CommandRun['host'] } = {}): OwnCall { + return { ...run, host: run.host ?? testHost(), text: (text) => { process.stderr.write(text); } }; } diff --git a/src/__tests__/host-paths.test.ts b/src/__tests__/host-paths.test.ts index 32a3cc26..ac01d8a0 100644 --- a/src/__tests__/host-paths.test.ts +++ b/src/__tests__/host-paths.test.ts @@ -7,16 +7,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { createHost, type Host, parseArgs, MIDNIGHT_DIR, loadCliConfig, sdkSetOf, readOpenOffers, recordOpenOffer, type OpenOffer, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; +import { captureCommand, createHost, type Host, parseArgs, MIDNIGHT_DIR, loadCliConfig, sdkSetOf, readOpenOffers, recordOpenOffer, type OpenOffer, PASSPHRASE_ENV } from '@kuiralabs/midnight-cli-core'; import { cacheRootDir, getCachePath, networkCacheFolder } from '@kuiralabs/midnight-cli-core/engine'; import { configDefinition } from '@kuiralabs/midnight-cli-core/commands'; -import { captureCommand } from '../lib/run-command.ts'; +import { ownCall } from './helpers/own-call.ts'; import { installedCommands } from '../lib/installed-commands.ts'; import { createWallet, walletSecretFrom, getActiveWalletName, listWallets, clearChainCaches, passphraseForNewSecret } from '@kuiralabs/midnight-wallet'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; -// The config handler, as the shell loads it. -const { default: configCommand } = await configDefinition.load(); const PASSPHRASE = 'correct horse battery staple'; const MAKER = 'mn_addr_undeployed1maker'; @@ -66,11 +64,11 @@ afterEach(() => { describe('two hosts with different state roots', () => { it('each read and write their own config through the config command', async () => { - await captureCommand(configCommand, parseArgs(['config', 'set', 'network', 'preview']), { host: hostA }); - await captureCommand(configCommand, parseArgs(['config', 'set', 'network', 'preprod']), { host: hostB }); + await captureCommand(configDefinition, parseArgs(['config', 'set', 'network', 'preview']), ownCall({ host: hostA })); + await captureCommand(configDefinition, parseArgs(['config', 'set', 'network', 'preprod']), ownCall({ host: hostB })); - expect(await captureCommand(configCommand, parseArgs(['config', 'get', 'network']), { host: hostA })).toMatchObject({ value: 'preview' }); - expect(await captureCommand(configCommand, parseArgs(['config', 'get', 'network']), { host: hostB })).toMatchObject({ value: 'preprod' }); + expect(await captureCommand(configDefinition, parseArgs(['config', 'get', 'network']), ownCall({ host: hostA }))).toMatchObject({ value: 'preview' }); + expect(await captureCommand(configDefinition, parseArgs(['config', 'get', 'network']), ownCall({ host: hostB }))).toMatchObject({ value: 'preprod' }); expect(loadCliConfig(rootA).network).toBe('preview'); expect(loadCliConfig(rootB).network).toBe('preprod'); expect(fs.readdirSync(process.env.HOME!)).toEqual([]); @@ -85,9 +83,8 @@ describe('two hosts with different state roots', () => { expect(getActiveWalletName(rootA)).toBe('alice'); expect(getActiveWalletName(rootB)).toBe('bob'); // As the MCP server runs it. - const { default: walletCommand } = await installedCommands.find('wallet')!.load(); - const listedA = await captureCommand(walletCommand, parseArgs(['wallet', 'list']), { host: hostA }); - const listedB = await captureCommand(walletCommand, parseArgs(['wallet', 'list']), { host: hostB }); + const listedA = await captureCommand(installedCommands.find('wallet')!, parseArgs(['wallet', 'list']), ownCall({ host: hostA })); + const listedB = await captureCommand(installedCommands.find('wallet')!, parseArgs(['wallet', 'list']), ownCall({ host: hostB })); expect((listedA.wallets as { name: string }[]).map((w) => w.name)).toEqual(['alice']); expect((listedB.wallets as { name: string }[]).map((w) => w.name)).toEqual(['bob']); expect(fs.existsSync(path.join(rootA, 'wallets', 'alice.json'))).toBe(true); @@ -106,7 +103,7 @@ describe('two hosts with different state roots', () => { it('each keep their wallet caches in their own folder, named by their own config\'s SDK set', async () => { const address = 'mn_addr_undeployed1abcdefghijklmnopqrst'; - await captureCommand(configCommand, parseArgs(['config', 'set', 'sdk-set', 'beta', '--network', 'undeployed']), { host: hostA }); + await captureCommand(configDefinition, parseArgs(['config', 'set', 'sdk-set', 'beta', '--network', 'undeployed']), ownCall({ host: hostA })); expect(cacheRootDir(rootA)).toBe(path.join(rootA, 'cache')); expect(cacheRootDir(rootB)).toBe(path.join(rootB, 'cache')); diff --git a/src/__tests__/json-fields.test.ts b/src/__tests__/json-fields.test.ts index f5456e3d..a7a02520 100644 --- a/src/__tests__/json-fields.test.ts +++ b/src/__tests__/json-fields.test.ts @@ -7,9 +7,8 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import { parseArgs, type CommandHandler } from '@kuiralabs/midnight-cli-core'; +import { captureCommand, parseArgs } from '@kuiralabs/midnight-cli-core'; import { installedCommands } from '../lib/installed-commands.ts'; -import { captureCommand } from '../lib/run-command.ts'; import { ownCall } from './helpers/own-call.ts'; import { declaredOutcome } from './helpers/expect-declared.ts'; @@ -35,8 +34,7 @@ afterAll(() => { async function run(...argv: string[]): Promise> { const args = parseArgs([...argv, '--json']); args.flags._full = true; - const { default: handler } = await installedCommands.find(args.command!)!.load(); - return declaredOutcome(args.command!, captureCommand(handler as CommandHandler, args, ownCall())); + return declaredOutcome(args.command!, captureCommand(installedCommands.find(args.command!)!, args, ownCall())); } // In order: a later run reads what an earlier one wrote. diff --git a/src/__tests__/layering.test.ts b/src/__tests__/layering.test.ts index c021049f..30b49497 100644 --- a/src/__tests__/layering.test.ts +++ b/src/__tests__/layering.test.ts @@ -26,7 +26,7 @@ describe('the layering', () => { }); it('keeps the MCP server to core, the shell and the serve payer', () => { - expect(importRule('mcp-server.ts', 'lib/run-command.ts')).toBeUndefined(); + expect(importRule('mcp-server.ts', 'lib/cli-host.ts')).toBeUndefined(); expect(importRule('mcp-server.ts', 'lib/serve-payer.ts')).toBeUndefined(); expect(importRule('lib/mcp/registry-tools.ts', 'lib/command-definition.ts')).toBeUndefined(); expect(importRule('mcp-server.ts', 'lib/facade.ts')).toBe('mcp → wallet'); @@ -35,7 +35,7 @@ describe('the layering', () => { }); it('keeps every package off the shell and the MCP server', () => { - expect(importRule('lib/facade.ts', 'lib/run-command.ts')).toBe('wallet → shell'); + expect(importRule('lib/facade.ts', 'lib/cli-host.ts')).toBe('wallet → shell'); expect(importRule('lib/argv.ts', 'lib/mcp/known-params.ts')).toBe('core → mcp'); expect(importRule('commands/grant.ts', 'mcp-server.ts')).toBe('grant → mcp'); }); diff --git a/src/__tests__/run-command.test.ts b/src/__tests__/run-command.test.ts index 376d0b8c..f10e36c5 100644 --- a/src/__tests__/run-command.test.ts +++ b/src/__tests__/run-command.test.ts @@ -1,7 +1,9 @@ +// mn's installed commands run as its MCP server runs them (core's +// captureCommand): the JSON each writes, kept from the process's streams. +// How captureCommand runs a command is core's to test (packages/cli-core). + import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { captureCommand } from '../lib/run-command.ts'; -import { SecondResultError, type CommandHandler, CancelledError, CommandFailedError, classifyError, parseArgs, type ParsedArgs } from '@kuiralabs/midnight-cli-core'; -import type { Spinner } from '@kuiralabs/midnight-cli-core/ui'; +import { captureCommand, CommandFailedError, classifyError, parseArgs } from '@kuiralabs/midnight-cli-core'; import { generateDefinition, infoDefinition, addressDefinition, genesisAddressDefinition } from '@kuiralabs/midnight-wallet/commands'; import { installedCommands } from '../lib/installed-commands.ts'; import { captureOutput, type CapturedOutput } from '../../test-support/capture-output.ts'; @@ -15,13 +17,6 @@ import { rcKeys } from '../../test-support/rc-engine.ts'; import { localIndexerFlags } from '../../test-support/local-indexer.ts'; import { ownCall } from './helpers/own-call.ts'; -// The handlers, as the shell loads them. -const { default: inspectCostCommand } = await inspectCostDefinition.load(); -const { default: generateCommand } = await generateDefinition.load(); -const { default: infoCommand } = await infoDefinition.load(); -const { default: addressCommand } = await addressDefinition.load(); -const { default: genesisAddressCommand } = await genesisAddressDefinition.load(); - const TEST_DIR = path.join(os.tmpdir(), `midnight-run-cmd-test-${process.pid}`); const TEST_SEED = '0000000000000000000000000000000000000000000000000000000000000002'; @@ -53,23 +48,18 @@ afterEach(() => { fs.rmSync(TEST_DIR, { recursive: true, force: true }); }); -describe('captureCommand', () => { - it('fails a command that returns a non-zero exit code, with the result it wrote, and passes one that returns 0', async () => { - const failing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'fail' }); return { exitCode: 1 }; }; +describe('captureCommand with mn\'s commands', () => { + it('fails a command that ends with a non-zero exit code: COMMAND_FAILED, with that exit code', async () => { + const failing = { shell: {}, load: async () => ({ default: async () => ({ exitCode: 1 }) }) }; const err = await captureCommand(failing, parseArgs(['test', 'run']), ownCall()).catch((e: unknown) => e); expect(err).toBeInstanceOf(CommandFailedError); - expect((err as CommandFailedError).exitCode).toBe(1); - expect((err as CommandFailedError).result).toStrictEqual({ overall: 'fail' }); - expect(classifyError(err as Error, installedCommands).exitCode).toBe(1); - - const passing: CommandHandler = async (_args, ctx) => { ctx.output.result({ overall: 'pass' }); return { exitCode: 0 }; }; - expect(await captureCommand(passing, parseArgs(['test', 'run']), ownCall())).toStrictEqual({ overall: 'pass' }); + expect(classifyError(err as Error, installedCommands)).toStrictEqual({ exitCode: 1, errorCode: 'COMMAND_FAILED' }); }); it('captures JSON output from generate command', async () => { const walletFile = path.join(TEST_DIR, 'wallet.json'); const args = parseArgs(['generate', '--network', 'undeployed', '--output', walletFile]); - const result = await captureCommand(generateCommand, args, ownCall()); + const result = await captureCommand(generateDefinition, args, ownCall()); expect(result.addresses).toBeDefined(); const addrs = result.addresses as Record; @@ -83,7 +73,7 @@ describe('captureCommand', () => { saveWalletConfig(TEST_CONFIG, walletFile); const args = parseArgs(['info', '--wallet', walletFile, '--network', 'undeployed']); - const result = await captureCommand(infoCommand, args, ownCall()); + const result = await captureCommand(infoDefinition, args, ownCall()); expect(result.addresses).toBeDefined(); expect(result.activeNetwork).toBe('undeployed'); @@ -93,7 +83,7 @@ describe('captureCommand', () => { it('captures JSON output from address command', async () => { const args = parseArgs(['address', '--seed', TEST_SEED, '--network', 'undeployed']); - const result = await captureCommand(addressCommand, args, ownCall()); + const result = await captureCommand(addressDefinition, args, ownCall()); expect((result.address as string).startsWith('mn_addr_undeployed1')).toBe(true); expect(result.network).toBe('undeployed'); @@ -102,7 +92,7 @@ describe('captureCommand', () => { it('captures JSON output from genesis-address command', async () => { const args = parseArgs(['genesis-address', '--network', 'undeployed']); - const result = await captureCommand(genesisAddressCommand, args, ownCall()); + const result = await captureCommand(genesisAddressDefinition, args, ownCall()); expect((result.address as string).startsWith('mn_addr_undeployed1')).toBe(true); expect(result.network).toBe('undeployed'); @@ -111,7 +101,7 @@ describe('captureCommand', () => { it('captures JSON output from inspect-cost command', async () => { const local = await localIndexerFlags(); const args = parseArgs(['inspect-cost', ...local.flags]); - const result = await captureCommand(inspectCostCommand, args, ownCall()).finally(local.close); + const result = await captureCommand(inspectCostDefinition, args, ownCall()).finally(local.close); expect(result.readTime).toBeDefined(); expect(result.computeTime).toBeDefined(); @@ -122,7 +112,7 @@ describe('captureCommand', () => { it('does not leak to real stdout or stderr', async () => { const args = parseArgs(['genesis-address', '--network', 'undeployed']); - await captureCommand(genesisAddressCommand, args, ownCall()); + await captureCommand(genesisAddressDefinition, args, ownCall()); // captureOutput intercepts real stdout/stderr — if captureCommand leaked, // we'd see output here @@ -132,12 +122,12 @@ describe('captureCommand', () => { it('throws original error when handler fails', async () => { const args = parseArgs(['info', '--wallet', path.join(TEST_DIR, 'nonexistent.json')]); - await expect(captureCommand(infoCommand, args, ownCall())).rejects.toThrow('Wallet file not found'); + await expect(captureCommand(infoDefinition, args, ownCall())).rejects.toThrow('Wallet file not found'); }); it('restores stdout/stderr even when handler throws', async () => { const args = parseArgs(['info', '--wallet', path.join(TEST_DIR, 'nonexistent.json')]); - try { await captureCommand(infoCommand, args, ownCall()); } catch {} + try { await captureCommand(infoDefinition, args, ownCall()); } catch {} // Verify stdout/stderr are restored by writing to them io.clearStdout(); @@ -147,186 +137,4 @@ describe('captureCommand', () => { expect(io.stdout()).toBe('test-stdout'); expect(io.stderr()).toBe('test-stderr'); }); - - describe('_minimal flag injection', () => { - // Use a no-op handler so we can observe the args object after captureCommand - // mutates it, without depending on any real command's behavior. - const captureArgs = (sink: { args?: ParsedArgs }) => - async (a: ParsedArgs) => { sink.args = a; }; - - it('injects _minimal: true by default', async () => { - const sink: { args?: ParsedArgs } = {}; - await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: {} }, ownCall()); - expect(sink.args?.flags._minimal).toBe(true); - }); - - it('also sets json: true', async () => { - const sink: { args?: ParsedArgs } = {}; - await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: {} }, ownCall()); - expect(sink.args?.flags.json).toBe(true); - }); - - it('does not override an explicitly-set _minimal flag', async () => { - const sink: { args?: ParsedArgs } = {}; - // Tool handler may want to opt out (e.g. when an agent passes full:true, - // it sets _full:true; the wallet-list handler reads both flags). - await captureCommand(captureArgs(sink), { command: 'x', subcommand: undefined, positionals: [], flags: { _minimal: true, _full: true } }, ownCall()); - expect(sink.args?.flags._minimal).toBe(true); - expect(sink.args?.flags._full).toBe(true); - }); - }); - - describe('progress and cancellation', () => { - const noArgs = (): ParsedArgs => ({ command: 'x', subcommand: undefined, positionals: [], flags: {} }); - - it('sends what a command\'s spinner says to onProgress, a --json command\'s silent spinner too', async () => { - const said: string[] = []; - await captureCommand(async (_args, ctx) => { - const quiet = ctx.progress.silent(); - quiet.update('Starting mn serve...'); - quiet.stop('mn serve ready (port 9932)'); - const shown = ctx.progress.start('Checking balance on undeployed...'); - shown.update('Syncing transactions... 40%'); - shown.log('fetching keys/deposit_shielded.prover (11 MB), once, from github.com'); - shown.stop('Synced 3 transactions'); - }, noArgs(), ownCall({ onProgress: (message) => said.push(message) })); - expect(said).toEqual([ - 'Starting mn serve...', - 'mn serve ready (port 9932)', - 'Checking balance on undeployed...', - 'Syncing transactions... 40%', - 'fetching keys/deposit_shielded.prover (11 MB), once, from github.com', - 'Synced 3 transactions', - ]); - }); - - it('sends nothing once the run is over, even when it failed', async () => { - const said: string[] = []; - let left: Spinner | undefined; - await expect(captureCommand(async (_args, ctx) => { - left = ctx.progress.silent(); - throw new Error('refused'); - }, noArgs(), ownCall({ onProgress: (message) => said.push(message) }))).rejects.toThrow('refused'); - left?.update('said after the run'); - expect(said).toEqual([]); - }); - - it('tells the command which of its spinners runs now, and none once it stops', async () => { - await captureCommand(async (_args, ctx) => { - expect(ctx.progress.active()).toBeNull(); - const spinner = ctx.progress.start('Syncing wallet...'); - expect(ctx.progress.active()).toBe(spinner); - spinner.stop('Wallet synced'); - expect(ctx.progress.active()).toBeNull(); - }, noArgs(), ownCall()); - }); - - it('hands the command the run\'s signal', async () => { - const controller = new AbortController(); - let seen: AbortSignal | undefined; - await captureCommand(async (_args, ctx) => { seen = ctx.signal; }, noArgs(), ownCall({ signal: controller.signal })); - expect(seen).toBe(controller.signal); - }); - - it('hands every command a signal, one never cancelled when the run gives none', async () => { - let seen: AbortSignal | undefined; - await captureCommand(async (_args, ctx) => { seen = ctx.signal; }, noArgs(), ownCall()); - expect(seen).toBeInstanceOf(AbortSignal); - expect(seen?.aborted).toBe(false); - }); - - it('never starts a call already cancelled: CANCELLED, the command not run', async () => { - const controller = new AbortController(); - controller.abort(); - let ran = false; - const err = await captureCommand(async () => { ran = true; }, noArgs(), ownCall({ signal: controller.signal })).catch((e: unknown) => e); - expect(err).toBeInstanceOf(CancelledError); - expect(classifyError(err as Error, installedCommands).errorCode).toBe('CANCELLED'); - expect(ran).toBe(false); - }); - }); - - // Regression: the capture target was one module global. Two calls - // in one server that overlapped shared it: the first to finish cleared it, - // and the other's result fell through to stdout, the MCP protocol channel, - // while its call returned {}. - describe('two calls at once', () => { - const noArgs = (): ParsedArgs => ({ command: 'x', subcommand: undefined, positionals: [], flags: {} }); - const gate = () => { - let open!: () => void; - const opened = new Promise((resolve) => { open = resolve; }); - return { open, opened }; - }; - - it('each keeps its own result when they finish in the opposite order they started, and none reaches stdout', async () => { - const first = gate(); - const second = gate(); - const a = captureCommand(async (_args, ctx) => { await first.opened; ctx.output.result({ call: 'a' }); }, noArgs(), ownCall()); - const b = captureCommand(async (_args, ctx) => { await second.opened; ctx.output.result({ call: 'b' }); }, noArgs(), ownCall()); - second.open(); - expect(await b).toEqual({ call: 'b' }); - first.open(); - expect(await a).toEqual({ call: 'a' }); - expect(io.stdout()).toBe(''); - }); - - // Regression: the progress target and the active spinner were - // module globals. The second call to start took the target, so what the - // first call's spinners said went to the second call's client, and the - // first call's went nowhere once the second ended. - it('each keeps its own progress: what one call\'s spinners say never reaches the other\'s client', async () => { - const first = gate(); - const second = gate(); - const saidA: string[] = []; - const saidB: string[] = []; - let activeInA: Spinner | null | undefined; - const a = captureCommand(async (_args, ctx) => { - const spinner = ctx.progress.silent(); - spinner.update('a: before b starts'); - await first.opened; - spinner.update('a: while b runs'); - activeInA = ctx.progress.active(); - spinner.stop('a: done'); - }, noArgs(), ownCall({ onProgress: (message) => saidA.push(message) })); - const b = captureCommand(async (_args, ctx) => { - const spinner = ctx.progress.start('b: started'); - first.open(); - await second.opened; - spinner.stop('b: done'); - }, noArgs(), ownCall({ onProgress: (message) => saidB.push(message) })); - await new Promise((resolve) => setTimeout(resolve, 10)); - second.open(); - await Promise.all([a, b]); - expect(saidA).toEqual(['a: before b starts', 'a: while b runs', 'a: done']); - expect(saidB).toEqual(['b: started', 'b: done']); - // b's spinner is b's: a has none running. - expect(activeInA).toBeNull(); - }); - - it('keeps a result as it was written: a change the command makes after is not seen', async () => { - const result = await captureCommand(async (_args, ctx) => { - const data: Record = { balance: '1' }; - ctx.output.result(data); - data.balance = '2'; - }, noArgs(), ownCall()); - expect(result).toEqual({ balance: '1' }); - }); - - it('refuses a second result in one call', async () => { - await expect(captureCommand(async (_args, ctx) => { - ctx.output.result({ call: 'first' }); - ctx.output.result({ call: 'second' }); - }, noArgs(), ownCall())).rejects.toThrow(SecondResultError); - }); - - it('sends a command\'s text for the person to the server\'s stderr, never stdout', async () => { - await captureCommand(async (_args, ctx) => { - ctx.output.stdout('shown\n'); - ctx.output.stderr('chrome\n'); - ctx.output.result({ ok: true }); - }, noArgs(), ownCall()); - expect(io.stdout()).toBe(''); - expect(io.stderr()).toBe('shown\nchrome\n'); - }); - }); }); diff --git a/src/__tests__/two-hosts.test.ts b/src/__tests__/two-hosts.test.ts index 3c6280bd..f4e4bb49 100644 --- a/src/__tests__/two-hosts.test.ts +++ b/src/__tests__/two-hosts.test.ts @@ -94,8 +94,8 @@ async function run(host: Host, argv: string[]): Promise> signal: new AbortController().signal, output, host, - loadPayer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, - loadProtectors: async () => [(await import('@kuiralabs/midnight-grant')).accountProtector], + payer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, + protectors: async () => [(await import('@kuiralabs/midnight-grant')).accountProtector], }); if (result === undefined) throw new Error(`${argv.join(' ')} wrote no result`); return result; diff --git a/src/__tests__/verbose-per-call.test.ts b/src/__tests__/verbose-per-call.test.ts index be5b3e73..557d0701 100644 --- a/src/__tests__/verbose-per-call.test.ts +++ b/src/__tests__/verbose-per-call.test.ts @@ -8,8 +8,7 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Buffer } from 'node:buffer'; -import { captureCommand } from '../lib/run-command.ts'; -import { callDiagnostics, parseArgs, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; +import { callDiagnostics, captureCommand, parseArgs, type NetworkConfig } from '@kuiralabs/midnight-cli-core'; import { rcKeys } from '../../test-support/rc-engine.ts'; import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; import { balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; @@ -17,8 +16,6 @@ import { captureOutput, type CapturedOutput } from '../../test-support/capture-o import { ownCall } from './helpers/own-call.ts'; import { testHost } from '../../test-support/test-host.ts'; -// The handler, as the shell loads it. -const { default: balanceCommand } = await balanceDefinition.load(); // One host for every call, as the MCP server has: its notices are where verbose lines go. const host = testHost({ notice: (line) => notices.push(line) }); @@ -50,8 +47,8 @@ afterEach(() => { describe('verbose, per call', () => { it('two balance calls at once, one --verbose: only the verbose one writes diagnostic lines', async () => { - const verboseCall = captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall({ host })); - const quietCall = captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall({ host })); + const verboseCall = captureCommand(balanceDefinition, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall({ host })); + const quietCall = captureCommand(balanceDefinition, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall({ host })); const outcomes = await Promise.allSettled([verboseCall, quietCall]); // Neither reaches an indexer; both fail, each with its own error. expect(outcomes.map((o) => o.status)).toEqual(['rejected', 'rejected']); @@ -60,11 +57,11 @@ describe('verbose, per call', () => { }); it('a call after a verbose one is quiet', async () => { - const verbose = await captureCommand(balanceCommand, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall({ host })).then(() => null, (err: unknown) => err); + const verbose = await captureCommand(balanceDefinition, parseArgs(['balance', VERBOSE_ADDRESS, '--verbose', ...UNREACHABLE]), ownCall({ host })).then(() => null, (err: unknown) => err); // It got as far as its first diagnostic, and failed connecting. expect(notices.some((line) => line.includes(`balance: address=${VERBOSE_ADDRESS}`))).toBe(true); notices = []; - const quiet = await captureCommand(balanceCommand, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall({ host })).then(() => null, (err: unknown) => err); + const quiet = await captureCommand(balanceDefinition, parseArgs(['balance', QUIET_ADDRESS, ...UNREACHABLE]), ownCall({ host })).then(() => null, (err: unknown) => err); // It got as far too, failing the same way, past where the verbose one wrote its diagnostic. expect(quiet).toBeInstanceOf(Error); expect((quiet as Error).message).toBe((verbose as Error).message.replace(VERBOSE_ADDRESS, QUIET_ADDRESS)); diff --git a/src/lib/code-tables.ts b/src/lib/code-tables.ts index 80763df1..c71808cb 100644 --- a/src/lib/code-tables.ts +++ b/src/lib/code-tables.ts @@ -7,7 +7,7 @@ // The manual's and the skills' rows come from each package's guidance // (codeGuidancePieces). -import { declaredCodeSets, type CommandHelpSpec, type CommandRegistry, type CodeDefinition, wrapWords } from '@kuiralabs/midnight-cli-core'; +import { declaredCodeSets, type CommandHelpSpec, type CommandRegistry, type CodeDefinition, listedNames, wrapWords } from '@kuiralabs/midnight-cli-core'; import { EVERY_COMMAND } from '@kuiralabs/midnight-cli-core/commands'; import { withGeneratedBlock } from './readme-commands.ts'; @@ -53,11 +53,6 @@ export function manualCodeLines(registry: Pick, sty }); } -/** Names in a sentence: "network", "network and wallet", "network, wallet and engine". */ -export function listedNames(names: readonly string[]): string { - return names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`; -} - /** * A command's Errors section, each line from `indent`: one per code of its own * (the code in the manual's column, its exit code, its meaning), one per exit diff --git a/src/lib/command-dispatch.ts b/src/lib/command-dispatch.ts index ed2a5437..37250139 100644 --- a/src/lib/command-dispatch.ts +++ b/src/lib/command-dispatch.ts @@ -3,19 +3,11 @@ // shell (src/wallet.ts) owns the process: it passes in what a handler may be // given and where a notice goes, and decides the heap and the exit. -import { type ParsedArgs, createCallContext, runHandler, type CallContext, type CommandOutcome, type CallOutput, type CommandDefinition, type CommandRegistry, UsageError, writeJsonResult, type Payer, type CallSdkWarnings, type Host } from '@kuiralabs/midnight-cli-core'; +import { type ParsedArgs, type CommandOutcome, type CallOutput, type CommandDefinition, type CommandRegistry, type CommandRun, UsageError, writeJsonResult, runCommand } from '@kuiralabs/midnight-cli-core'; import type { WalletProtector } from '@kuiralabs/midnight-wallet'; -/** What the shell can give a handler: its call's signal and output, and, as its definition's `shell` field asks, the payer or protectors, loaded only then. */ -export interface ShellProvisions { - readonly signal: AbortSignal; - /** Where the call's output goes; a definition's notice goes to its stderr, before the handler loads. */ - readonly output: CallOutput; - /** The host the call runs in; each call runs in one of its calls, with its own SDK warnings. */ - readonly host: Host; - readonly loadPayer: () => Promise; - readonly loadProtectors: () => Promise; -} +/** What the shell gives a command: its call's signal and output, the host, and the payer and protectors, loaded only for a command whose definition asks for them. */ +export type ShellProvisions = CommandRun & { readonly output: CallOutput }; /** The CLI's output, written at once: the result as one line of JSON on stdout, text on stdout and stderr. */ export const processOutput: CallOutput = { @@ -41,30 +33,13 @@ export function findInstalledCommand(registry: CommandRegistry, name: string): C return definition; } -/** The call's context: its signal, its output, its SDK warnings and --verbose, and the payer or the protectors when its definition asks for them. */ -async function cliCallContext(definition: CommandDefinition, args: ParsedArgs, provisions: ShellProvisions, sdkWarnings: CallSdkWarnings): Promise> { - const { payer, protectors } = definition.shell; - return createCallContext({ - host: provisions.host, - args, - signal: provisions.signal, - output: provisions.output, - sdkWarnings, - ...(payer === true ? { payer: await provisions.loadPayer() } : {}), - ...(protectors === true ? { protectors: await provisions.loadProtectors() } : {}), - }); -} - /** - * Runs the command named by `name` with `args`: refuses it when its - * definition says it is unavailable, writes its notice, loads its handler and - * calls it with its call's context; a call already cancelled never starts. - * Returns the exit code the handler gives, for the shell to set. + * Runs the command named by `name` with `args` (core's `runCommand`): + * refuses it when its definition says it is unavailable, writes its notice, + * loads its handler and calls it with its call's context; a call already + * cancelled never starts. Returns the exit code the handler gives, for the + * shell to set. */ export async function dispatchCommand(registry: CommandRegistry, name: string, args: ParsedArgs, provisions: ShellProvisions): Promise { - const definition = findInstalledCommand(registry, name); - if (definition.shell.unavailable !== undefined) throw new Error(definition.shell.unavailable); - if (definition.shell.notice !== undefined) provisions.output.stderr(definition.shell.notice); - const { default: handler } = await definition.load(); - return provisions.host.sdkWarnings.run(async (sdkWarnings) => runHandler(handler, args, await cliCallContext(definition, args, provisions, sdkWarnings))); + return runCommand(findInstalledCommand(registry, name), args, provisions); } diff --git a/src/lib/mcp/registry-tools.ts b/src/lib/mcp/registry-tools.ts index 0675fbbd..ac23bd20 100644 --- a/src/lib/mcp/registry-tools.ts +++ b/src/lib/mcp/registry-tools.ts @@ -5,9 +5,7 @@ // server's one tool of its own, midnight_confirm_operation, redeems the tokens // the confirmation flow gives. -import { type CommandRun, captureCommand } from '../run-command.ts'; -import { listedNames } from '../code-tables.ts'; -import { getEndpointOverridesForNetwork, loadCliConfig, resolveNetworkName, type CommandRegistry, type RegisteredTool, type ToolAnnotations, type ToolInputSchema, commandOwnCodes, confirmationText, declaredSets, toolArgv } from '@kuiralabs/midnight-cli-core'; +import { captureCommand, type CommandRun, getEndpointOverridesForNetwork, loadCliConfig, resolveNetworkName, type CommandRegistry, type ParsedArgs, type RegisteredTool, type ToolAnnotations, type ToolInputSchema, confirmationText, toolArgv, toolDescription } from '@kuiralabs/midnight-cli-core'; /** A tool as tools/list sends it. */ export interface ListedTool { @@ -25,19 +23,6 @@ export const CONFIRM_TOOL: ListedTool = { annotations: { destructiveHint: true, openWorldHint: true }, }; -/** - * A command's tool's description as tools/list sends it: its definition's, - * then the codes its command can end with: its own, and the sets it declares - * by name, which the full skill lists. - */ -export function toolDescription(registry: Pick, tool: RegisteredTool): string { - const own = commandOwnCodes(registry, tool.command).map((definition) => definition.code); - const sets = declaredSets(tool.command).map((set) => set.name); - if (own.length === 0 && sets.length === 0) return tool.description; - const named = sets.length === 0 ? '' : `the ${listedNames(sets)} codes (see the skill)`; - return `${tool.description} Errors: ${own.join(', ')}${own.length > 0 && named !== '' ? '; and ' : ''}${named}.`; -} - /** tools/list: every tool the installed commands define, in the registry's order, then the confirm tool. */ export function listedTools(registry: CommandRegistry): ListedTool[] { return [...registry.tools.map((tool) => ({ ...tool, description: toolDescription(registry, tool) })), CONFIRM_TOOL].map((tool) => ({ @@ -53,9 +38,17 @@ export function findTool(registry: CommandRegistry, name: string): RegisteredToo return registry.tools.find((tool) => tool.name === name); } +/** The server's stderr: where a call's text for the person goes, never the protocol channel on stdout. */ +const serverStderr = (text: string): void => { process.stderr.write(text); }; + +/** Runs the tool's command with `args` (core's `captureCommand`), its text on the server's stderr, and returns its JSON result. */ +function captureTool(tool: RegisteredTool, args: ParsedArgs, call: CommandRun): Promise> { + return captureCommand(tool.command, args, { ...call, text: serverStderr }); +} + /** Runs the tool's command with the argv its parameters map to, and returns its JSON result. */ export async function runTool(tool: RegisteredTool, params: Readonly>, call: CommandRun): Promise> { - return captureCommand((await tool.command.load()).default, toolArgv(tool, params), call); + return captureTool(tool, toolArgv(tool, params), call); } /** The endpoint parameters, and how a confirmation names each. */ @@ -92,7 +85,7 @@ export async function confirmationFor(tool: RegisteredTool, params: Readonly toolArgv(tool, params), - run: async (args) => captureCommand((await tool.command.load()).default, args, call), + run: async (args) => captureTool(tool, args, call), }); return (found ?? confirmationText(tool, params)) + endpointOverridesNote(tool, params, call.host.paths().stateRoot); } diff --git a/src/lib/run-command.ts b/src/lib/run-command.ts deleted file mode 100644 index 9db105c4..00000000 --- a/src/lib/run-command.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Run a command handler and capture its JSON output -// Used by the MCP server to invoke CLI commands programmatically - -import { type ParsedArgs, MINIMAL_FLAG, type Payer, createCallContext, runHandler, type CommandHandler, type CallOutput, type Host, CommandFailedError } from '@kuiralabs/midnight-cli-core'; - -export interface CommandRun { - /** Cancels the command; a call already cancelled never starts. None: it runs to the end. */ - signal?: AbortSignal; - /** Each message the command's spinners say while it runs, --json mode included. */ - onProgress?: (message: string) => void; - /** What a command that submits a transaction pays with. */ - payer?: Payer; - /** - * The host the command runs in. Its calls give the command its own SDK - * warnings, so the host's filters report the SDK's warnings to this call. - */ - host: Host; -} - -/** The server's stderr: where a call's text for the person goes, never the protocol channel on stdout. */ -const serverStderr = (text: string): void => { process.stderr.write(text); }; - -/** - * Execute a command handler with --json mode, capturing the JSON result. - * - * The call gets a context of its own: its result is kept for this call - * alone, as JSON reads it back, so two calls that overlap never see each - * other's result, and none reaches stdout, the MCP stdio channel. Its text for - * the person goes to the server's stderr, which clients typically log - * separately. - * - * Also opts every MCP-invoked command into agent-slim mode by injecting - * `_minimal: true` into args.flags. Handlers that opt in (currently: - * wallet list) emit a smaller JSON shape for agents while keeping - * `mn --json` (human path) byte-for-byte identical, since humans - * never go through captureCommand. Tool handlers expose a `full: true` - * escape hatch by setting `_full: true` in args.flags — handlers treat - * that as "agent explicitly wants the full shape" and emit the human - * shape instead. - * - * What the command's spinners say goes to `onProgress` while it runs, and - * nothing once it is over: each call has its own progress, so two calls - * at once never report each other's. - * - * Returns the result as a JSON object ({} when the command wrote none). - * Throws the original error if the handler throws, and CommandFailedError, - * carrying the result, if it returns a non-zero exit code. - */ -export async function captureCommand( - handler: CommandHandler, - args: ParsedArgs, - { signal, onProgress, payer, host }: CommandRun, -): Promise> { - let result: Record = {}; - const output: CallOutput = { - // Read back as JSON, as the server sends it: what was written then, nothing the handler changes after. - result: (data) => { result = JSON.parse(JSON.stringify(data)) as Record; }, - stdout: serverStderr, - stderr: serverStderr, - }; - args.flags.json = true; - if (!(MINIMAL_FLAG in args.flags)) { - args.flags[MINIMAL_FLAG] = true; - } - // The call's own progress, closed when it ends: a spinner it left running says nothing after. - let running = true; - const report = onProgress === undefined ? undefined : (message: string): void => { if (running) onProgress(message); }; - try { - const outcome = await host.sdkWarnings.run((warnings) => runHandler(handler, args, createCallContext({ - host, - args, - signal: signal ?? new AbortController().signal, - output, - sdkWarnings: warnings, - ...(report === undefined ? {} : { onProgress: report }), - ...(payer === undefined ? {} : { payer }), - }))); - if (outcome !== undefined && outcome.exitCode !== 0) throw new CommandFailedError(args.command ?? 'the command', outcome.exitCode, result); - return result; - } finally { - running = false; - } -} diff --git a/src/mcp-server.ts b/src/mcp-server.ts index 5fbff504..d777f98c 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -14,9 +14,8 @@ import { type ServerRequest, } from '@modelcontextprotocol/sdk/types.js'; import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'; -import type { CommandRun } from './lib/run-command.ts'; import { servePayer } from '@kuiralabs/midnight-connect'; -import { classifyError, asReported, trimAgentMessage, needsConfirmation, type Host } from '@kuiralabs/midnight-cli-core'; +import { classifyError, asReported, trimAgentMessage, needsConfirmation, type CommandRun, type Host } from '@kuiralabs/midnight-cli-core'; import { withServerAdvice } from './lib/mcp/server-advice.ts'; import { PKG_VERSION } from './lib/pkg.ts'; import { createConfirmationStore } from './lib/mcp/confirmation.ts'; diff --git a/src/wallet.ts b/src/wallet.ts index a763fea1..6d94185c 100644 --- a/src/wallet.ts +++ b/src/wallet.ts @@ -92,9 +92,9 @@ async function run(): Promise { signal, output: processOutput, host, - loadPayer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, + payer: async () => (await import('@kuiralabs/midnight-connect')).servePayer, // wallet protect also seals grant's accounts, through the protector grant provides. - loadProtectors: async () => [(await import('@kuiralabs/midnight-grant')).accountProtector], + protectors: async () => [(await import('@kuiralabs/midnight-grant')).accountProtector], }); } From 63e4a686105260ffbfe1e4f02386d6b058f49eeb Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 15:14:27 -0800 Subject: [PATCH 80/88] Package READMEs, registry entries per package, two typed codes (3H, part 2) - Each public package has a README (Y63): install, entry points, what you call, its codes, and one example that mounts its commands (an engine's shows loading). Core's README adds "Mounting commands in your program", and mn's README a section for programs. - The codes tables are generated (npm run package-readmes) and checked. package-readmes.test.ts runs every example as written, in a child process with its own home: config under ~/.my-app, a generated wallet, and typed errors (WALLET_NOT_FOUND, NETWORK_ERROR, CONTRACT_NOT_COMPILED, NO_TEST_CONFIG, NO_ACCOUNT), plus each engine loaded by its network's set. - Each package's ./commands exports its registry entry: coreCommands, chainCommands, walletCommands, swapCommands, contractCommands, connectCommands, devCommands, grantCommands. mn's registry is built from them. The README test found that a registry needs the entries of the packages a package builds on, which the examples now show. - Y64: "No compiled contract found" is now CONTRACT_NOT_COMPILED (contract, dev, test), and "No dapp.test.json found" is NO_TEST_CONFIG (test); both were UNKNOWN. Exported as ContractNotCompiledError and NoTestConfigError, with regression rows in error-code-parity. Suite 3058 green, beta 195. The snapshot against rc.13 differs only by the two codes. --- README.md | 6 + docs/JSON_CONTRACT.md | 2 + docs/SKILL.md | 2 + package.json | 3 +- packages/chain/README.md | 76 +++++++++ packages/chain/api-report.md | 1 + packages/chain/src/commands.ts | 1 + packages/chain/src/commands/chain.package.ts | 11 ++ packages/cli-core/README.md | 97 +++++++++++- packages/cli-core/api-report.md | 1 + packages/cli-core/src/commands.ts | 1 + .../cli-core/src/commands/core.package.ts | 10 ++ packages/connect/README.md | 68 ++++++++ packages/connect/api-report.md | 1 + packages/connect/src/commands.ts | 1 + .../connect/src/commands/connect.package.ts | 9 ++ packages/contract/README.md | 77 +++++++++ packages/contract/api-report.md | 12 ++ packages/contract/src/commands.ts | 1 + .../contract/src/commands/contract.codes.ts | 1 + .../src/commands/contract.definition.ts | 2 +- .../contract/src/commands/contract.package.ts | 11 ++ packages/contract/src/index.ts | 2 +- packages/contract/src/lib/contract/inspect.ts | 12 +- packages/dev/README.md | 76 +++++++++ packages/dev/api-report.md | 12 ++ packages/dev/src/commands.ts | 1 + packages/dev/src/commands/dev.codes.ts | 3 +- packages/dev/src/commands/dev.definition.ts | 2 +- packages/dev/src/commands/dev.package.ts | 12 ++ packages/dev/src/commands/test.definition.ts | 2 +- packages/dev/src/index.ts | 1 + packages/dev/src/lib/test/discovery.ts | 12 +- packages/engine-beta/README.md | 47 ++++++ packages/engine-rc/README.md | 47 ++++++ packages/grant/README.md | 77 +++++++++ packages/grant/api-report.md | 1 + packages/grant/src/commands.ts | 1 + packages/grant/src/commands/grant.package.ts | 10 ++ packages/wallet/README.md | 76 +++++++++ packages/wallet/api-report.md | 2 + packages/wallet/src/commands.ts | 2 + packages/wallet/src/commands/swap.package.ts | 9 ++ .../wallet/src/commands/wallet.package.ts | 19 +++ scripts/check-layering.mjs | 6 +- scripts/write-package-readmes.ts | 18 +++ src/__tests__/command-flags.test.ts | 4 +- src/__tests__/error-code-parity.test.ts | 8 +- src/__tests__/help.test.ts | 2 + src/__tests__/package-readmes.test.ts | 149 ++++++++++++++++++ src/lib/installed-commands.ts | 35 ++-- src/lib/package-readmes.ts | 40 +++++ 52 files changed, 1047 insertions(+), 35 deletions(-) create mode 100644 packages/chain/README.md create mode 100644 packages/chain/src/commands/chain.package.ts create mode 100644 packages/cli-core/src/commands/core.package.ts create mode 100644 packages/connect/README.md create mode 100644 packages/connect/src/commands/connect.package.ts create mode 100644 packages/contract/README.md create mode 100644 packages/contract/src/commands/contract.package.ts create mode 100644 packages/dev/README.md create mode 100644 packages/dev/src/commands/dev.package.ts create mode 100644 packages/engine-beta/README.md create mode 100644 packages/engine-rc/README.md create mode 100644 packages/grant/README.md create mode 100644 packages/grant/src/commands/grant.package.ts create mode 100644 packages/wallet/README.md create mode 100644 packages/wallet/src/commands/swap.package.ts create mode 100644 packages/wallet/src/commands/wallet.package.ts create mode 100644 scripts/write-package-readmes.ts create mode 100644 src/__tests__/package-readmes.test.ts create mode 100644 src/lib/package-readmes.ts diff --git a/README.md b/README.md index 1d6ffd38..8deab96f 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,12 @@ The legacy `midnight-wallet://skill` URI still works as an alias for `/full`. Every tool error returns `{ error: true, code: , message: }`. Agents should index on the stable `code` (`INSUFFICIENT_BALANCE`, `DUST_REQUIRED`, `INVALID_DUST_PROOF`, `STALE_CACHE`, `PROOF_FAILURE`, `SYNC_TIMEOUT`, `NETWORK_ERROR`, `WALLET_NOT_FOUND`, `INVALID_ARGS`, `TX_REJECTED`, `STALE_UTXO`, `PROOF_TIMEOUT`, `CANCELLED`, `UNKNOWN`) — full taxonomy + recovery recipes are in `docs/SKILL.md`. +## Using mn's packages in your program + +mn is built from packages a program can install on its own: `@kuiralabs/midnight-cli-core` (the host, typed errors and codes, running a command), `@kuiralabs/midnight-chain`, `@kuiralabs/midnight-wallet` (with swap), `@kuiralabs/midnight-contract`, `@kuiralabs/midnight-connect`, `@kuiralabs/midnight-dev`, `@kuiralabs/midnight-grant`, and the two SDK engines, `@kuiralabs/midnight-engine-rc` and `@kuiralabs/midnight-engine-beta`. A program calls their functions with plain values (bigint amounts, typed results and receipts), or mounts their commands in its own command line or MCP server, with its own state root, settings, prompter and output; errors carry a `code` it can act on without reading messages. All are release candidates on the `next` tag; install them with npm. + +Start with [core's README](packages/cli-core/README.md): mounting commands, and what a program does to its own process for the wallet SDK. Each package's README lists its entry points, its codes and one example, and its `api-report.md` lists every export. + ## Issues & Feedback Found a bug or have a feature request? [Open an issue](https://github.com/kuiralabs/midnight-cli/issues). diff --git a/docs/JSON_CONTRACT.md b/docs/JSON_CONTRACT.md index 821391d6..58de66a9 100644 --- a/docs/JSON_CONTRACT.md +++ b/docs/JSON_CONTRACT.md @@ -111,10 +111,12 @@ Stable identifiers used in error messages and structured error objects, with the | `CHAIN_CLOCK_BEHIND` | 4 | The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold. | | `UNSUPPORTED_LEDGER` | 4 | The network is on ledger 8; this build supports ledger 9 only. | | `LOCALNET_UNAVAILABLE` | 4 | `mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build. | +| `NO_TEST_CONFIG` | 1 | No dapp.test.json in the folder the test command ran in. | | `LOCAL_STACK_UNREACHABLE` | 4 | No ledger-9 stack answers at the configured endpoints. | | `AMBIGUOUS_LOCAL_STACKS` | 4 | Several local Midnight stacks are running and no endpoints are configured, so mn won't guess. | | `UNSUPPORTED_NODE` | 1 | Node.js is older than 22 (22.18 for mn grant). | | `NO_NODE_RUNTIME` | 1 | Contract scripts run under Node.js, and none was found on PATH. | +| `CONTRACT_NOT_COMPILED` | 1 | No compiled contract was found where the command looked (managed//compiler/contract-info.json). | | `NO_ACCOUNT` | 1 | A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network. | | `CALLER_PIN_UNSUPPORTED` | 2 | A grant request pins the contract that calls the account, and the account on this network (stagenet) has no caller pin; nothing was submitted. | | `WRONG_PASSPHRASE` | 2 | `MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | diff --git a/docs/SKILL.md b/docs/SKILL.md index 9d65581c..b3eaa2a6 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -159,10 +159,12 @@ Every MCP tool error returns `{ error: true, code: , message: /compiler/contract-info.json). | Ask the user to compile the contract (compact compile), or pass the dApp folder (path) or the managed folder (managed). | | `NO_ACCOUNT` | A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network. | Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow). | | `CALLER_PIN_UNSUPPORTED` | A grant request pins the contract that calls the account, and the account on this network (stagenet) has no caller pin; nothing was submitted. | Tell the user; ask the agent for a grant request that names no calling contract, or issue it on undeployed. | | `WRONG_PASSPHRASE` | `MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed. | diff --git a/package.json b/package.json index a67aed70..40e9c396 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,8 @@ "api-report": "node scripts/api-report.mjs write", "typecheck": "tsc --noEmit", "skill-docs": "tsx --conditions=midnight-cli-source scripts/write-skill-docs.ts", - "readme-commands": "tsx --conditions=midnight-cli-source scripts/write-readme-commands.ts" + "readme-commands": "tsx --conditions=midnight-cli-source scripts/write-readme-commands.ts", + "package-readmes": "tsx --conditions=midnight-cli-source scripts/write-package-readmes.ts" }, "dependencies": { "@kuiralabs/midnight-chain": "0.1.0-rc.2", diff --git a/packages/chain/README.md b/packages/chain/README.md new file mode 100644 index 00000000..2797feeb --- /dev/null +++ b/packages/chain/README.md @@ -0,0 +1,76 @@ +# @kuiralabs/midnight-chain + +Read-only network access for the Midnight CLI packages: whether a node, an indexer and a proof server are ready, the chain's id, time and tip, its events, the ledger version a chain runs (and the guard that refuses one this build doesn't support), and a transaction's status and receipt. It holds no wallet and sends nothing. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-chain@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-chain` | The functions below, and the errors they throw | +| `@kuiralabs/midnight-chain/commands` | `tx` (and `status`, refused while it is reworked) as a registry entry (`chainCommands`), its codes (`chainCodes`) | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/chain/api-report.md). + +## What you call + +- `transactionStatus`, `receiptOf`, `receiptJson`: where a transaction is (pending, in a block, failed) and its receipt. +- `waitForFirstBlock`, `waitForProofServerReady`, `assertNetworkAnswers`: wait for or check a network's services. +- `fetchProtocolVersion`, `assertLedgerSupported`, `walletsBelowLedger`: the ledger a chain runs. +- `getChainGenesisHash`, `fetchChainTime`, `assertChainClockCurrent`, `fetchEventTip`: the chain's id, time and tip. +- `queryIndexer`, `subscribeGraphqlWs`, `callNodeRpc`: the indexer's GraphQL and the node's RPC, with their failures typed. + +## Codes + +Each error carries a `code`, and `classifyError(err, registry)` gives its code and exit code by that code alone, never by its message. These are the codes this package owns; the rest come from core and the packages below it, each listed in its README. + + +| Code | Exit | What went wrong | What to do | +|------|------|-----------------|------------| +| `CHAIN_CLOCK_BEHIND` | 4 | The chain's clock lags this computer's (a local chain after sleep), so Dust estimates don't hold. | Wait for it to catch up, or ask the user to restart the local chain. | +| `UNSUPPORTED_LEDGER` | 4 | The network is on ledger 8; this build supports ledger 9 only. | Tell the user: this network needs midnight-wallet-cli 0.5.x. Don't retry. | +| `LOCAL_STACK_UNREACHABLE` | 4 | No ledger-9 stack answers at the configured endpoints. | Ask the user to start their stack or fix the configured node / indexer-ws / proof-server endpoints. | + + +## Mounting its commands + +The commands are definitions your program mounts in its own command line, with your state root, settings and notices (core's README explains each part). Its commands name codes the packages it builds on own, so the registry holds their entries too, as mn's does; a registry missing one is refused when it is built. Built on core's example, this one adds chain's `tx` command: + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands, chainCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`node my-cli.mjs tx status --network preview` prints where the transaction is. With an indexer that doesn't answer, it ends with `NETWORK_ERROR` and exit code 4. A test in mn runs the block above as it is written. diff --git a/packages/chain/api-report.md b/packages/chain/api-report.md index c557f8e7..c08b9046 100644 --- a/packages/chain/api-report.md +++ b/packages/chain/api-report.md @@ -96,6 +96,7 @@ export declare const chainCodes: readonly [ ]; export declare const READS_CHAIN: import("@kuiralabs/midnight-cli-core").CodeSet; export declare const chainGuidance: PackageGuidance; +export declare const chainCommands: CommandPackage; export declare const statusDefinition: CommandDefinition; export declare const txDefinition: CommandDefinition; ``` diff --git a/packages/chain/src/commands.ts b/packages/chain/src/commands.ts index 9fe9c9c1..ef26ea26 100644 --- a/packages/chain/src/commands.ts +++ b/packages/chain/src/commands.ts @@ -4,5 +4,6 @@ export { chainCodes, READS_CHAIN } from './commands/chain.codes.ts'; export { chainGuidance } from './commands/chain.guidance.ts'; +export { chainCommands } from './commands/chain.package.ts'; export { statusDefinition } from './commands/status.definition.ts'; export { txDefinition } from './commands/tx.definition.ts'; diff --git a/packages/chain/src/commands/chain.package.ts b/packages/chain/src/commands/chain.package.ts new file mode 100644 index 00000000..f0b549e1 --- /dev/null +++ b/packages/chain/src/commands/chain.package.ts @@ -0,0 +1,11 @@ +// The chain package's commands, as a program's registry installs them: +// createPackageRegistry([..., chainCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { statusDefinition } from './status.definition.ts'; +import { txDefinition } from './tx.definition.ts'; +import { chainGuidance } from './chain.guidance.ts'; +import { chainCodes } from './chain.codes.ts'; + +/** The chain package's commands, their agent guidance and codes, as one entry of a program's registry. */ +export const chainCommands: CommandPackage = { name: 'chain', commands: [statusDefinition, txDefinition], guidance: chainGuidance, codes: chainCodes }; diff --git a/packages/cli-core/README.md b/packages/cli-core/README.md index 8d7fa98b..53d9bf28 100644 --- a/packages/cli-core/README.md +++ b/packages/cli-core/README.md @@ -1,6 +1,101 @@ # @kuiralabs/midnight-cli-core -The base of the Midnight CLI packages: the host a program passes to them, typed errors and their codes, networks, settings and the state root, the wallet session, and the engine contract the SDK engines are built against. +The base of the Midnight CLI packages: the host a program passes to them, typed errors and their codes, networks, settings and the state root, the wallet session, running a command from its definition, and the engine contract the SDK engines are built against. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine too: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-cli-core` | The host (`createHost`), typed errors and `classifyError`, networks, settings, amounts, arguments (`parseArgs`), the command registry (`createPackageRegistry`), running a command (`runCommand`, `captureCommand`), the wallet session (`openWalletSession`) | +| `@kuiralabs/midnight-cli-core/commands` | core's own command (`config`) as a registry entry (`coreCommands`), its codes (`coreCodes`) and the code sets other packages' commands name | +| `@kuiralabs/midnight-cli-core/process` | What a program does to its own process: `installSdkProcessGuard`, `syncHeapAdvice` | +| `@kuiralabs/midnight-cli-core/ui` | Terminal formatting, spinners and the terminal prompter mn uses | +| `@kuiralabs/midnight-cli-core/engine` | The engine contract, for the engine packages | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/api-report.md). + +## Codes + +Each error a package throws carries a `code`; `classifyError(err, registry)` gives its code and exit code by that code alone. These are core's own; each package lists its own in its README. + + +| Code | Exit | What went wrong | What to do | +|------|------|-----------------|------------| +| `INVALID_ARGS` | 2 | Missing/invalid argument. | Show the message to the user verbatim — it names the missing field. | +| `NETWORK_ERROR` | 4 | Indexer/node/proof-server connection refused or DNS failure. | Check `midnight_localnet_status()` or the endpoints the user configured; on this build `midnight_localnet_up()` is refused, so ask the user to start their ledger-9 stack. | +| `SYNC_TIMEOUT` | 4 | Long-running wallet sync hit its deadline. Common on a hosted-network first-cold-sync. | Retry; the cache resumes from the last applied event so progress is preserved. | +| `INSUFFICIENT_BALANCE` | 5 | Wallet doesn't have enough NIGHT to cover the requested amount. | Show the user. On localnet: `midnight_airdrop({ amount: "..." })`. On hosted networks: tell user to fund the address. | +| `TX_REJECTED` | 6 | Chain rejected the submitted transaction (catch-all when no more specific code applies). | Read the message; usually a state mismatch resolved by re-sync + retry. | +| `STALE_UTXO` | 6 | UTXO was already spent on-chain (substrate "error code 115"). | Re-sync (the next call will refresh state) and retry. | +| `STALE_CACHE` | 6 | Local wallet cache disagrees with chain (e.g. localnet reset, remote testnet re-indexed). | `midnight_cache_clear({ wallet: "" })` then retry. | +| `PROOF_TIMEOUT` | 6 | ZK proof generation didn't finish within the deadline. | Retry — proofs can be slow under load. | +| `PROOF_FAILURE` | 6 | Proof server rejected or failed to generate the ZK proof. Often a stale commitment tree or unreachable proof server. | Check that the proof server is running (`midnight_localnet_status()`, or the endpoint the user configured); if it is, `midnight_cache_clear({ wallet: "" })` then retry. | +| `INVALID_DUST_PROOF` | 6 | Chain rejected the dust spend proof as malformed (substrate "Custom error 170"). Stale commitment tree. | `midnight_cache_clear({ wallet: "" })` then retry. | +| `DUST_REQUIRED` | 5 | Wallet has NIGHT but not enough DUST for the fee. | Not registered (`midnight_dust_status()` shows `registered: false`): run `midnight_dust_register()`. Registered: its NIGHT is still generating the fee, which happens with time. mn has already waited when the fee was a few minutes away; the message says how long the rest takes ("generates the rest in about 4 minutes"). Wait that long and retry, don't retry at once. | +| `DUST_GENERATING` | 5 | A Dust registration can't pay its fee yet: the wallet's NIGHT hasn't generated enough Dust. | The message says when: run `midnight_dust_register()` again then, or add NIGHT. | +| `AMBIGUOUS_LOCAL_STACKS` | 4 | Several local Midnight stacks are running and no endpoints are configured, so mn won't guess. | Ask the user which stack to use; they set its endpoints with `midnight config set`. Don't retry blindly. | +| `UNSUPPORTED_NODE` | 1 | Node.js is older than 22 (22.18 for mn grant). | Ask the user to install a current Node.js. | +| `WRONG_PASSPHRASE` | 2 | `MN_PASSPHRASE` is not the passphrase mn's secrets were encrypted with, or a sealed file was changed. | Ask the user to correct `MN_PASSPHRASE` in the MCP server's environment. Nothing was changed. | +| `PASSPHRASE_REQUIRED` | 2 | A tool needed a secret (a wallet's seed, an account's owner key) and no passphrase could be had: `MN_PASSPHRASE` is unset and there is no terminal to ask at (the MCP server has none). | Ask the user to set `MN_PASSPHRASE` in the MCP server's environment and restart it. Never ask them to type the passphrase into the chat. | +| `BLOCKFROST_PROJECT_ID_REQUIRED` | 4 | The network (preprod) is served by Blockfrost and no project id is set. | Ask the user to create a Midnight preprod project at https://blockfrost.io and run `midnight config set blockfrost-project-id ` themselves. Never ask them to paste the id into the chat. Don't retry until they have. | +| `BLOCKFROST_PROJECT_ID_REJECTED` | 4 | Blockfrost refused the project id (HTTP 403): mistyped, revoked, or for another network. | Ask the user to check it at blockfrost.io and set it again. Don't retry blindly. | +| `BLOCKFROST_LIMIT_REACHED` | 4 | Blockfrost's plan limit or rate limit. | Wait and retry once; if it persists, tell the user it is their Blockfrost plan. | +| `ENDPOINT_SHUT_DOWN` | 4 | An endpoint set by flag or config was shut down by its operator (the old preprod indexer). | `midnight_config_unset({ key: "indexer-ws" })` (and `node` if set), then retry. | +| `OTHER_SDK_SET` | 1 | The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet). | Make the call in a process of its own: ask the user to start an MCP server for that network. | +| `MIXED_SDK_LAYOUT` | 1 | mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger. | Ask the user to install mn with npm. | +| `NO_STATE_ROOT` | 1 | The host gave mn no place to keep its state (a program's `createHost` without paths). | Give the host its paths (`createHost({ paths })`). | +| `NO_PAYER` | 1 | A command that submits a transaction was called without a payer. | Give the call a payer. | +| `COMMAND_FAILED` | 1 | A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result. | Read the command's result in the message. | +| `NOT_AN_OFFER` | 2 | The bytes given as a swap offer are not one. | Ask the maker for the offer again. | +| `TERMS_MISMATCH` | 2 | A swap offer's own terms differ from the agreed ones. | Don't take it; agree the terms again with the maker. | +| `OFFER_EXPIRED` | 2 | A swap offer is past the expiry its maker set. | Ask the maker for a new one. | +| `OFFER_COINS_IN_USE` | 2 | A spend would use coins an open swap offer of this wallet's holds, cancelling it. | Cancel the offer first (`mn swap cancel`), or wait until it is taken. | +| `CANCELLED` | 7 | Operation was aborted (SIGINT, or the MCP call was cancelled). | A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user. | +| `UNKNOWN` | 1 | Error didn't match any known classifier. | Surface the message to the user. If reproducible, a new code may be warranted. | + + +## Mounting commands in your program + +Each package's commands are definitions a program mounts in its own command line: the registry is built from the packages you choose, and `runCommand` does around each handler what mn's shell does. The host gives the commands your state root, your settings, where notices go and, when a command asks a question, your prompter. + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`node my-cli.mjs config set network preview` writes `~/.my-app/config.json`, never mn's `~/.midnight`. Add a package's commands by adding its entry to the registry (`walletCommands`, `chainCommands` and so on; each package's README shows its own); a command that pays (contract, swap, grant, dev) takes a `payer` in the run, such as connect's `servePayer`. For an MCP server, `captureCommand(tool.command, toolArgv(tool, params), { host, text })` runs a tool's command and returns its JSON result, and `toolDescription(registry, tool)` gives the description to list, with the codes the tool can end with. A test in mn runs the block above as it is written. ## Your process: what mn's shell does that you must do diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index 40267625..671bd529 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -1052,6 +1052,7 @@ export declare const PAYS: import("../index.ts").CodeSet; export declare const READS_OFFERS: import("../index.ts").CodeSet; export declare const RESOLVES_NETWORK: import("../index.ts").CodeSet; export declare const coreGuidance: PackageGuidance; +export declare const coreCommands: CommandPackage; ``` ## `@kuiralabs/midnight-cli-core/engine` diff --git a/packages/cli-core/src/commands.ts b/packages/cli-core/src/commands.ts index 53ce22c4..8d503a6d 100644 --- a/packages/cli-core/src/commands.ts +++ b/packages/cli-core/src/commands.ts @@ -5,3 +5,4 @@ export { configDefinition } from './commands/config.definition.ts'; export { coreCodes, ENGINE_SYNC, EVERY_COMMAND, LOADS_ENGINE, PAYS, READS_OFFERS, RESOLVES_NETWORK } from './commands/core.codes.ts'; export { coreGuidance } from './commands/core.guidance.ts'; +export { coreCommands } from './commands/core.package.ts'; diff --git a/packages/cli-core/src/commands/core.package.ts b/packages/cli-core/src/commands/core.package.ts new file mode 100644 index 00000000..c825510c --- /dev/null +++ b/packages/cli-core/src/commands/core.package.ts @@ -0,0 +1,10 @@ +// The core package's commands, as a program's registry installs them: +// createPackageRegistry([..., coreCommands, ...]). + +import type { CommandPackage } from '../lib/command-definition.ts'; +import { configDefinition } from './config.definition.ts'; +import { coreGuidance } from './core.guidance.ts'; +import { coreCodes } from './core.codes.ts'; + +/** The core package's commands, their agent guidance and codes, as one entry of a program's registry. */ +export const coreCommands: CommandPackage = { name: 'core', commands: [configDefinition], guidance: coreGuidance, codes: coreCodes }; diff --git a/packages/connect/README.md b/packages/connect/README.md new file mode 100644 index 00000000..7852dfd2 --- /dev/null +++ b/packages/connect/README.md @@ -0,0 +1,68 @@ +# @kuiralabs/midnight-connect + +`mn serve` for the Midnight CLI packages: the DApp connector API over a local WebSocket JSON-RPC server, the serve manager that starts one or reuses one already running, and the payer that pays a command through it. A command that pays (contract, swap, grant, dev) takes this payer. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-wallet@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-connect` | The payer (`servePayer`, `servePayerAt`), the serve manager and the RPC server | +| `@kuiralabs/midnight-connect/commands` | `serve` as a registry entry (`connectCommands`) | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/connect/api-report.md). + +## What you call + +- `servePayer`: the payer that pays through a running `mn serve` for the wallet and network asked, starting one when none runs; `servePayerAt` for one at a given port. +- `startServeOrReuse`, `probeServeNetwork`: start or find a server. +- `createRpcServer`: the JSON-RPC server itself, over handlers you give. + +## Codes + +This package owns no codes of its own: its errors carry core's, and those of the packages below it, each listed in its README. `classifyError(err, registry)` gives an error's code and exit code by that code alone. + +## Mounting its commands + +The commands are definitions your program mounts in its own command line, with your state root, settings and notices (core's README explains each part). Its commands name codes the packages it builds on own, so the registry holds their entries too, as mn's does; a registry missing one is refused when it is built. Built on core's example, this one adds `serve` beside the wallet's commands, which make the wallet it serves: + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; +import { walletCommands } from '@kuiralabs/midnight-wallet/commands'; +import { connectCommands } from '@kuiralabs/midnight-connect/commands'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands, chainCommands, walletCommands, connectCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`node my-cli.mjs serve --wallet alice --network preview` serves alice's wallet until it is stopped; for a wallet that doesn't exist it ends with `WALLET_NOT_FOUND` and exit code 3. A test in mn runs the block above as it is written. diff --git a/packages/connect/api-report.md b/packages/connect/api-report.md index ae559485..09bc7ebb 100644 --- a/packages/connect/api-report.md +++ b/packages/connect/api-report.md @@ -67,5 +67,6 @@ export interface RpcServerOptions { ```ts export declare const connectGuidance: PackageGuidance; +export declare const connectCommands: CommandPackage; export declare const serveDefinition: CommandDefinition; ``` diff --git a/packages/connect/src/commands.ts b/packages/connect/src/commands.ts index be4ad2df..4e8ba35e 100644 --- a/packages/connect/src/commands.ts +++ b/packages/connect/src/commands.ts @@ -2,4 +2,5 @@ // guidance, for the shell that installs them. export { connectGuidance } from './commands/connect.guidance.ts'; +export { connectCommands } from './commands/connect.package.ts'; export { serveDefinition } from './commands/serve.definition.ts'; diff --git a/packages/connect/src/commands/connect.package.ts b/packages/connect/src/commands/connect.package.ts new file mode 100644 index 00000000..5b02ddb4 --- /dev/null +++ b/packages/connect/src/commands/connect.package.ts @@ -0,0 +1,9 @@ +// The connect package's commands, as a program's registry installs them: +// createPackageRegistry([..., connectCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { serveDefinition } from './serve.definition.ts'; +import { connectGuidance } from './connect.guidance.ts'; + +/** The connect package's commands, their agent guidance, as one entry of a program's registry. */ +export const connectCommands: CommandPackage = { name: 'connect', commands: [serveDefinition], guidance: connectGuidance }; diff --git a/packages/contract/README.md b/packages/contract/README.md new file mode 100644 index 00000000..9ce875a9 --- /dev/null +++ b/packages/contract/README.md @@ -0,0 +1,77 @@ +# @kuiralabs/midnight-contract + +Contracts for the Midnight CLI packages: deploying, calling and reading a Compact contract from its dApp folder, the requests a deploy or a call is built from, a compiled contract's circuits and witnesses, and the chain's block limits. A deploy or a call is proved and paid through a payer you pass (connect's `servePayer`, which runs it through `mn serve`); its contract script runs under Node.js, also when your program runs under bun. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-contract@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-contract` | The functions below, and the errors they throw (`ContractNotCompiledError` among them) | +| `@kuiralabs/midnight-contract/commands` | `contract` (inspect, deploy, call, state) and `inspect-cost` as a registry entry (`contractCommands`), its codes (`contractCodes`) | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/contract/api-report.md). + +## What you call + +- `deployContract`, `callContract`: deploy or call a compiled contract, paid by the payer you pass; they return receipts. +- `readContractState`, `contractExists`: a deployed contract's state. +- `findContractInfo`: a compiled contract's circuits and witnesses, from its `managed/` folder. +- `contractDeployRequest`, `contractCallRequest`: the requests a deploy or a call is built from, without sending them. + +## Codes + +Each error carries a `code`, and `classifyError(err, registry)` gives its code and exit code by that code alone, never by its message. These are the codes this package owns; the rest come from core and the packages below it, each listed in its README. + + +| Code | Exit | What went wrong | What to do | +|------|------|-----------------|------------| +| `NO_NODE_RUNTIME` | 1 | Contract scripts run under Node.js, and none was found on PATH. | Ask the user to install Node.js 22 or later, or to run mn under Node. | +| `CONTRACT_NOT_COMPILED` | 1 | No compiled contract was found where the command looked (managed//compiler/contract-info.json). | Ask the user to compile the contract (compact compile), or pass the dApp folder (path) or the managed folder (managed). | + + +## Mounting its commands + +The commands are definitions your program mounts in its own command line, with your state root, settings and notices (core's README explains each part). Its commands name codes the packages it builds on own, so the registry holds their entries too, as mn's does; a registry missing one is refused when it is built. Built on core's example, this one adds the contract commands, and connect's payer for the deploys and calls: + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; +import { walletCommands } from '@kuiralabs/midnight-wallet/commands'; +import { contractCommands } from '@kuiralabs/midnight-contract/commands'; +import { servePayer } from '@kuiralabs/midnight-connect'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands, chainCommands, walletCommands, contractCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output, payer: servePayer }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`node my-cli.mjs contract inspect --path ./my-dapp` lists the compiled contract's circuits; in a folder with no compiled contract it ends with `CONTRACT_NOT_COMPILED` and exit code 1. A test in mn runs the block above as it is written. diff --git a/packages/contract/api-report.md b/packages/contract/api-report.md index ac9abd14..244768a2 100644 --- a/packages/contract/api-report.md +++ b/packages/contract/api-report.md @@ -53,6 +53,10 @@ export interface ContractInfo { witnesses: WitnessInfo[]; siblings: string[]; } +export declare class ContractNotCompiledError extends Error { + readonly code = "CONTRACT_NOT_COMPILED"; + constructor(message: string); +} export declare function findContractInfo(startDir: string, contractName?: string): { info: ContractInfo; infoPath: string; @@ -203,9 +207,17 @@ export declare const contractCodes: readonly [ readonly order: 200; readonly summary: "Contract scripts run under Node.js, and none was found on PATH."; readonly recovery: "Ask the user to install Node.js 22 or later, or to run mn under Node."; + }, + { + readonly code: "CONTRACT_NOT_COMPILED"; + readonly exitCode: 1; + readonly order: 205; + readonly summary: "No compiled contract was found where the command looked (managed//compiler/contract-info.json)."; + readonly recovery: "Ask the user to compile the contract (compact compile), or pass the dApp folder (path) or the managed folder (managed)."; } ]; export declare const contractDefinition: CommandDefinition; export declare const contractGuidance: PackageGuidance; +export declare const contractCommands: CommandPackage; export declare const inspectCostDefinition: CommandDefinition; ``` diff --git a/packages/contract/src/commands.ts b/packages/contract/src/commands.ts index e1bfa0f7..4fde6571 100644 --- a/packages/contract/src/commands.ts +++ b/packages/contract/src/commands.ts @@ -5,4 +5,5 @@ export { contractCodes } from './commands/contract.codes.ts'; export { contractDefinition } from './commands/contract.definition.ts'; export { contractGuidance } from './commands/contract.guidance.ts'; +export { contractCommands } from './commands/contract.package.ts'; export { inspectCostDefinition } from './commands/inspect-cost.definition.ts'; diff --git a/packages/contract/src/commands/contract.codes.ts b/packages/contract/src/commands/contract.codes.ts index 759bf7a6..2235e19b 100644 --- a/packages/contract/src/commands/contract.codes.ts +++ b/packages/contract/src/commands/contract.codes.ts @@ -4,4 +4,5 @@ import { defineCodes, EXIT_GENERAL_ERROR } from '@kuiralabs/midnight-cli-core'; export const contractCodes = defineCodes([ { code: 'NO_NODE_RUNTIME', exitCode: EXIT_GENERAL_ERROR, order: 200, summary: 'Contract scripts run under Node.js, and none was found on PATH.', recovery: 'Ask the user to install Node.js 22 or later, or to run mn under Node.' }, + { code: 'CONTRACT_NOT_COMPILED', exitCode: EXIT_GENERAL_ERROR, order: 205, summary: 'No compiled contract was found where the command looked (managed//compiler/contract-info.json).', recovery: 'Ask the user to compile the contract (compact compile), or pass the dApp folder (path) or the managed folder (managed).' }, ]); diff --git a/packages/contract/src/commands/contract.definition.ts b/packages/contract/src/commands/contract.definition.ts index 8bb65751..d24532e9 100644 --- a/packages/contract/src/commands/contract.definition.ts +++ b/packages/contract/src/commands/contract.definition.ts @@ -156,7 +156,7 @@ export const contractDefinition: CommandDefinition = { intro: { brief: 'Inspect, deploy, call contracts', order: 10 }, needsWalletSdk: true, shell: { payer: true }, - errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_NODE_RUNTIME', 'NO_PAYER'] }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'CONTRACT_NOT_COMPILED', 'NO_NODE_RUNTIME', 'NO_PAYER'] }, load: () => import('./contract.ts'), mcp: { tools: [ diff --git a/packages/contract/src/commands/contract.package.ts b/packages/contract/src/commands/contract.package.ts new file mode 100644 index 00000000..5b4d8bf4 --- /dev/null +++ b/packages/contract/src/commands/contract.package.ts @@ -0,0 +1,11 @@ +// The contract package's commands, as a program's registry installs them: +// createPackageRegistry([..., contractCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { inspectCostDefinition } from './inspect-cost.definition.ts'; +import { contractDefinition } from './contract.definition.ts'; +import { contractGuidance } from './contract.guidance.ts'; +import { contractCodes } from './contract.codes.ts'; + +/** The contract package's commands, their agent guidance and codes, as one entry of a program's registry. */ +export const contractCommands: CommandPackage = { name: 'contract', commands: [inspectCostDefinition, contractDefinition], guidance: contractGuidance, codes: contractCodes }; diff --git a/packages/contract/src/index.ts b/packages/contract/src/index.ts index 818c7145..885635df 100644 --- a/packages/contract/src/index.ts +++ b/packages/contract/src/index.ts @@ -11,7 +11,7 @@ export { type CallContractOptions, type CalledCircuit, callContract } from './lib/contract/call.ts'; export { type DeployContractOptions, type DeployedContract, deployContract } from './lib/contract/deploy.ts'; export { contractExists } from './lib/contract/exists.ts'; -export { type CircuitInfo, type CompactType, type ContractInfo, findContractInfo, type WitnessInfo } from './lib/contract/inspect.ts'; +export { type CircuitInfo, type CompactType, type ContractInfo, ContractNotCompiledError, findContractInfo, type WitnessInfo } from './lib/contract/inspect.ts'; export { clearDappPrivateState, PRIVATE_STATE_DATABASE } from './lib/contract/private-state.ts'; export { type ContractCallRequest, contractCallRequest, type ContractDeployRequest, contractDeployRequest, type ContractLocation diff --git a/packages/contract/src/lib/contract/inspect.ts b/packages/contract/src/lib/contract/inspect.ts index c936defe..ac67cd6f 100644 --- a/packages/contract/src/lib/contract/inspect.ts +++ b/packages/contract/src/lib/contract/inspect.ts @@ -109,7 +109,7 @@ export function findContractInfo(startDir: string, contractName?: string): { inf return loadContractInfo(infoPath, join(managedDir, chosen), siblings); } - throw new Error( + throw new ContractNotCompiledError( `No compiled contract found in ${startDir}\n` + `Expected: managed//compiler/${CONTRACT_INFO_FILENAME}\n` + `Searched: ${SCAN_CANDIDATES.map((s) => s ? `${s}/managed/` : 'managed/').join(', ')}\n` + @@ -265,3 +265,13 @@ export function toJsonOutput(info: ContractInfo): Record { })), }; } + +/** No compiled contract (managed//compiler/contract-info.json) where one was looked for. */ +export class ContractNotCompiledError extends Error { + readonly code = 'CONTRACT_NOT_COMPILED'; + constructor(message: string) { + super(message); + this.name = 'ContractNotCompiledError'; + Object.setPrototypeOf(this, ContractNotCompiledError.prototype); + } +} diff --git a/packages/dev/README.md b/packages/dev/README.md new file mode 100644 index 00000000..60c8526c --- /dev/null +++ b/packages/dev/README.md @@ -0,0 +1,76 @@ +# @kuiralabs/midnight-dev + +Development for the Midnight CLI packages: `mn dev` (compile, deploy and test a dApp as its files change, on dev wallets), `mn test` (prepare, run and scaffold a dApp's test suites from its `dapp.test.json`) and `mn localnet` (a local network in Docker; `localnet up` is refused on this ledger-9 build). + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-dev@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-dev` | The localnet compose path and the errors these commands throw (`NoTestConfigError`, `LocalnetUnavailableError`, `PrepStepFailedError`) | +| `@kuiralabs/midnight-dev/commands` | `test`, `dev` and `localnet` as a registry entry (`devCommands`), its codes (`devCodes`) | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/dev/api-report.md). + +## What you call + +These are commands more than functions: mount them (below). `getComposePath` gives where a local network's compose file is written. + +## Codes + +Each error carries a `code`, and `classifyError(err, registry)` gives its code and exit code by that code alone, never by its message. These are the codes this package owns; the rest come from core and the packages below it, each listed in its README. + + +| Code | Exit | What went wrong | What to do | +|------|------|-----------------|------------| +| `LOCALNET_UNAVAILABLE` | 4 | `mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build. | Ask the user to start their ledger-9 stack and point mn at it (endpoint config). | +| `NO_TEST_CONFIG` | 1 | No dapp.test.json in the folder the test command ran in. | Ask the user to run it from the dApp's root, or create one with `mn test create`. | + + +## Mounting its commands + +The commands are definitions your program mounts in its own command line, with your state root, settings and notices (core's README explains each part). Its commands name codes the packages it builds on own, so the registry holds their entries too, as mn's does; a registry missing one is refused when it is built. Built on core's example, this one adds the dev commands, and connect's payer for `mn dev`'s deploys: + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; +import { walletCommands } from '@kuiralabs/midnight-wallet/commands'; +import { contractCommands } from '@kuiralabs/midnight-contract/commands'; +import { connectCommands } from '@kuiralabs/midnight-connect/commands'; +import { devCommands } from '@kuiralabs/midnight-dev/commands'; +import { servePayer } from '@kuiralabs/midnight-connect'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands, chainCommands, walletCommands, contractCommands, connectCommands, devCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output, payer: servePayer }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`node my-cli.mjs test list` in a dApp's folder lists its test suites; in a folder with no `dapp.test.json` it ends with `NO_TEST_CONFIG` and exit code 1. A test in mn runs the block above as it is written. diff --git a/packages/dev/api-report.md b/packages/dev/api-report.md index ca96dd38..4be46887 100644 --- a/packages/dev/api-report.md +++ b/packages/dev/api-report.md @@ -10,6 +10,10 @@ export declare class LocalnetUnavailableError extends Error { readonly code = "LOCALNET_UNAVAILABLE"; constructor(); } +export declare class NoTestConfigError extends Error { + readonly code = "NO_TEST_CONFIG"; + constructor(message: string); +} export declare class PrepStepFailedError extends Error { readonly code: string | undefined; constructor(step: PrepStepId, cause: unknown); @@ -26,10 +30,18 @@ export declare const devCodes: readonly [ readonly order: 160; readonly summary: "`mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build."; readonly recovery: "Ask the user to start their ledger-9 stack and point mn at it (endpoint config)."; + }, + { + readonly code: "NO_TEST_CONFIG"; + readonly exitCode: 1; + readonly order: 165; + readonly summary: "No dapp.test.json in the folder the test command ran in."; + readonly recovery: "Ask the user to run it from the dApp's root, or create one with `mn test create`."; } ]; export declare const devDefinition: CommandDefinition; export declare const devGuidance: PackageGuidance; +export declare const devCommands: CommandPackage; export declare const localnetDefinition: CommandDefinition; export declare const testDefinition: CommandDefinition; ``` diff --git a/packages/dev/src/commands.ts b/packages/dev/src/commands.ts index 36eea2a7..3e2a3ac6 100644 --- a/packages/dev/src/commands.ts +++ b/packages/dev/src/commands.ts @@ -4,5 +4,6 @@ export { devCodes } from './commands/dev.codes.ts'; export { devDefinition } from './commands/dev.definition.ts'; export { devGuidance } from './commands/dev.guidance.ts'; +export { devCommands } from './commands/dev.package.ts'; export { localnetDefinition } from './commands/localnet.definition.ts'; export { testDefinition } from './commands/test.definition.ts'; diff --git a/packages/dev/src/commands/dev.codes.ts b/packages/dev/src/commands/dev.codes.ts index 7fc4c884..b9d1e91b 100644 --- a/packages/dev/src/commands/dev.codes.ts +++ b/packages/dev/src/commands/dev.codes.ts @@ -1,7 +1,8 @@ // The error codes the dev package owns. -import { defineCodes, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core'; +import { defineCodes, EXIT_GENERAL_ERROR, EXIT_NETWORK_ERROR } from '@kuiralabs/midnight-cli-core'; export const devCodes = defineCodes([ { code: 'LOCALNET_UNAVAILABLE', exitCode: EXIT_NETWORK_ERROR, order: 160, summary: "`mn localnet up` (`midnight_localnet_up()`) can't start a ledger-9 stack on this build.", recovery: 'Ask the user to start their ledger-9 stack and point mn at it (endpoint config).' }, + { code: 'NO_TEST_CONFIG', exitCode: EXIT_GENERAL_ERROR, order: 165, summary: 'No dapp.test.json in the folder the test command ran in.', recovery: 'Ask the user to run it from the dApp\'s root, or create one with `mn test create`.' }, ]); diff --git a/packages/dev/src/commands/dev.definition.ts b/packages/dev/src/commands/dev.definition.ts index 5a7728cc..ec4a7827 100644 --- a/packages/dev/src/commands/dev.definition.ts +++ b/packages/dev/src/commands/dev.definition.ts @@ -31,6 +31,6 @@ export const devDefinition: CommandDefinition = { // It provisions wallets itself (airdrop, Dust registration), whose facades' WebSocket handles aren't reliably reclaimed. needsWalletSdk: true, shell: { payer: true }, - errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_NODE_RUNTIME', 'NO_PAYER'] }, + errors: { codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'CONTRACT_NOT_COMPILED', 'NO_NODE_RUNTIME', 'NO_PAYER'] }, load: () => import('./dev.ts'), }; diff --git a/packages/dev/src/commands/dev.package.ts b/packages/dev/src/commands/dev.package.ts new file mode 100644 index 00000000..484c14c4 --- /dev/null +++ b/packages/dev/src/commands/dev.package.ts @@ -0,0 +1,12 @@ +// The dev package's commands, as a program's registry installs them: +// createPackageRegistry([..., devCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { testDefinition } from './test.definition.ts'; +import { devDefinition } from './dev.definition.ts'; +import { localnetDefinition } from './localnet.definition.ts'; +import { devGuidance } from './dev.guidance.ts'; +import { devCodes } from './dev.codes.ts'; + +/** The dev package's commands, their agent guidance and codes, as one entry of a program's registry. */ +export const devCommands: CommandPackage = { name: 'dev', commands: [testDefinition, devDefinition, localnetDefinition], guidance: devGuidance, codes: devCodes }; diff --git a/packages/dev/src/commands/test.definition.ts b/packages/dev/src/commands/test.definition.ts index 3c12a60f..7c98af71 100644 --- a/packages/dev/src/commands/test.definition.ts +++ b/packages/dev/src/commands/test.definition.ts @@ -175,7 +175,7 @@ export const testDefinition: CommandDefinition = { needsWalletSdk: true, shell: {}, errors: { - codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'NO_NODE_RUNTIME'], + codes: [RESOLVES_NETWORK, OPENS_WALLET, LOADS_ENGINE, ENGINE_SYNC, PAYS, READS_OFFERS, READS_CHAIN, 'CHAIN_CLOCK_BEHIND', 'CONTRACT_NOT_COMPILED', 'NO_NODE_RUNTIME', 'NO_TEST_CONFIG'], // `test run` returns it when a test fails, with the results as its JSON (COMMAND_FAILED under MCP). outcomes: [{ exitCode: EXIT_GENERAL_ERROR, when: 'A test failed' }], }, diff --git a/packages/dev/src/index.ts b/packages/dev/src/index.ts index afba7411..4d527f21 100644 --- a/packages/dev/src/index.ts +++ b/packages/dev/src/index.ts @@ -6,4 +6,5 @@ // guidance are "./commands". export { getComposePath, LocalnetUnavailableError } from './lib/localnet.ts'; +export { NoTestConfigError } from './lib/test/discovery.ts'; export { PrepStepFailedError } from './lib/test/prep-runner.ts'; diff --git a/packages/dev/src/lib/test/discovery.ts b/packages/dev/src/lib/test/discovery.ts index b437be32..2a354c09 100644 --- a/packages/dev/src/lib/test/discovery.ts +++ b/packages/dev/src/lib/test/discovery.ts @@ -20,7 +20,7 @@ export function discoverDappConfig(dir?: string): { config: DappTestConfig; conf const configPath = join(dappDir, CONFIG_FILENAME); if (!existsSync(configPath)) { - throw new Error( + throw new NoTestConfigError( `No ${CONFIG_FILENAME} found in ${dappDir}\n` + `Run this command from the root of a dApp project, or create a ${CONFIG_FILENAME} file.` ); @@ -298,3 +298,13 @@ function validateActions(raw: unknown, path: string): TestActions { return { actions: obj.actions as TestActions['actions'] }; } + +/** No dapp.test.json in the folder a test command runs in. */ +export class NoTestConfigError extends Error { + readonly code = 'NO_TEST_CONFIG'; + constructor(message: string) { + super(message); + this.name = 'NoTestConfigError'; + Object.setPrototypeOf(this, NoTestConfigError.prototype); + } +} diff --git a/packages/engine-beta/README.md b/packages/engine-beta/README.md new file mode 100644 index 00000000..60782e82 --- /dev/null +++ b/packages/engine-beta/README.md @@ -0,0 +1,47 @@ +# @kuiralabs/midnight-engine-beta + +The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK beta split packages, ledger 9 rc.3, midnight-js 5 beta): everything the CLI packages do with that SDK set (wallets, the ledger, contracts, readers, the account package) behind core's engine interface. It runs stagenet. Only an engine imports the SDK; the other packages reach it through the engine your host loads. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-beta@next +``` + +Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). A layout with two copies is refused with `MIXED_SDK_LAYOUT`. A program that also uses the other networks (`@kuiralabs/midnight-engine-rc`) installs both; a process loads one of them. + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-engine-beta` | `createBetaEngine(host)`: the engine, for a host's `engineLoader` | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/engine-beta/api-report.md). + +## Codes + +This package owns no codes of its own. The SDK's errors are read once, here, and given core's codes (`PROOF_FAILURE`, `TX_REJECTED`, `STALE_UTXO` and the rest, in core's README), so a program never matches the SDK's messages. + +## Loading it + +A host loads an engine the first time a call needs one, by the SDK set of the call's network: `rc` for preprod, preview and a local network, `beta` for stagenet. A process runs one set; a call on a network of the other set fails with `OTHER_SDK_SET`, so a program that needs both runs two processes. + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { createHost } from '@kuiralabs/midnight-cli-core'; + +// One process runs one SDK set: the loader imports only the engine of the set asked for. +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + engineLoader: async (set, host) => set === 'rc' + ? (await import('@kuiralabs/midnight-engine-rc')).createRcEngine(host) + : (await import('@kuiralabs/midnight-engine-beta')).createBetaEngine(host), +}); + +const engine = await host.engines.for('stagenet'); +const seed = Buffer.from(process.env.WALLET_SEED, 'hex'); +console.log(engine.set, engine.keys.unshieldedAddress(seed, 'stagenet')); +``` + +With `WALLET_SEED` a seed in hex, it prints `beta` and the wallet's first address on stagenet (`mn_addr_stagenet1…`). A test in mn runs the block above as it is written. diff --git a/packages/engine-rc/README.md b/packages/engine-rc/README.md new file mode 100644 index 00000000..de2996af --- /dev/null +++ b/packages/engine-rc/README.md @@ -0,0 +1,47 @@ +# @kuiralabs/midnight-engine-rc + +The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, ledger 9 rc, midnight-js 5 rc): everything the CLI packages do with that SDK set (wallets, the ledger, contracts, readers, the account package) behind core's engine interface. It runs preprod, preview and a local network (`undeployed`). Only an engine imports the SDK; the other packages reach it through the engine your host loads. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-rc@next +``` + +Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). A layout with two copies is refused with `MIXED_SDK_LAYOUT`. A program that also uses stagenet (`@kuiralabs/midnight-engine-beta`) installs both; a process loads one of them. + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-engine-rc` | `createRcEngine(host)`: the engine, for a host's `engineLoader` | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/engine-rc/api-report.md). + +## Codes + +This package owns no codes of its own. The SDK's errors are read once, here, and given core's codes (`PROOF_FAILURE`, `TX_REJECTED`, `STALE_UTXO` and the rest, in core's README), so a program never matches the SDK's messages. + +## Loading it + +A host loads an engine the first time a call needs one, by the SDK set of the call's network: `rc` for preprod, preview and a local network, `beta` for stagenet. A process runs one set; a call on a network of the other set fails with `OTHER_SDK_SET`, so a program that needs both runs two processes. + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { createHost } from '@kuiralabs/midnight-cli-core'; + +// One process runs one SDK set: the loader imports only the engine of the set asked for. +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + engineLoader: async (set, host) => set === 'rc' + ? (await import('@kuiralabs/midnight-engine-rc')).createRcEngine(host) + : (await import('@kuiralabs/midnight-engine-beta')).createBetaEngine(host), +}); + +const engine = await host.engines.for('undeployed'); +const seed = Buffer.from(process.env.WALLET_SEED, 'hex'); +console.log(engine.set, engine.keys.unshieldedAddress(seed, 'undeployed')); +``` + +With `WALLET_SEED` a seed in hex, it prints `rc` and the wallet's first address on undeployed (`mn_addr_undeployed1…`). A test in mn runs the block above as it is written. diff --git a/packages/grant/README.md b/packages/grant/README.md new file mode 100644 index 00000000..46495dfd --- /dev/null +++ b/packages/grant/README.md @@ -0,0 +1,77 @@ +# @kuiralabs/midnight-grant + +Grants for the Midnight CLI packages: `mn grant`, the wallet owner's side of an account (`@kuiralabs/midnight-account-chain`) and the grants that let an agent spend from it, its owner devices and backups; and the protector `wallet protect` seals the accounts' records with. The account package runs through the loaded engine, so the same commands work on each engine's networks. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-wallet@next @kuiralabs/midnight-grant@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-grant` | `accountProtector`, the account records, and the errors grant throws | +| `@kuiralabs/midnight-grant/commands` | `grant` as a registry entry (`grantCommands`), its codes (`grantCodes`) | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/grant/api-report.md). + +## What you call + +- `accountProtector`: pass it as a protector so `wallet protect` also seals the accounts' records. +- `accountRecordsDir`, `accountArtifactsDir`: where an account's records and its contract's keys are kept under your state root. + +## Codes + +Each error carries a `code`, and `classifyError(err, registry)` gives its code and exit code by that code alone, never by its message. These are the codes this package owns; the rest come from core and the packages below it, each listed in its README. + + +| Code | Exit | What went wrong | What to do | +|------|------|-----------------|------------| +| `NO_ACCOUNT` | 1 | A grant command (`midnight_grant_*` tool) was called for a wallet that has no account on this network. | Offer `midnight_grant_deploy()`, after telling the user how its owner key is kept (see the allowance flow). | +| `CALLER_PIN_UNSUPPORTED` | 2 | A grant request pins the contract that calls the account, and the account on this network (stagenet) has no caller pin; nothing was submitted. | Tell the user; ask the agent for a grant request that names no calling contract, or issue it on undeployed. | + + +## Mounting its commands + +The commands are definitions your program mounts in its own command line, with your state root, settings and notices (core's README explains each part). Its commands name codes the packages it builds on own, so the registry holds their entries too, as mn's does; a registry missing one is refused when it is built. Built on core's example, this one adds `grant` beside the wallet's commands, connect's payer for the account's transactions, and the protector `wallet protect` seals the accounts with: + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; +import { walletCommands } from '@kuiralabs/midnight-wallet/commands'; +import { contractCommands } from '@kuiralabs/midnight-contract/commands'; +import { grantCommands } from '@kuiralabs/midnight-grant/commands'; +import { accountProtector } from '@kuiralabs/midnight-grant'; +import { servePayer } from '@kuiralabs/midnight-connect'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands, chainCommands, walletCommands, contractCommands, grantCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output, payer: servePayer, protectors: [accountProtector] }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`node my-cli.mjs grant list --wallet alice --network preview` lists alice's grants; for a wallet with no account on that network it ends with `NO_ACCOUNT` and exit code 1. A test in mn runs the block above as it is written. diff --git a/packages/grant/api-report.md b/packages/grant/api-report.md index 9ba6d928..30e0b106 100644 --- a/packages/grant/api-report.md +++ b/packages/grant/api-report.md @@ -46,4 +46,5 @@ export declare const grantCodes: readonly [ ]; export declare const grantDefinition: CommandDefinition; export declare const grantGuidance: PackageGuidance; +export declare const grantCommands: CommandPackage; ``` diff --git a/packages/grant/src/commands.ts b/packages/grant/src/commands.ts index 4b6049d6..011aad09 100644 --- a/packages/grant/src/commands.ts +++ b/packages/grant/src/commands.ts @@ -4,3 +4,4 @@ export { grantCodes } from './commands/grant.codes.ts'; export { grantDefinition } from './commands/grant.definition.ts'; export { grantGuidance } from './commands/grant.guidance.ts'; +export { grantCommands } from './commands/grant.package.ts'; diff --git a/packages/grant/src/commands/grant.package.ts b/packages/grant/src/commands/grant.package.ts new file mode 100644 index 00000000..960e8b8c --- /dev/null +++ b/packages/grant/src/commands/grant.package.ts @@ -0,0 +1,10 @@ +// The grant package's commands, as a program's registry installs them: +// createPackageRegistry([..., grantCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { grantDefinition } from './grant.definition.ts'; +import { grantGuidance } from './grant.guidance.ts'; +import { grantCodes } from './grant.codes.ts'; + +/** The grant package's commands, their agent guidance and codes, as one entry of a program's registry. */ +export const grantCommands: CommandPackage = { name: 'grant', commands: [grantDefinition], guidance: grantGuidance, codes: grantCodes }; diff --git a/packages/wallet/README.md b/packages/wallet/README.md new file mode 100644 index 00000000..98e9decc --- /dev/null +++ b/packages/wallet/README.md @@ -0,0 +1,76 @@ +# @kuiralabs/midnight-wallet + +Wallets for the Midnight CLI packages: mn's passphrase and sealed wallet files, seeds and addresses, balances, NIGHT transfers and airdrops, Dust registration, and swap offers. Wallet files live under the state root your host gives, never in `~/.midnight` unless that is the root you give. + +## Install + +```sh +npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-wallet@next @kuiralabs/midnight-engine-rc@next +``` + +Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). + +## Entry points + +| Import | What it holds | +|---|---| +| `@kuiralabs/midnight-wallet` | The functions below, the wallet protector type, and the errors they throw | +| `@kuiralabs/midnight-wallet/commands` | `wallet`, `generate`, `info`, `balance`, `address`, `genesis-address`, `airdrop`, `transfer`, `dust` and `cache` as one registry entry (`walletCommands`), `swap` as another (`swapCommands`), the wallet's codes (`walletCodes`) | + +Every export and its signature is in [api-report.md](https://github.com/kuiralabs/midnight-cli/blob/main/packages/wallet/api-report.md). + +## What you call + +- `createWallet`, `listWallets`, `setActiveWallet`, `unlockWallet`, `walletAddress`: wallet files under your state root. +- `readWalletBalance`, `readAddressBalance`: balances, as bigints in each token's smallest unit. +- `transferNight`, `airdropNight`: send NIGHT, shielded or not; `airdropNight` on a local network. +- `registerDust`, `readDustStatus`, `exportDustSnapshot`: Dust for fees. +- `makeSwapOffer`, `inspectSwapOffer`, `takeSwapOffer`, `cancelSwapOffer`, `listSwapOffers`: swap offers, each paid through a payer you pass. +- `establishPassphrase`, `unlockPassphrase`, `checkPassphrase`: mn's passphrase, asked through your host's prompter or read from `MN_PASSPHRASE`. + +## Codes + +Each error carries a `code`, and `classifyError(err, registry)` gives its code and exit code by that code alone, never by its message. These are the codes this package owns; the rest come from core and the packages below it, each listed in its README. + + +| Code | Exit | What went wrong | What to do | +|------|------|-----------------|------------| +| `WALLET_NOT_FOUND` | 3 | Named wallet doesn't exist on disk. | `midnight_wallet_list()` — user may have removed it. | + + +## Mounting its commands + +The commands are definitions your program mounts in its own command line, with your state root, settings and notices (core's README explains each part). Its commands name codes the packages it builds on own, so the registry holds their entries too, as mn's does; a registry missing one is refused when it is built. Built on core's example, this one adds the wallet's commands. `swap` pays through a payer: add `swapCommands` and pass `payer: servePayer` from `@kuiralabs/midnight-connect` in the run: + +```js +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { classifyError, createHost, createPackageRegistry, parseArgs, runCommand, settingsFromEnvironment, UsageError } from '@kuiralabs/midnight-cli-core'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; +import { walletCommands } from '@kuiralabs/midnight-wallet/commands'; +import { createRcEngine } from '@kuiralabs/midnight-engine-rc'; + +const registry = createPackageRegistry([coreCommands, chainCommands, walletCommands], []); +const host = createHost({ + paths: { stateRoot: join(homedir(), '.my-app'), home: homedir() }, + settings: () => settingsFromEnvironment(process.env), + notice: (line) => console.error(line), + engineLoader: async (_set, host) => createRcEngine(host), +}); +const output = { result: (data) => console.log(JSON.stringify(data)), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }; + +const args = parseArgs(process.argv.slice(2)); +try { + const definition = registry.find(args.command ?? ''); + if (definition === undefined) throw new UsageError(`Unknown command: ${args.command}`); + const outcome = await runCommand(definition, args, { host, output }); + process.exitCode = outcome?.exitCode ?? 0; +} catch (err) { + const { errorCode, exitCode } = classifyError(err, registry); + console.error(`${errorCode}: ${err.message}`); + process.exitCode = exitCode; +} +``` + +`MN_PASSPHRASE=… node my-cli.mjs wallet generate alice` writes `~/.my-app/wallets/alice.json`; `node my-cli.mjs wallet info bob` for a wallet that doesn't exist ends with `WALLET_NOT_FOUND` and exit code 3. A test in mn runs the block above as it is written. diff --git a/packages/wallet/api-report.md b/packages/wallet/api-report.md index 1c2a1828..1ca80a2c 100644 --- a/packages/wallet/api-report.md +++ b/packages/wallet/api-report.md @@ -366,6 +366,7 @@ export declare const genesisAddressDefinition: CommandDefinition; export declare const infoDefinition: CommandDefinition; export declare const swapDefinition: CommandDefinition; export declare const swapGuidance: PackageGuidance; +export declare const swapCommands: CommandPackage; export declare const transferDefinition: CommandDefinition; export declare const OPENS_WALLET: import("@kuiralabs/midnight-cli-core").CodeSet; export declare const walletCodes: readonly [ @@ -379,5 +380,6 @@ export declare const walletCodes: readonly [ ]; export declare const walletDefinition: CommandDefinition; export declare const walletGuidance: PackageGuidance; +export declare const walletCommands: CommandPackage; export declare function showPaidStep(reporter: SpinnerReporter, event: ProgressEvent | StepFailed): void; ``` diff --git a/packages/wallet/src/commands.ts b/packages/wallet/src/commands.ts index f8dc42d1..82a0bea2 100644 --- a/packages/wallet/src/commands.ts +++ b/packages/wallet/src/commands.ts @@ -15,8 +15,10 @@ export { genesisAddressDefinition } from './commands/genesis-address.definition. export { infoDefinition } from './commands/info.definition.ts'; export { swapDefinition } from './commands/swap.definition.ts'; export { swapGuidance } from './commands/swap.guidance.ts'; +export { swapCommands } from './commands/swap.package.ts'; export { transferDefinition } from './commands/transfer.definition.ts'; export { OPENS_WALLET, walletCodes } from './commands/wallet.codes.ts'; export { walletDefinition } from './commands/wallet.definition.ts'; export { walletGuidance } from './commands/wallet.guidance.ts'; +export { walletCommands } from './commands/wallet.package.ts'; export { showPaidStep } from './lib/wallet/paid-call.ts'; diff --git a/packages/wallet/src/commands/swap.package.ts b/packages/wallet/src/commands/swap.package.ts new file mode 100644 index 00000000..d63df4eb --- /dev/null +++ b/packages/wallet/src/commands/swap.package.ts @@ -0,0 +1,9 @@ +// The swap command, as a program's registry installs it beside the wallet's: +// createPackageRegistry([..., walletCommands, swapCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { swapDefinition } from './swap.definition.ts'; +import { swapGuidance } from './swap.guidance.ts'; + +/** The swap command and its agent guidance, as one entry of a program's registry; its codes are the wallet's. */ +export const swapCommands: CommandPackage = { name: 'swap', commands: [swapDefinition], guidance: swapGuidance }; diff --git a/packages/wallet/src/commands/wallet.package.ts b/packages/wallet/src/commands/wallet.package.ts new file mode 100644 index 00000000..83416fcd --- /dev/null +++ b/packages/wallet/src/commands/wallet.package.ts @@ -0,0 +1,19 @@ +// The wallet package's commands, as a program's registry installs them: +// createPackageRegistry([..., walletCommands, ...]). + +import type { CommandPackage } from '@kuiralabs/midnight-cli-core'; +import { walletDefinition } from './wallet.definition.ts'; +import { generateDefinition } from './generate.definition.ts'; +import { infoDefinition } from './info.definition.ts'; +import { balanceDefinition } from './balance.definition.ts'; +import { addressDefinition } from './address.definition.ts'; +import { genesisAddressDefinition } from './genesis-address.definition.ts'; +import { airdropDefinition } from './airdrop.definition.ts'; +import { transferDefinition } from './transfer.definition.ts'; +import { dustDefinition } from './dust.definition.ts'; +import { cacheDefinition } from './cache.definition.ts'; +import { walletGuidance } from './wallet.guidance.ts'; +import { walletCodes } from './wallet.codes.ts'; + +/** The wallet package's commands, their agent guidance and codes, as one entry of a program's registry. */ +export const walletCommands: CommandPackage = { name: 'wallet', commands: [walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition], guidance: walletGuidance, codes: walletCodes }; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index b1bfb239..e7c65889 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -69,8 +69,8 @@ const HOMES = [ ['mcp', /^mcp-server\.ts$/], ['mcp', /^lib\/mcp\//], - // A package's agent guidance (.guidance.ts) and its error codes (.codes.ts) sit beside its commands. - ...PACKAGES.map((pkg) => [pkg, new RegExp(`^commands/${pkg}\\.(guidance|codes)\\.ts$`)]), + // A package's agent guidance (.guidance.ts), its error codes (.codes.ts) and its registry entry (.package.ts) sit beside its commands. + ...PACKAGES.map((pkg) => [pkg, new RegExp(`^commands/${pkg}\\.(guidance|codes|package)\\.ts$`)]), // A command's definition (.definition.ts) lives in its command's package. ['core', /^commands\/config(\.definition)?\.ts$/], @@ -92,7 +92,7 @@ const HOMES = [ ['wallet', /^lib\/wallet\//], ['wallet', /^ui\/receipt\.ts$/], // Swap is the wallet's: its offers are made, taken and cancelled by a wallet. - ['wallet', /^commands\/swap(\.definition|\.guidance)?\.ts$/], + ['wallet', /^commands\/swap(\.definition|\.guidance|\.package)?\.ts$/], ['wallet', /^lib\/swap\//], ['contract', /^commands\/(contract|inspect-cost)(\.definition)?\.ts$/], diff --git a/scripts/write-package-readmes.ts b/scripts/write-package-readmes.ts new file mode 100644 index 00000000..813bd8bb --- /dev/null +++ b/scripts/write-package-readmes.ts @@ -0,0 +1,18 @@ +// Writes each public package's table of codes into its README, between its +// markers, from the package's code definitions. A test fails when a README +// differs. +// +// Usage: npm run package-readmes + +import { readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { PACKAGE_CODES, withPackageCodeTable } from '../src/lib/package-readmes.ts'; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +for (const [dir, codes] of Object.entries(PACKAGE_CODES)) { + const path = join(ROOT, 'packages', dir, 'README.md'); + writeFileSync(path, withPackageCodeTable(readFileSync(path, 'utf8'), dir, codes)); + process.stdout.write(`wrote packages/${dir}/README.md\n`); +} diff --git a/src/__tests__/command-flags.test.ts b/src/__tests__/command-flags.test.ts index 09068783..57d85a74 100644 --- a/src/__tests__/command-flags.test.ts +++ b/src/__tests__/command-flags.test.ts @@ -134,10 +134,10 @@ describe('the accepted flags match the code', () => { // A command's definition (.definition.ts) sits beside it and is not a // command, nor is a package's agent guidance (.guidance.ts) or its - // error codes (.codes.ts). + // error codes (.codes.ts) or its registry entry (.package.ts). // Commands sit in commands/ under src/ or a workspace package. const commandPaths = new Map(sourceFiles() - .filter((f) => /\/commands\/[^/]+\.ts$/.test(f) && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts') && !f.endsWith('.codes.ts')) + .filter((f) => /\/commands\/[^/]+\.ts$/.test(f) && !f.endsWith('.definition.ts') && !f.endsWith('.guidance.ts') && !f.endsWith('.codes.ts') && !f.endsWith('.package.ts')) .map((f) => [basename(f), f])); const commandFiles = [...commandPaths.keys()]; diff --git a/src/__tests__/error-code-parity.test.ts b/src/__tests__/error-code-parity.test.ts index befdd215..28f8c7ca 100644 --- a/src/__tests__/error-code-parity.test.ts +++ b/src/__tests__/error-code-parity.test.ts @@ -10,7 +10,8 @@ // unreachable indexer, node or proof server as NETWORK_ERROR, whatever their // messages say; and (Y54) a ZK proof that timed out as PROOF_TIMEOUT, and a // contract run's transaction the node refused as TX_REJECTED whatever its -// reason's words. A test checks that every row that changed says so. +// reason's words; and (Y64) no compiled contract as CONTRACT_NOT_COMPILED and +// no dapp.test.json as NO_TEST_CONFIG. A test checks that every row that changed says so. import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; @@ -33,6 +34,8 @@ import * as ledger from '@midnightntwrk/ledger-v9'; import { readPassphrase, assertWalletFileExists, assertWalletRemovable, setActiveWallet, walletSecretFrom, assertWalletCanPay, NoSuchOfferError } from '@kuiralabs/midnight-wallet'; import { walletDefinition, generateDefinition, addressDefinition, airdropDefinition, balanceDefinition } from '@kuiralabs/midnight-wallet/commands'; import { LocalnetUnavailableError, PrepStepFailedError } from '@kuiralabs/midnight-dev'; +import { testDefinition } from '@kuiralabs/midnight-dev/commands'; +import { findContractInfo } from '@kuiralabs/midnight-contract'; import { loadInstalledEngine } from '../lib/installed-engines.ts'; import { cliCall } from './helpers/cli-call.ts'; import { saveWalletConfig } from '../../test-support/plain-wallet.ts'; @@ -214,6 +217,9 @@ const ROWS: Row[] = [ ['no account', () => { throw new NoAccountError('alice', 'undeployed'); }, as('NO_ACCOUNT', 1), as('NO_ACCOUNT', 1)], ['no state root (approved: was UNKNOWN)', () => createHost().paths(), as('UNKNOWN', 1), as('NO_STATE_ROOT', 1)], ['no payer (approved: was UNKNOWN)', () => payerFor('transfer', undefined), as('UNKNOWN', 1), as('NO_PAYER', 1)], + // (Y64) Found mounting the commands in a program: both read as UNKNOWN. + ['no compiled contract (approved: was UNKNOWN)', () => findContractInfo(root), as('UNKNOWN', 1), as('CONTRACT_NOT_COMPILED', 1)], + ['no dapp.test.json where mn test runs (approved: was UNKNOWN)', async () => cliCall((await testDefinition.load()).default, parseArgs(['test', 'list', '--json'])), as('UNKNOWN', 1), as('NO_TEST_CONFIG', 1)], // Without the registry its code came from its result's text: here, words that read as a network error. ['a failed command (approved: was by its text)', () => { throw new CommandFailedError('test run', 1, { overall: 'fail', error: 'network error' }); }, as('NETWORK_ERROR', 4), as('COMMAND_FAILED', 1)], ['an error no rule knows', () => { throw new Error('Something unexpected happened'); }, as('UNKNOWN', 1), as('UNKNOWN', 1)], diff --git a/src/__tests__/help.test.ts b/src/__tests__/help.test.ts index 908f3888..87443bc0 100644 --- a/src/__tests__/help.test.ts +++ b/src/__tests__/help.test.ts @@ -210,7 +210,9 @@ describe('help — the lists come from the registry', () => { io = captureOutput(); await cliCall(helpCommand, parseArgs(['help', 'test'])); expect(io.stdout()).toContain([ + ' NO_TEST_CONFIG 1 No dapp.test.json in the folder the test command ran in.', ' NO_NODE_RUNTIME 1 Contract scripts run under Node.js, and none was found on PATH.', + ' CONTRACT_NOT_COMPILED 1 No compiled contract was found where the command looked (managed//compiler/contract-info.json).', ' (no error) 1 A test failed', ' Also: the network, wallet, engine, sync, paying, offers and chain codes, and INVALID_ARGS, CANCELLED, UNKNOWN, UNSUPPORTED_NODE, NO_STATE_ROOT (mn manual lists them all).', ].join('\n')); diff --git a/src/__tests__/package-readmes.test.ts b/src/__tests__/package-readmes.test.ts new file mode 100644 index 00000000..4aa4bf2a --- /dev/null +++ b/src/__tests__/package-readmes.test.ts @@ -0,0 +1,149 @@ +// The public packages' READMEs: each has its sections, its table of codes as +// the package's code definitions give it, and a mounting (or, for an engine, +// loading) example that runs as it is written: copied into a program of its +// own, in a child process with the packages resolved as an install beside it +// would, a home of the test's own and no network. Each run is checked for +// what its README says it does, typed errors included. + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { PUBLIC_PACKAGES } from '../../scripts/api-report.mjs'; +import { PACKAGE_CODES, README_CODES_END, README_CODES_START, withPackageCodeTable } from '../lib/package-readmes.ts'; +import { closedPort } from '../../test-support/closed-port.ts'; + +const ROOT = resolve(import.meta.dirname, '..', '..'); +const readme = (dir: string): string => readFileSync(join(ROOT, 'packages', dir, 'README.md'), 'utf8'); +const ENGINES = ['engine-rc', 'engine-beta']; + +/** The first js block under the heading `heading`. */ +function blockUnder(text: string, heading: string): string { + const at = text.indexOf(`\n${heading}\n`); + if (at === -1) throw new Error(`no "${heading}" section`); + const block = /```js\n([\s\S]*?)```/.exec(text.slice(at)); + if (block === null) throw new Error(`no js block under "${heading}"`); + return block[1]!; +} + +const exampleOf = (dir: string): string => blockUnder(readme(dir), dir === 'cli-core' ? '## Mounting commands in your program' : ENGINES.includes(dir) ? '## Loading it' : '## Mounting its commands'); + +describe('each public package\'s README', () => { + it.each(PUBLIC_PACKAGES)('%s has its sections and links its API report', (dir) => { + const text = readme(dir); + const name = JSON.parse(readFileSync(join(ROOT, 'packages', dir, 'package.json'), 'utf8')).name as string; + expect(text.startsWith(`# ${name}\n`)).toBe(true); + for (const heading of ['## Install', '## Entry points', '## Codes']) expect(text, heading).toContain(`\n${heading}\n`); + expect(text).toContain(`packages/${dir}/api-report.md`); + expect(exampleOf(dir).length).toBeGreaterThan(0); + }); + + it.each(PUBLIC_PACKAGES)('%s lists the codes it owns as its code definitions give them (npm run package-readmes)', (dir) => { + const text = readme(dir); + const codes = PACKAGE_CODES[dir]; + if (codes === undefined) { + expect(text).not.toContain(README_CODES_START); + return; + } + expect(text).toBe(withPackageCodeTable(text, dir, codes)); + for (const { code } of codes) expect(text).toContain(`| \`${code}\` |`); + expect(text.indexOf(README_CODES_END)).toBeGreaterThan(text.indexOf(README_CODES_START)); + }); +}); + +describe('each README\'s example, run as it is written', () => { + let dir: string; + let home: string; + let closed: number; + + beforeAll(async () => { + dir = realpathSync(mkdtempSync(join(tmpdir(), 'mn-package-readmes-'))); + home = join(dir, 'home'); + mkdirSync(home); + // The packages resolve as they would installed beside the program. + symlinkSync(join(ROOT, 'node_modules'), join(dir, 'node_modules')); + closed = await closedPort(); + }); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + /** Runs the package's example with `argv` from `cwd` (the test's folder by default). */ + function run(pkg: string, argv: string[], cwd = dir): Promise<{ code: number | null; stdout: string; stderr: string }> { + const program = join(dir, `${pkg}.mjs`); + writeFileSync(program, exampleOf(pkg)); + return new Promise((done) => { + const child = spawn(process.execPath, ['--conditions=midnight-cli-source', '--import', 'tsx', program, ...argv], { + cwd, + env: { ...process.env, HOME: home, MN_PASSPHRASE: 'readme example passphrase', MN_NO_LOCAL_DETECT: '1', NO_COLOR: '1', WALLET_SEED: '07'.repeat(32) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + const hung = setTimeout(() => child.kill('SIGKILL'), 90_000); + child.on('exit', (code) => { clearTimeout(hung); done({ code, stdout, stderr }); }); + }); + } + const lastJson = (stdout: string): Record => JSON.parse(stdout.trim().split('\n').at(-1)!) as Record; + + it('core: config set and get, under the program\'s own state root', async () => { + expect((await run('cli-core', ['config', 'set', 'network', 'preview'])).code).toBe(0); + const got = await run('cli-core', ['config', 'get', 'network', '--json']); + expect(got.code).toBe(0); + expect(lastJson(got.stdout)).toMatchObject({ key: 'network', value: 'preview' }); + expect(existsSync(join(home, '.my-app', 'config.json'))).toBe(true); + expect(existsSync(join(home, '.midnight'))).toBe(false); + }, 120_000); + + it('wallet: generates a wallet in the program\'s state root, and a missing one is WALLET_NOT_FOUND, exit 3', async () => { + const made = await run('wallet', ['wallet', 'generate', 'alice', '--json']); + expect(made.code, made.stderr).toBe(0); + expect(lastJson(made.stdout)).toMatchObject({ name: 'alice' }); + expect(existsSync(join(home, '.my-app', 'wallets', 'alice.json'))).toBe(true); + const missing = await run('wallet', ['wallet', 'info', 'bob', '--json']); + expect(missing.code).toBe(3); + expect(missing.stderr.startsWith('WALLET_NOT_FOUND: ')).toBe(true); + }, 120_000); + + it('chain: tx status against an indexer that doesn\'t answer is NETWORK_ERROR, exit 4', async () => { + const result = await run('chain', ['tx', 'status', 'ab'.repeat(32), '--network', 'undeployed', '--indexer-ws', `ws://127.0.0.1:${closed}/api/v4/graphql/ws`, '--json']); + expect(result.code).toBe(4); + expect(result.stderr.startsWith('NETWORK_ERROR: ')).toBe(true); + }, 120_000); + + it('contract: inspect where nothing is compiled is CONTRACT_NOT_COMPILED, exit 1', async () => { + const empty = join(dir, 'no-contract'); + mkdirSync(empty, { recursive: true }); + const result = await run('contract', ['contract', 'inspect', '--path', empty, '--json']); + expect(result.code).toBe(1); + expect(result.stderr.startsWith('CONTRACT_NOT_COMPILED: ')).toBe(true); + }, 120_000); + + it('connect: serve for a wallet that doesn\'t exist is WALLET_NOT_FOUND, exit 3', async () => { + const result = await run('connect', ['serve', '--wallet', 'nobody', '--network', 'undeployed', '--json']); + expect(result.code).toBe(3); + expect(result.stderr.startsWith('WALLET_NOT_FOUND: ')).toBe(true); + }, 120_000); + + it('dev: test list in a folder with no dapp.test.json is NO_TEST_CONFIG, exit 1', async () => { + const result = await run('dev', ['test', 'list', '--json']); + expect(result.code).toBe(1); + expect(result.stderr.startsWith('NO_TEST_CONFIG: ')).toBe(true); + }, 120_000); + + it('grant: grant list for a wallet with no account is NO_ACCOUNT, exit 1', async () => { + // alice, from the wallet example: the same state root. + const result = await run('grant', ['grant', 'list', '--wallet', 'alice', '--network', 'undeployed', '--json']); + expect(result.code).toBe(1); + expect(result.stderr.startsWith('NO_ACCOUNT: ')).toBe(true); + }, 120_000); + + it.each([['engine-rc', 'rc', 'mn_addr_undeployed1'], ['engine-beta', 'beta', 'mn_addr_stagenet1']])('%s: loads its engine by the network\'s set and derives the address', async (pkg, set, prefix) => { + const result = await run(pkg, []); + expect(result.code, result.stderr).toBe(0); + const [printedSet, address] = result.stdout.trim().split(' '); + expect(printedSet).toBe(set); + expect(address!.startsWith(prefix)).toBe(true); + }, 120_000); +}); diff --git a/src/lib/installed-commands.ts b/src/lib/installed-commands.ts index 58d47f39..6b35a61d 100644 --- a/src/lib/installed-commands.ts +++ b/src/lib/installed-commands.ts @@ -7,13 +7,13 @@ // server's classification of an error by its code. import { getValidNetworkNames, createPackageRegistry, type FlagDefinition, type GlobalFlagHelp } from '@kuiralabs/midnight-cli-core'; -import { configDefinition, coreGuidance, coreCodes } from '@kuiralabs/midnight-cli-core/commands'; -import { walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition, swapDefinition, walletGuidance, swapGuidance, walletCodes } from '@kuiralabs/midnight-wallet/commands'; -import { inspectCostDefinition, contractDefinition, contractGuidance, contractCodes } from '@kuiralabs/midnight-contract/commands'; -import { serveDefinition, connectGuidance } from '@kuiralabs/midnight-connect/commands'; -import { testDefinition, devDefinition, localnetDefinition, devGuidance, devCodes } from '@kuiralabs/midnight-dev/commands'; -import { grantDefinition, grantGuidance, grantCodes } from '@kuiralabs/midnight-grant/commands'; -import { statusDefinition, txDefinition, chainGuidance, chainCodes } from '@kuiralabs/midnight-chain/commands'; +import { coreCommands } from '@kuiralabs/midnight-cli-core/commands'; +import { walletCommands, swapCommands } from '@kuiralabs/midnight-wallet/commands'; +import { contractCommands } from '@kuiralabs/midnight-contract/commands'; +import { connectCommands } from '@kuiralabs/midnight-connect/commands'; +import { devCommands } from '@kuiralabs/midnight-dev/commands'; +import { grantCommands } from '@kuiralabs/midnight-grant/commands'; +import { chainCommands } from '@kuiralabs/midnight-chain/commands'; import { helpDefinition } from '../commands/help.definition.ts'; import { manualDefinition } from '../commands/manual.definition.ts'; @@ -43,18 +43,13 @@ const GLOBAL_FLAGS_HELP: readonly GlobalFlagHelp[] = [ /** Every package, in the layering's order; the shell's own commands last, its guidance being the skeletons. */ export const installedCommands = createPackageRegistry([ - { name: 'core', commands: [configDefinition], guidance: coreGuidance, codes: coreCodes }, - { name: 'chain', commands: [statusDefinition, txDefinition], guidance: chainGuidance, codes: chainCodes }, - { - name: 'wallet', - commands: [walletDefinition, generateDefinition, infoDefinition, balanceDefinition, addressDefinition, genesisAddressDefinition, airdropDefinition, transferDefinition, dustDefinition, cacheDefinition], - guidance: walletGuidance, - codes: walletCodes, - }, - { name: 'contract', commands: [inspectCostDefinition, contractDefinition], guidance: contractGuidance, codes: contractCodes }, - { name: 'connect', commands: [serveDefinition], guidance: connectGuidance }, - { name: 'swap', commands: [swapDefinition], guidance: swapGuidance }, - { name: 'dev', commands: [testDefinition, devDefinition, localnetDefinition], guidance: devGuidance, codes: devCodes }, - { name: 'grant', commands: [grantDefinition], guidance: grantGuidance, codes: grantCodes }, + coreCommands, + chainCommands, + walletCommands, + contractCommands, + connectCommands, + swapCommands, + devCommands, + grantCommands, { name: 'shell', commands: [helpDefinition, manualDefinition], guidance: { pieces: [] } }, ], GLOBAL_FLAGS, GLOBAL_FLAGS_HELP); diff --git a/src/lib/package-readmes.ts b/src/lib/package-readmes.ts new file mode 100644 index 00000000..f814c122 --- /dev/null +++ b/src/lib/package-readmes.ts @@ -0,0 +1,40 @@ +// The public packages' READMEs: each package's table of the error codes it +// owns, from its code definitions, between the README's markers. +// scripts/write-package-readmes.ts writes them; a test fails when a README +// differs, and runs each README's mounting example as it is written. + +import type { CodeDefinition } from '@kuiralabs/midnight-cli-core'; +import { coreCodes } from '@kuiralabs/midnight-cli-core/commands'; +import { chainCodes } from '@kuiralabs/midnight-chain/commands'; +import { walletCodes } from '@kuiralabs/midnight-wallet/commands'; +import { contractCodes } from '@kuiralabs/midnight-contract/commands'; +import { devCodes } from '@kuiralabs/midnight-dev/commands'; +import { grantCodes } from '@kuiralabs/midnight-grant/commands'; +import { withGeneratedBlock } from './readme-commands.ts'; + +/** The markers around a package README's table of codes. */ +export const README_CODES_START = ''; +export const README_CODES_END = ''; + +/** The codes each public package owns, by its folder under packages/; a package that owns none is absent. */ +export const PACKAGE_CODES: Readonly> = { + 'cli-core': coreCodes, + chain: chainCodes, + wallet: walletCodes, + contract: contractCodes, + dev: devCodes, + grant: grantCodes, +}; + +/** The table of `codes`, in their tables' order, as markdown ending with a newline. */ +export function packageCodeTable(codes: readonly CodeDefinition[]): string { + const cell = (text: string): string => text.replaceAll('|', '\\|').replaceAll('\n', ' '); + const ordered = [...codes].sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.code.localeCompare(b.code)); + const rows = ordered.map((c) => `| \`${c.code}\` | ${c.exitCode} | ${cell(c.summary)} | ${cell(c.recovery ?? '')} |`); + return ['| Code | Exit | What went wrong | What to do |', '|------|------|-----------------|------------|', ...rows].join('\n') + '\n'; +} + +/** The README `readme` (of the package in `dir`) with its table of codes written between its markers. */ +export function withPackageCodeTable(readme: string, dir: string, codes: readonly CodeDefinition[]): string { + return withGeneratedBlock(readme, `packages/${dir}/README.md`, README_CODES_START, README_CODES_END, packageCodeTable(codes)); +} From 0c59ebd965bc2d9962630387aceb7eb4dada90f6 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 15:31:24 -0800 Subject: [PATCH 81/88] A command's spinners draw through its call's output (3H, part 3) Found by the consumer project: a mounted command run without --json drew its spinners on the process's stderr, whatever output the program gave runCommand. createProgress and start now take where to draw, and a call's progress draws through the call's output.stderr. mn's shell output is the process's stderr, so mn draws the same bytes (snapshot unchanged). The regression test in core's run-command tests fails without the fix. --- .../src/__tests__/run-command.test.ts | 16 ++++++++ packages/cli-core/src/lib/call-context.ts | 3 +- packages/cli-core/src/ui/spinner.ts | 37 +++++++++++-------- 3 files changed, 39 insertions(+), 17 deletions(-) diff --git a/packages/cli-core/src/__tests__/run-command.test.ts b/packages/cli-core/src/__tests__/run-command.test.ts index b1fd479a..0ae59024 100644 --- a/packages/cli-core/src/__tests__/run-command.test.ts +++ b/packages/cli-core/src/__tests__/run-command.test.ts @@ -127,6 +127,22 @@ describe('runCommand', () => { expect(loaded).toStrictEqual([]); }); + // Regression: a command's spinners drew on the process's stderr, so a program mounting the commands got them on its + // terminal whatever output it gave. + it('draws the command\'s spinners through the run\'s output, never on the process\'s stderr', async () => { + const drawn: string[] = []; + const written: string[] = []; + const original = process.stderr.write.bind(process.stderr); + process.stderr.write = ((chunk: string | Uint8Array) => { written.push(String(chunk)); return true; }) as typeof process.stderr.write; + try { + await runCommand(definitionOf(async (_args, ctx) => { ctx.progress.start('Syncing...').stop('Synced'); }), noArgs(), { host: testHost(), output: { ...output, stderr: (text) => { drawn.push(text); } } }); + } finally { + process.stderr.write = original; + } + expect(drawn.join('')).toContain('Synced'); + expect(written.join('')).not.toContain('Synced'); + }); + it('sends what the command\'s spinners say to onProgress', async () => { const said: string[] = []; await runCommand(definitionOf(async (_args, ctx) => { ctx.progress.start('Syncing...').stop('Synced'); }), noArgs(), { host: testHost(), output, onProgress: (m) => said.push(m) }); diff --git a/packages/cli-core/src/lib/call-context.ts b/packages/cli-core/src/lib/call-context.ts index 053aa21b..b87c2ad3 100644 --- a/packages/cli-core/src/lib/call-context.ts +++ b/packages/cli-core/src/lib/call-context.ts @@ -135,7 +135,8 @@ export function createCallContext(parts: CallParts parts.output.stderr(text)), diagnostics: callDiagnostics(isVerbose(parts.args), parts.host.notice), sdkWarnings: parts.sdkWarnings ?? createSdkWarningRouter().openCall().warnings, config: { settings: parts.host.settings(), paths: parts.host.paths() }, diff --git a/packages/cli-core/src/ui/spinner.ts b/packages/cli-core/src/ui/spinner.ts index 48b46379..49dee622 100644 --- a/packages/cli-core/src/ui/spinner.ts +++ b/packages/cli-core/src/ui/spinner.ts @@ -46,13 +46,13 @@ export interface Progress { } /** The progress of one call, whose spinners say what they say to `report` too. */ -export function createProgress(report: ProgressReport = reportNowhere): Progress { +export function createProgress(report: ProgressReport = reportNowhere, write: TerminalWrite = writeStderr): Progress { let active: Spinner | null = null; return { start(message) { const spinner = start(message, report, (ended) => { if (active === ended) active = null; - }); + }, write); active = spinner; return spinner; }, @@ -106,11 +106,16 @@ function stripAnsi(str: string): string { return str.replace(/\x1b\[[0-9;]*m/g, ''); } +/** Where a spinner draws: a call's stderr, or the process's for a spinner outside any call. */ +export type TerminalWrite = (text: string) => void; + +const writeStderr: TerminalWrite = (text) => { process.stderr.write(text); }; + /** - * Starts a spinner on the terminal (stderr) saying `message`; what it says + * Starts a spinner on the terminal (`write`, stderr by default) saying `message`; what it says * goes to `report` too. `onEnd` hears when it stops, fails or clears. */ -export function start(message: string, report: ProgressReport = reportNowhere, onEnd: (spinner: Spinner) => void = () => {}): Spinner { +export function start(message: string, report: ProgressReport = reportNowhere, onEnd: (spinner: Spinner) => void = () => {}, write: TerminalWrite = writeStderr): Spinner { let stopped = false; const say = (said: string | undefined): void => { if (said !== undefined) report(said); @@ -119,36 +124,36 @@ export function start(message: string, report: ProgressReport = reportNowhere, o if (!isColorEnabled()) { let currentMessage = message; - process.stderr.write(`⠋ ${currentMessage}`); + write(`⠋ ${currentMessage}`); const spinner: Spinner = { update(msg: string) { currentMessage = msg; say(msg); - process.stderr.write(`\r⠋ ${currentMessage}\x1b[K`); + write(`\r⠋ ${currentMessage}\x1b[K`); }, stop(finalMessage?: string) { if (stopped) return; stopped = true; onEnd(spinner); say(finalMessage); - process.stderr.write(`\r✓ ${finalMessage ?? currentMessage}\x1b[K\n`); + write(`\r✓ ${finalMessage ?? currentMessage}\x1b[K\n`); }, fail(finalMessage?: string) { if (stopped) return; stopped = true; onEnd(spinner); - process.stderr.write(`\r✗ ${finalMessage ?? currentMessage}\x1b[K\n`); + write(`\r✗ ${finalMessage ?? currentMessage}\x1b[K\n`); }, log(line: string) { say(line); - process.stderr.write(`\r\x1b[K${line}\n`); - process.stderr.write(`⠋ ${currentMessage}`); + write(`\r\x1b[K${line}\n`); + write(`⠋ ${currentMessage}`); }, clear() { if (stopped) return; stopped = true; onEnd(spinner); - process.stderr.write('\r\x1b[K'); + write('\r\x1b[K'); }, }; return spinner; @@ -168,7 +173,7 @@ export function start(message: string, report: ProgressReport = reportNowhere, o const plain = stripAnsi(text); text = plain.slice(0, maxVisible); } - process.stderr.write(`\r${frame} ${text}\x1b[K`); + write(`\r${frame} ${text}\x1b[K`); frameIndex = (frameIndex + 1) % BRAILLE_FRAMES.length; }; @@ -187,7 +192,7 @@ export function start(message: string, report: ProgressReport = reportNowhere, o onEnd(spinner); say(finalMessage); const final = finalMessage ?? currentMessage; - process.stderr.write(`\r\x1b[32m✓\x1b[0m ${final}\x1b[K\n`); + write(`\r\x1b[32m✓\x1b[0m ${final}\x1b[K\n`); }, fail(finalMessage?: string) { if (stopped) return; @@ -195,11 +200,11 @@ export function start(message: string, report: ProgressReport = reportNowhere, o clearInterval(timer); onEnd(spinner); const final = finalMessage ?? currentMessage; - process.stderr.write(`\r\x1b[31m✗\x1b[0m ${final}\x1b[K\n`); + write(`\r\x1b[31m✗\x1b[0m ${final}\x1b[K\n`); }, log(line: string) { say(line); - process.stderr.write(`\r\x1b[K${line}\n`); + write(`\r\x1b[K${line}\n`); render(); }, clear() { @@ -207,7 +212,7 @@ export function start(message: string, report: ProgressReport = reportNowhere, o stopped = true; clearInterval(timer); onEnd(spinner); - process.stderr.write('\r\x1b[K'); + write('\r\x1b[K'); }, }; From 37ad93f0359a77077a289e597427cd2efe972ca3 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 15:55:12 -0800 Subject: [PATCH 82/88] Engines find the script's packages under bun (3H, part 4) Found by the consumer project: on bun, a contract deploy from a program failed because the Node-run script couldn't import ws. bun answers require.resolve('ws') with its own module, not a file, so the engine linked no ws into the dApp. packageFolder (both engines) now looks in the node_modules folders above the engine when the runtime answers with something that isn't a file, which is where Node's resolution finds it. The bun regression test fails without the fix. Node is unchanged. --- packages/engine-beta/src/contract-scripts.ts | 31 +++++++++++++------ .../src/__tests__/contract-scripts.test.ts | 18 ++++++++++- packages/engine-rc/src/contract-scripts.ts | 31 +++++++++++++------ 3 files changed, 61 insertions(+), 19 deletions(-) diff --git a/packages/engine-beta/src/contract-scripts.ts b/packages/engine-beta/src/contract-scripts.ts index c91b6985..ccab38d4 100644 --- a/packages/engine-beta/src/contract-scripts.ts +++ b/packages/engine-beta/src/contract-scripts.ts @@ -5,7 +5,7 @@ // where the witnesses may be) comes from the runner as ScriptParts. import { existsSync, readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { dirname, isAbsolute, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/engine'; @@ -32,21 +32,25 @@ export const SCRIPT_PACKAGES = [ 'ws', ] as const; -/** The folder of the installed package `name`, as mn resolves it; null when it isn't installed. */ -export function packageFolder(name: string): string | null { +/** + * The folder of the installed package `name`, as mn resolves it from `from` + * (this engine's module); null when it isn't installed. + */ +export function packageFolder(name: string, from: string = import.meta.url): string | null { // node:module's createRequire works in every host (Node, the test runner, // the bundle); a package exported to `import` only is found through - // import.meta.resolve where the host has it. - let entry: string; + // import.meta.resolve where the host has it. bun answers some names (ws) + // with a module of its own, not a file: those are looked up in the + // node_modules folders above this module, where the script finds them too. + let entry: string | undefined; try { - entry = createRequire(import.meta.url).resolve(name); + entry = createRequire(from).resolve(name); } catch { try { entry = fileURLToPath(import.meta.resolve(name)); - } catch { - return null; - } + } catch { /* not resolvable here: looked up below */ } } + if (entry === undefined || !isAbsolute(entry)) return installedFolder(name, dirname(fileURLToPath(from))); for (let dir = dirname(entry); ; dir = dirname(dir)) { const manifest = join(dir, 'package.json'); if (existsSync(manifest)) { @@ -58,6 +62,15 @@ export function packageFolder(name: string): string | null { } } +/** The package `name` in the nearest node_modules above `dir` that holds it, as Node's resolution walks; null when none does. */ +function installedFolder(name: string, dir: string): string | null { + for (let at = dir; ; at = dirname(at)) { + const folder = join(at, 'node_modules', name); + if (existsSync(join(folder, 'package.json'))) return folder; + if (dirname(at) === at) return null; + } +} + /** * SDK imports used by walletProviderCode and providerSetupCode. Kept out of * those fragments so a test can evaluate a fragment with the same bindings. diff --git a/packages/engine-rc/src/__tests__/contract-scripts.test.ts b/packages/engine-rc/src/__tests__/contract-scripts.test.ts index 31c67880..c4598943 100644 --- a/packages/engine-rc/src/__tests__/contract-scripts.test.ts +++ b/packages/engine-rc/src/__tests__/contract-scripts.test.ts @@ -7,7 +7,9 @@ import { describe, it, expect, beforeAll, afterEach } from 'vitest'; import type { NetworkConfig } from '@kuiralabs/midnight-cli-core'; import type { ScriptParts } from '@kuiralabs/midnight-cli-core/engine'; -import { mkdtempSync, rmSync } from 'node:fs'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import * as ledger from '@midnightntwrk/ledger-v9'; @@ -224,3 +226,17 @@ describe('generated scripts', () => { expect(scripts.call).toContain(PROVIDER_IMPORTS); }); }); + +// Regression: under bun, require.resolve('ws') answers with bun's own ws, not a +// file, so the engine found no folder for it and the contract script (run under +// Node) could not import it: a deploy from a program on bun failed. +describe('packageFolder on bun', () => { + const bunInstalled = spawnSync('bun', ['--version'], { encoding: 'utf8' }).status === 0; + it.skipIf(!bunInstalled)('finds the installed ws, a folder holding its package.json, where bun answers with its own', () => { + const source = fileURLToPath(new URL('../contract-scripts.ts', import.meta.url)); + const found = spawnSync('bun', ['--conditions=midnight-cli-source', '-e', `const { packageFolder } = await import(${JSON.stringify(source)}); console.log(packageFolder('ws'));`], { encoding: 'utf8' }); + const folder = found.stdout.trim(); + expect(folder, found.stderr).toMatch(/node_modules\/ws$/); + expect(existsSync(join(folder, 'package.json'))).toBe(true); + }); +}); diff --git a/packages/engine-rc/src/contract-scripts.ts b/packages/engine-rc/src/contract-scripts.ts index b1b64cc0..7779c520 100644 --- a/packages/engine-rc/src/contract-scripts.ts +++ b/packages/engine-rc/src/contract-scripts.ts @@ -5,7 +5,7 @@ // where the witnesses may be) comes from the runner as ScriptParts. import { existsSync, readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { dirname, isAbsolute, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createRequire } from 'node:module'; import type { CallScript, DeployScript, ScriptParts, StateScript } from '@kuiralabs/midnight-cli-core/engine'; @@ -32,21 +32,25 @@ export const SCRIPT_PACKAGES = [ 'ws', ] as const; -/** The folder of the installed package `name`, as mn resolves it; null when it isn't installed. */ -export function packageFolder(name: string): string | null { +/** + * The folder of the installed package `name`, as mn resolves it from `from` + * (this engine's module); null when it isn't installed. + */ +export function packageFolder(name: string, from: string = import.meta.url): string | null { // node:module's createRequire works in every host (Node, the test runner, // the bundle); a package exported to `import` only is found through - // import.meta.resolve where the host has it. - let entry: string; + // import.meta.resolve where the host has it. bun answers some names (ws) + // with a module of its own, not a file: those are looked up in the + // node_modules folders above this module, where the script finds them too. + let entry: string | undefined; try { - entry = createRequire(import.meta.url).resolve(name); + entry = createRequire(from).resolve(name); } catch { try { entry = fileURLToPath(import.meta.resolve(name)); - } catch { - return null; - } + } catch { /* not resolvable here: looked up below */ } } + if (entry === undefined || !isAbsolute(entry)) return installedFolder(name, dirname(fileURLToPath(from))); for (let dir = dirname(entry); ; dir = dirname(dir)) { const manifest = join(dir, 'package.json'); if (existsSync(manifest)) { @@ -58,6 +62,15 @@ export function packageFolder(name: string): string | null { } } +/** The package `name` in the nearest node_modules above `dir` that holds it, as Node's resolution walks; null when none does. */ +function installedFolder(name: string, dir: string): string | null { + for (let at = dir; ; at = dirname(at)) { + const folder = join(at, 'node_modules', name); + if (existsSync(join(folder, 'package.json'))) return folder; + if (dirname(at) === at) return null; + } +} + /** * SDK imports used by walletProviderCode and providerSetupCode. Kept out of * those fragments so a test can evaluate a fragment with the same bindings. From e98c4de7da972e751a15ce12853b2b28f5c4da6b Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 16:51:30 -0800 Subject: [PATCH 83/88] Pin account-chain 0.3.0-rc.3 and account 0.2.0-rc.1 (Y64) Both engines pin @kuiralabs/midnight-account-chain 0.3.0-rc.3 (batched inbox appends: one transaction for up to four entries), and grant pins @kuiralabs/midnight-account 0.2.0-rc.1, the version rc.3 depends on, so one copy is installed. The beta engine's nested copy is restored in the lockfile and the tree, as before (npm dedupes it away). An account deployed with rc.2 has the older contract; rc.3 needs a new one. Suite 3060, beta 195. The only snapshot change is contract inspect of the account contract itself, which lists rc.3's circuits. --- package-lock.json | 28 ++++++++++++++-------------- packages/engine-beta/package.json | 2 +- packages/engine-rc/package.json | 2 +- packages/grant/package.json | 2 +- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/package-lock.json b/package-lock.json index c6216d8f..12d1b534 100644 --- a/package-lock.json +++ b/package-lock.json @@ -605,9 +605,9 @@ } }, "node_modules/@kuiralabs/midnight-account": { - "version": "0.2.0-rc.0", - "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account/-/midnight-account-0.2.0-rc.0.tgz", - "integrity": "sha512-OgTQoh8QU7FYsc1SpdL8JZ36N86Lp+O53c7SZzNscQCGiOx8pU8a1TYWjk5GHlR1MSlEvg92yinXqO3Q7DSBiw==", + "version": "0.2.0-rc.1", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account/-/midnight-account-0.2.0-rc.1.tgz", + "integrity": "sha512-rioDrd6cSglnwZ6TMPzBqr3VUazax4+JKqmMTBlF9YdSFXiYssJkncr2Q1hYkYgUwEYYXZpSol6pkGeYlYdixw==", "license": "Apache-2.0", "dependencies": { "@noble/ciphers": "2.4.0", @@ -620,12 +620,12 @@ } }, "node_modules/@kuiralabs/midnight-account-chain": { - "version": "0.3.0-rc.2", - "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.2.tgz", - "integrity": "sha512-Cu4G3p0g4JcEOCZtM6JwMsugqwtJmzaFz4HFB1//lOJjqYoqd1XYyNwUryLX1SvusPx9OjxQZvqCgDxcY66jDQ==", + "version": "0.3.0-rc.3", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.3.tgz", + "integrity": "sha512-2q1ocSUfjmflLcLnZ9rEWOq861VE1/GYUkyEjpvFmnP9SeRjctGBlRELUMKmlskuP4hjzH4F6DsQZtPJhOz6Dg==", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@kuiralabs/midnight-account": "0.2.0-rc.1", "@scure/base": "2.0.0" }, "engines": { @@ -5820,7 +5820,7 @@ "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", "@kuiralabs/midnight-chain": "0.1.0-rc.2", "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", @@ -5868,12 +5868,12 @@ } }, "packages/engine-beta/node_modules/@kuiralabs/midnight-account-chain": { - "version": "0.3.0-rc.2", - "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.2.tgz", - "integrity": "sha512-Cu4G3p0g4JcEOCZtM6JwMsugqwtJmzaFz4HFB1//lOJjqYoqd1XYyNwUryLX1SvusPx9OjxQZvqCgDxcY66jDQ==", + "version": "0.3.0-rc.3", + "resolved": "https://registry.npmjs.org/@kuiralabs/midnight-account-chain/-/midnight-account-chain-0.3.0-rc.3.tgz", + "integrity": "sha512-2q1ocSUfjmflLcLnZ9rEWOq861VE1/GYUkyEjpvFmnP9SeRjctGBlRELUMKmlskuP4hjzH4F6DsQZtPJhOz6Dg==", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@kuiralabs/midnight-account": "0.2.0-rc.1", "@scure/base": "2.0.0" }, "engines": { @@ -6328,7 +6328,7 @@ "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", "@kuiralabs/midnight-chain": "0.1.0-rc.2", "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", @@ -6359,7 +6359,7 @@ "version": "0.1.0-rc.2", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@kuiralabs/midnight-account": "0.2.0-rc.1", "@kuiralabs/midnight-chain": "0.1.0-rc.2", "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@kuiralabs/midnight-contract": "0.1.0-rc.2", diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index db5b9172..af469680 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -31,7 +31,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", "@kuiralabs/midnight-chain": "0.1.0-rc.2", "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index ce302930..ba663375 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -31,7 +31,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-account-chain": "0.3.0-rc.2", + "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", "@kuiralabs/midnight-chain": "0.1.0-rc.2", "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", diff --git a/packages/grant/package.json b/packages/grant/package.json index b26139b7..81c4ccd0 100644 --- a/packages/grant/package.json +++ b/packages/grant/package.json @@ -36,7 +36,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-account": "0.2.0-rc.0", + "@kuiralabs/midnight-account": "0.2.0-rc.1", "@kuiralabs/midnight-chain": "0.1.0-rc.2", "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", "@kuiralabs/midnight-contract": "0.1.0-rc.2", From 1b59a9c408a25c7dda011bb027e0d616dc381825 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 19:18:41 -0800 Subject: [PATCH 84/88] Engines refuse a tree bun installed, before any SDK loads (3J) Y65 (option B): install with npm, run with Node or bun. bun's installer ignores each engine's npm-shrinkwrap.json and resolves the ranges again; its peer resolution differs too (graphql-tag shares graphql 17). The SDK then fails as it loads, intermittently, before the engine's ledger-copy check runs. - core's shippedTreeDrift / assertInstalledAsShipped walks the engine's dependency graph. Each dependency is resolved as Node resolves it from where its requirer sits and compared with the shrinkwrap's version. A tree npm nests (a program) or hoists (mn's own install) passes, and one resolved again fails with NotInstalledAsShippedError (MIXED_SDK_LAYOUT): the first drift, why, and the npm command. A checkout ships no shrinkwrap and is not checked. - Each engine's entry (index.ts) runs it, then loads the engine (-engine.ts). code-reach follows the assembler there. - MIXED_SDK_LAYOUT's summary now says what it covers. The READMEs say bun runs what npm installed. Measured on the spike's trees: npm (nested) 0 drift, mn's global install (hoisted) 0, bun installs 36 to 78. Suite 3066, beta 195. --- README.md | 2 +- docs/JSON_CONTRACT.md | 2 +- docs/SKILL.md | 2 +- packages/cli-core/README.md | 4 +- packages/cli-core/api-report.md | 15 ++- .../cli-core/src/__tests__/sdk-layout.test.ts | 77 +++++++++++- packages/cli-core/src/commands/core.codes.ts | 2 +- packages/cli-core/src/engine.ts | 2 +- packages/cli-core/src/lib/sdk-layout.ts | 92 ++++++++++++++ packages/engine-beta/README.md | 2 +- packages/engine-beta/api-report.md | 2 +- packages/engine-beta/src/beta-engine.ts | 113 +++++++++++++++++ packages/engine-beta/src/index.ts | 118 ++---------------- packages/engine-rc/README.md | 2 +- packages/engine-rc/api-report.md | 2 +- packages/engine-rc/src/index.ts | 115 ++--------------- packages/engine-rc/src/rc-engine.ts | 112 +++++++++++++++++ scripts/code-reach.mjs | 6 +- src/__tests__/declared-codes.test.ts | 6 +- 19 files changed, 449 insertions(+), 227 deletions(-) create mode 100644 packages/engine-beta/src/beta-engine.ts create mode 100644 packages/engine-rc/src/rc-engine.ts diff --git a/README.md b/README.md index 8deab96f..bf7b227a 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ npm install -g midnight-wallet-cli@next # this ledger-9 prerelease This installs two commands: `midnight` (or `mn` for short) and `midnight-wallet-mcp`. -Install the prerelease with npm (or run it with `npx`). It ships an `npm-shrinkwrap.json` that keeps each SDK set's packages apart; bun's installer ignores it, and a command whose SDK set it then mixes up is refused, saying so (`MIXED_SDK_LAYOUT`; under bun today, every stagenet command). +Install the prerelease with npm (or run it with `npx`). Each engine ships an `npm-shrinkwrap.json` that pins the SDK set it was tested with; bun's installer ignores it and resolves the packages again, so an engine bun installed is refused before any SDK loads, saying so (`MIXED_SDK_LAYOUT`). bun can run what npm installed. ## Commands diff --git a/docs/JSON_CONTRACT.md b/docs/JSON_CONTRACT.md index 58de66a9..a6617fe6 100644 --- a/docs/JSON_CONTRACT.md +++ b/docs/JSON_CONTRACT.md @@ -126,7 +126,7 @@ Stable identifiers used in error messages and structured error objects, with the | `BLOCKFROST_LIMIT_REACHED` | 4 | Blockfrost's plan limit or rate limit. | | `ENDPOINT_SHUT_DOWN` | 4 | An endpoint set by flag or config was shut down by its operator (the old preprod indexer). | | `OTHER_SDK_SET` | 1 | The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet). | -| `MIXED_SDK_LAYOUT` | 1 | mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger. | +| `MIXED_SDK_LAYOUT` | 1 | mn's packages were installed without each engine's shrinkwrap (bun's installer): an engine's SDK tree isn't the one it was tested with. | | `NO_STATE_ROOT` | 1 | The host gave mn no place to keep its state (a program's `createHost` without paths). | | `NO_PAYER` | 1 | A command that submits a transaction was called without a payer. | | `COMMAND_FAILED` | 1 | A command ended with a non-zero exit code without throwing (an MCP test run whose tests failed); the message carries its result. | diff --git a/docs/SKILL.md b/docs/SKILL.md index b3eaa2a6..c131e6da 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -174,7 +174,7 @@ Every MCP tool error returns `{ error: true, code: , message: (operations: T): export declare function toEngineError(err: unknown): unknown; export declare function withDustShortfall(error: E, shortfall: DustShortfall): E; export declare function withEngineCode(err: unknown): unknown; +export declare function assertInstalledAsShipped(engine: string, engineDir: string): void; export declare function assertOneSdkCopy(engine: string, engineDir: string, packages: readonly string[], wasmPackages: readonly string[]): void; export declare class MixedSdkLayoutError extends Error { readonly code = "MIXED_SDK_LAYOUT"; constructor(engine: string, wasmPackage: string, copies: string[]); } +export declare class NotInstalledAsShippedError extends Error { + readonly code = "MIXED_SDK_LAYOUT"; + readonly drift: readonly TreeDrift[]; + constructor(engine: string, drift: readonly TreeDrift[]); +} export declare function resolvedPackageFolder(from: string, name: string): string | null; +export declare function shippedTreeDrift(engineDir: string): TreeDrift[] | null; +export interface TreeDrift { + readonly from: string; + readonly name: string; + readonly found: string | null; + readonly shipped: string; +} export declare function decodeSignPayload(data: string, encoding: string): Uint8Array; export declare function signedMessageBytes(payload: Uint8Array): Uint8Array; export declare function describeLeg(leg: SwapLeg): string; diff --git a/packages/cli-core/src/__tests__/sdk-layout.test.ts b/packages/cli-core/src/__tests__/sdk-layout.test.ts index bc12f770..7084b3f2 100644 --- a/packages/cli-core/src/__tests__/sdk-layout.test.ts +++ b/packages/cli-core/src/__tests__/sdk-layout.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { MixedSdkLayoutError, assertOneSdkCopy } from '../lib/sdk-layout.ts'; +import { MixedSdkLayoutError, NotInstalledAsShippedError, assertInstalledAsShipped, assertOneSdkCopy, shippedTreeDrift } from '../lib/sdk-layout.ts'; let dir: string; beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mn-sdk-layout-')); }); @@ -47,3 +47,78 @@ describe('an engine\'s SDK layout', () => { expect(() => assertOneSdkCopy('the test engine', engine, ['utils'], ['ledger'])).not.toThrow(); }); }); + +// Whether an engine is installed as the tree its npm-shrinkwrap.json describes: npm nests or hoists that tree and +// passes; an installer that resolves the ranges again (bun's) fails before any SDK module loads. +describe('an engine installed as shipped', () => { + /** A package `name`@`version` at `at`, with `dependencies` (name to range). */ + const at = (dir: string, name: string, version: string, dependencies: Record = {}): string => { + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version, dependencies })); + return dir; + }; + // The engine's shrinkwrap: it needs a@1.0.0 and b@2.0.0; a needs b@^1, which the shrinkwrap nests under a. + const SHRINKWRAP = { + packages: { + '': { name: 'engine', version: '0.1.0', dependencies: { a: '1.0.0', b: '2.0.0' } }, + 'node_modules/a': { version: '1.0.0', dependencies: { b: '^1.0.0' } }, + 'node_modules/a/node_modules/b': { version: '1.4.0' }, + 'node_modules/b': { version: '2.0.0' }, + 'node_modules/dev-only': { version: '9.0.0', dev: true }, + }, + }; + const engineAt = (dir: string): string => { + const engine = at(dir, 'engine', '0.1.0', { a: '1.0.0', b: '2.0.0' }); + fs.writeFileSync(path.join(engine, 'npm-shrinkwrap.json'), JSON.stringify(SHRINKWRAP)); + return engine; + }; + + it('is not checked where the engine ships no shrinkwrap (a workspace checkout)', () => { + const engine = at(path.join(dir, 'node_modules', 'engine'), 'engine', '0.1.0', { a: '1.0.0' }); + expect(shippedTreeDrift(engine)).toBeNull(); + expect(() => assertInstalledAsShipped('the test engine', engine)).not.toThrow(); + }); + + it('passes the tree as npm installs a dependency\'s shrinkwrap: nested under the engine', () => { + const engine = engineAt(path.join(dir, 'node_modules', 'engine')); + at(path.join(engine, 'node_modules', 'a'), 'a', '1.0.0', { b: '^1.0.0' }); + at(path.join(engine, 'node_modules', 'a', 'node_modules', 'b'), 'b', '1.4.0'); + at(path.join(engine, 'node_modules', 'b'), 'b', '2.0.0'); + expect(shippedTreeDrift(engine)).toEqual([]); + }); + + it('passes the same tree hoisted, as npm lays it out under a package that ships its own shrinkwrap (mn)', () => { + const engine = engineAt(path.join(dir, 'node_modules', 'engine')); + at(path.join(dir, 'node_modules', 'a'), 'a', '1.0.0', { b: '^1.0.0' }); + at(path.join(dir, 'node_modules', 'a', 'node_modules', 'b'), 'b', '1.4.0'); + at(path.join(dir, 'node_modules', 'b'), 'b', '2.0.0'); + expect(shippedTreeDrift(engine)).toEqual([]); + }); + + it('finds a dependency resolved again to another version, and refuses with MIXED_SDK_LAYOUT, naming npm', () => { + const engine = engineAt(path.join(dir, 'node_modules', 'engine')); + at(path.join(dir, 'node_modules', 'a'), 'a', '1.0.0', { b: '^1.0.0' }); + at(path.join(dir, 'node_modules', 'a', 'node_modules', 'b'), 'b', '1.4.0'); + at(path.join(dir, 'node_modules', 'b'), 'b', '2.1.0'); + expect(shippedTreeDrift(engine)).toEqual([{ from: '.', name: 'b', found: '2.1.0', shipped: '2.0.0' }]); + const refusal = (() => { try { assertInstalledAsShipped('the test engine', engine); } catch (error) { return error; } })(); + expect(refusal).toBeInstanceOf(NotInstalledAsShippedError); + expect((refusal as NotInstalledAsShippedError).code).toBe('MIXED_SDK_LAYOUT'); + expect((refusal as Error).message).toContain('the test engine isn\'t installed as it was tested: 1 of its dependencies'); + expect((refusal as Error).message).toContain('Install with npm'); + }); + + // As bun's installer leaves graphql-tag: sharing the top-level graphql instead of the one nested for it. + it('finds a package that shares a top-level copy where the shrinkwrap nests its own', () => { + const engine = engineAt(path.join(dir, 'node_modules', 'engine')); + at(path.join(dir, 'node_modules', 'a'), 'a', '1.0.0', { b: '^1.0.0' }); + at(path.join(dir, 'node_modules', 'b'), 'b', '2.0.0'); + expect(shippedTreeDrift(engine)).toEqual([{ from: 'node_modules/a', name: 'b', found: '2.0.0', shipped: '1.4.0' }]); + }); + + it('finds a dependency that is missing', () => { + const engine = engineAt(path.join(dir, 'node_modules', 'engine')); + at(path.join(dir, 'node_modules', 'b'), 'b', '2.0.0'); + expect(shippedTreeDrift(engine)).toEqual([{ from: '.', name: 'a', found: null, shipped: '1.0.0' }]); + }); +}); diff --git a/packages/cli-core/src/commands/core.codes.ts b/packages/cli-core/src/commands/core.codes.ts index 92ecc710..b94362c4 100644 --- a/packages/cli-core/src/commands/core.codes.ts +++ b/packages/cli-core/src/commands/core.codes.ts @@ -29,7 +29,7 @@ export const coreCodes = defineCodes([ { code: 'ENDPOINT_SHUT_DOWN', exitCode: EXIT_NETWORK_ERROR, order: 270, summary: 'An endpoint set by flag or config was shut down by its operator (the old preprod indexer).', recovery: '`midnight_config_unset({ key: "indexer-ws" })` (and `node` if set), then retry.' }, { code: 'CANCELLED', exitCode: EXIT_CANCELLED, order: 370, summary: 'Operation was aborted (SIGINT, or the MCP call was cancelled).', recovery: "A transaction already submitted may still have landed: read the state first (`midnight_grant_status`, `midnight_balance`). Don't retry without confirming with the user." }, { code: 'OTHER_SDK_SET', exitCode: EXIT_GENERAL_ERROR, order: 280, summary: "The process runs one SDK set's engine and the network runs on the other (an MCP server that served rc asked for stagenet).", recovery: 'Make the call in a process of its own: ask the user to start an MCP server for that network.' }, - { code: 'MIXED_SDK_LAYOUT', exitCode: EXIT_GENERAL_ERROR, order: 290, summary: "mn was installed without its shrinkwrap (bun's installer): an engine's SDK packages reach more than one copy of its ledger.", recovery: 'Ask the user to install mn with npm.' }, + { code: 'MIXED_SDK_LAYOUT', exitCode: EXIT_GENERAL_ERROR, order: 290, summary: "mn's packages were installed without each engine's shrinkwrap (bun's installer): an engine's SDK tree isn't the one it was tested with.", recovery: 'Ask the user to install mn with npm.' }, { code: 'UNSUPPORTED_NODE', exitCode: EXIT_GENERAL_ERROR, order: 190, summary: 'Node.js is older than 22 (22.18 for mn grant).', recovery: 'Ask the user to install a current Node.js.' }, { code: 'NO_STATE_ROOT', exitCode: EXIT_GENERAL_ERROR, order: 300, summary: "The host gave mn no place to keep its state (a program's `createHost` without paths).", recovery: "Give the host its paths (`createHost({ paths })`)." }, { code: 'NO_PAYER', exitCode: EXIT_GENERAL_ERROR, order: 310, summary: 'A command that submits a transaction was called without a payer.', recovery: 'Give the call a payer.' }, diff --git a/packages/cli-core/src/engine.ts b/packages/cli-core/src/engine.ts index b9741849..0892f770 100644 --- a/packages/cli-core/src/engine.ts +++ b/packages/cli-core/src/engine.ts @@ -37,7 +37,7 @@ export { isSdkInsufficientFundsError, markingEngineCodes, refusalCodeOf, reportingEngineErrors, toEngineError, withDustShortfall, withEngineCode } from './lib/sdk-errors.ts'; -export { assertOneSdkCopy, MixedSdkLayoutError, resolvedPackageFolder } from './lib/sdk-layout.ts'; +export { assertInstalledAsShipped, assertOneSdkCopy, MixedSdkLayoutError, NotInstalledAsShippedError, resolvedPackageFolder, shippedTreeDrift, type TreeDrift } from './lib/sdk-layout.ts'; export { decodeSignPayload, signedMessageBytes } from './lib/sign-data.ts'; export { describeLeg, NotAnOfferError } from './lib/swap-offer.ts'; export { fromHex, toHex } from './lib/tx-serde.ts'; diff --git a/packages/cli-core/src/lib/sdk-layout.ts b/packages/cli-core/src/lib/sdk-layout.ts index d7dfa543..677b79bf 100644 --- a/packages/cli-core/src/lib/sdk-layout.ts +++ b/packages/cli-core/src/lib/sdk-layout.ts @@ -59,3 +59,95 @@ function dependsOn(packageDir: string, name: string): boolean { return false; } } + +/** One dependency that resolves to another version than the engine's shrinkwrap gives it. */ +export interface TreeDrift { + /** The package that depends on it, as the shrinkwrap names its place ('.' for the engine). */ + readonly from: string; + readonly name: string; + /** The version Node resolves from where `from` sits, or null when it finds none. */ + readonly found: string | null; + readonly shipped: string; +} + +/** An engine's installed tree isn't the one its shrinkwrap describes: an installer resolved its ranges again. */ +export class NotInstalledAsShippedError extends Error { + readonly code = 'MIXED_SDK_LAYOUT'; + readonly drift: readonly TreeDrift[]; + constructor(engine: string, drift: readonly TreeDrift[]) { + const first = drift[0]!; + super( + `${engine} isn't installed as it was tested: ${drift.length} of its dependencies resolve to other versions than the npm-shrinkwrap.json it ships ` + + `(${first.name} ${first.found ?? 'missing'} where ${first.shipped} was tested, for ${first.from}), so it could fail in ways nobody has seen. ` + + 'This happens with an installer that ignores the shrinkwrap, such as bun\'s. ' + + 'Install with npm (npm install -g midnight-wallet-cli for mn, or npm install for a program); bun can run what npm installed.', + ); + this.name = 'NotInstalledAsShippedError'; + this.drift = drift; + } +} + +interface ShrinkwrapEntry { + readonly version?: string; + readonly optional?: boolean; + readonly dev?: boolean; + readonly dependencies?: Record; + readonly optionalDependencies?: Record; +} + +/** + * The dependencies of the engine at `engineDir` that resolve to other versions + * than its shipped `npm-shrinkwrap.json` gives them; null when it ships none + * (a workspace checkout). The dependency graph is walked from the engine: each + * dependency is resolved as Node resolves it, from where the package that + * needs it really sits, and compared with the version the shrinkwrap places + * for that package. So a tree npm nests and one it hoists both pass, and one + * an installer built from the ranges again fails. + */ +export function shippedTreeDrift(engineDir: string): TreeDrift[] | null { + const shrinkwrap = join(engineDir, 'npm-shrinkwrap.json'); + if (!existsSync(shrinkwrap)) return null; + const entries = (JSON.parse(readFileSync(shrinkwrap, 'utf-8')) as { packages?: Record }).packages ?? {}; + // Where the shrinkwrap places `name` for the package at `key`: the nearest node_modules above it that holds it. + const placed = (key: string, name: string): string | undefined => { + for (let at = key; ; ) { + const candidate = `${at === '' ? '' : `${at}/`}node_modules/${name}`; + if (entries[candidate] !== undefined) return candidate; + if (at === '') return undefined; + const parent = at.lastIndexOf('/node_modules/'); + at = parent < 0 ? '' : at.slice(0, parent); + } + }; + const versionAt = (dir: string): string | null => { + try { return (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')) as { version?: string }).version ?? null; } catch { return null; } + }; + const drift: TreeDrift[] = []; + const seen = new Set(); + const todo: [key: string, dir: string][] = [['', realpathSync(engineDir)]]; + while (todo.length > 0) { + const [key, dir] = todo.pop()!; + if (seen.has(dir)) continue; + seen.add(dir); + const entry = entries[key] ?? {}; + for (const name of Object.keys({ ...entry.dependencies, ...entry.optionalDependencies })) { + const shippedKey = placed(key, name); + const shipped = shippedKey === undefined ? undefined : entries[shippedKey]; + if (shippedKey === undefined || shipped?.version === undefined || shipped.dev === true) continue; + const found = resolvedPackageFolder(dir, name); + if (found === null) { + if (shipped.optional !== true) drift.push({ from: key === '' ? '.' : key, name, found: null, shipped: shipped.version }); + continue; + } + const version = versionAt(found); + if (version !== shipped.version) drift.push({ from: key === '' ? '.' : key, name, found: version, shipped: shipped.version }); + else todo.push([shippedKey, found]); + } + } + return drift; +} + +/** Throws NotInstalledAsShippedError when the engine at `engineDir` ships a shrinkwrap its install doesn't match. */ +export function assertInstalledAsShipped(engine: string, engineDir: string): void { + const drift = shippedTreeDrift(engineDir); + if (drift !== null && drift.length > 0) throw new NotInstalledAsShippedError(engine, drift); +} diff --git a/packages/engine-beta/README.md b/packages/engine-beta/README.md index 60782e82..558e7067 100644 --- a/packages/engine-beta/README.md +++ b/packages/engine-beta/README.md @@ -8,7 +8,7 @@ The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-beta@next ``` -Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). A layout with two copies is refused with `MIXED_SDK_LAYOUT`. A program that also uses the other networks (`@kuiralabs/midnight-engine-rc`) installs both; a process loads one of them. +Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). An install that isn't that tree (bun's installer ignores the shrinkwrap and resolves the packages again) is refused before any SDK module loads, with `MIXED_SDK_LAYOUT` and the npm command; bun can run what npm installed. A program that also uses the other networks (`@kuiralabs/midnight-engine-rc`) installs both; a process loads one of them. ## Entry points diff --git a/packages/engine-beta/api-report.md b/packages/engine-beta/api-report.md index 6c0d8ac2..3753f2b0 100644 --- a/packages/engine-beta/api-report.md +++ b/packages/engine-beta/api-report.md @@ -6,7 +6,7 @@ Generated by `node scripts/api-report.mjs write` from the code: every entry poin ```ts import { type Engine, type EngineHost } from "@kuiralabs/midnight-cli-core/engine"; -import { type RepoDeps } from "./wallet-data-repository.ts"; +import type { RepoDeps } from "./wallet-data-repository.ts"; export interface BetaEngineOptions { readonly repository?: RepoDeps; } diff --git a/packages/engine-beta/src/beta-engine.ts b/packages/engine-beta/src/beta-engine.ts new file mode 100644 index 00000000..2af86154 --- /dev/null +++ b/packages/engine-beta/src/beta-engine.ts @@ -0,0 +1,113 @@ +// The engine for the SDK's beta set, which stagenet runs: the wallet SDK's +// 5.0 beta split packages, ledger 9 rc.3 and midnight-js 5 beta, as mn pins +// them. + +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { type Engine, type EngineHost, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/engine'; +import type { BetaEngineOptions } from './index.ts'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; +import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; +import { blockLimitsOf } from './ledger-parameters.ts'; +import { rawContractState } from './contract-providers.ts'; +import { assertAddress } from './addresses.ts'; +import { inspectTxHex } from './tx-inspect.ts'; +import { readOffer, spentNullifiers } from './offer-reader.ts'; +import { createBetaWallet } from './wallet.ts'; +import { WalletDataRepository, type RepoDeps } from './wallet-data-repository.ts'; +import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; + +// The account package, whose Midnight libraries are peer dependencies: each +// engine declares it, and its copy in the engine's install resolves them to +// the engine's own SDK set. +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; + +// The engine's folder (above src/ or dist/), and the SDK packages it declares +// with the account package: each must reach the engine's own copy of every +// WASM package. +const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); +const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) + .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name) || name === ACCOUNT_PACKAGE); +assertOneSdkCopy("mn's beta engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); + +export type { BetaEngineOptions } from './index.ts'; + +/** + * The beta engine for a host: its own wallet repository (the in-memory caches), + * reading the host's settings and telling the host's notices. Each host gets + * one of its own; the work every engine does alike is shared. + */ +export function createBetaEngine(host: EngineHost, options: BetaEngineOptions = {}): Engine { + return { ...SHARED, wallet: createBetaWallet(new WalletDataRepository(host, options.repository)) }; +} + +// The parts that keep no state: the same for every host's engine. +const SHARED: Omit = { + set: 'beta', + keys: { + unshieldedAddress: deriveUnshieldedAddress, + unshieldedAddresses: deriveAllAddresses, + shieldedAddress: deriveShieldedAddressString, + shieldedAddresses: deriveAllShieldedAddresses, + dustPublicKeyHex: dustPublicKeyHexFromSeed, + shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, + assertAddress, + }, + ledger: { + blockLimits: blockLimitsOf, + nightTokenId: () => ledger.unshieldedToken().raw, + readTransaction: inspectTxHex, + readOffer, + spentNullifiers, + }, + contracts: { + rawState: rawContractState, + acceptsPrivateStatePassword(password) { + try { + validatePassword(password); + return true; + } catch { + return false; + } + }, + scripts: { + packages: SCRIPT_PACKAGES, + packageFolder, + compactRuntimeVersion, + // The compiler release whose contracts compact-runtime 0.18 runs (compactc 0.33, built with --feature-zkir-v3). + compiler: 'compactc 0.33', + acceptsRuntime(runtimeVersion) { + try { + checkRuntimeVersion(runtimeVersion); + return true; + } catch { + return false; + } + }, + deploy: generateDeployScript, + call: generateCallScript, + state: generateStateScript, + }, + }, + readers: { + shieldedBalance: readShieldedBalanceCached, + }, + // Imported from this engine's folder, so the copy is the one its install gives it. + async account() { + const [artefacts, connector, context, contract, deposit, errors, owner] = await Promise.all([ + import('@kuiralabs/midnight-account-chain/artefacts'), + import('@kuiralabs/midnight-account-chain/connector'), + import('@kuiralabs/midnight-account-chain/context'), + import('@kuiralabs/midnight-account-chain/contract'), + import('@kuiralabs/midnight-account-chain/deposit'), + import('@kuiralabs/midnight-account-chain/errors'), + import('@kuiralabs/midnight-account-chain/owner'), + ]); + return { artefacts, connector, context, contract, deposit, errors, owner }; + }, +}; diff --git a/packages/engine-beta/src/index.ts b/packages/engine-beta/src/index.ts index 8d33e0b2..a3059b03 100644 --- a/packages/engine-beta/src/index.ts +++ b/packages/engine-beta/src/index.ts @@ -1,116 +1,24 @@ -// The engine for the SDK's beta set, which stagenet runs: the wallet SDK's -// 5.0 beta split packages, ledger 9 rc.3 and midnight-js 5 beta, as mn pins -// them. +// @kuiralabs/midnight-engine-beta: the engine, loaded once the install is known to +// be the tree it was tested with. That is checked before any SDK module loads, +// against the npm-shrinkwrap.json the package ships: an installer that ignores +// it (bun's) resolves the ranges again, and the SDK can then fail as it loads, +// before any check inside the engine could say why. -import { readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { type Engine, type EngineHost, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/engine'; -import * as ledger from '@midnightntwrk/ledger-v9'; -import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; -import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; -import { blockLimitsOf } from './ledger-parameters.ts'; -import { rawContractState } from './contract-providers.ts'; -import { assertAddress } from './addresses.ts'; -import { inspectTxHex } from './tx-inspect.ts'; -import { readOffer, spentNullifiers } from './offer-reader.ts'; -import { createBetaWallet } from './wallet.ts'; -import { WalletDataRepository, type RepoDeps } from './wallet-data-repository.ts'; -import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; -import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; +import { assertInstalledAsShipped, type Engine, type EngineHost } from '@kuiralabs/midnight-cli-core/engine'; +import type { RepoDeps } from './wallet-data-repository.ts'; -// The account package, whose Midnight libraries are peer dependencies: each -// engine declares it, and its copy in the engine's install resolves them to -// the engine's own SDK set. -const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; +assertInstalledAsShipped("mn's beta engine", dirname(dirname(fileURLToPath(import.meta.url)))); +const engine = await import('./beta-engine.ts'); -// The engine's folder (above src/ or dist/), and the SDK packages it declares -// with the account package: each must reach the engine's own copy of every -// WASM package. -const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); -const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) - .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name) || name === ACCOUNT_PACKAGE); -assertOneSdkCopy("mn's beta engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); - -/** What an beta engine is made with besides its host. */ +/** What a beta engine is made with besides its host. */ export interface BetaEngineOptions { /** Its wallet repository's seams (the clock, the chain's and the indexer's reads), for a test standing in for the network. */ readonly repository?: RepoDeps; } -/** - * The beta engine for a host: its own wallet repository (the in-memory caches), - * reading the host's settings and telling the host's notices. Each host gets - * one of its own; the work every engine does alike is shared. - */ +/** The beta engine, for a host's engine loader. */ export function createBetaEngine(host: EngineHost, options: BetaEngineOptions = {}): Engine { - return { ...SHARED, wallet: createBetaWallet(new WalletDataRepository(host, options.repository)) }; + return engine.createBetaEngine(host, options); } - -// The parts that keep no state: the same for every host's engine. -const SHARED: Omit = { - set: 'beta', - keys: { - unshieldedAddress: deriveUnshieldedAddress, - unshieldedAddresses: deriveAllAddresses, - shieldedAddress: deriveShieldedAddressString, - shieldedAddresses: deriveAllShieldedAddresses, - dustPublicKeyHex: dustPublicKeyHexFromSeed, - shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, - assertAddress, - }, - ledger: { - blockLimits: blockLimitsOf, - nightTokenId: () => ledger.unshieldedToken().raw, - readTransaction: inspectTxHex, - readOffer, - spentNullifiers, - }, - contracts: { - rawState: rawContractState, - acceptsPrivateStatePassword(password) { - try { - validatePassword(password); - return true; - } catch { - return false; - } - }, - scripts: { - packages: SCRIPT_PACKAGES, - packageFolder, - compactRuntimeVersion, - // The compiler release whose contracts compact-runtime 0.18 runs (compactc 0.33, built with --feature-zkir-v3). - compiler: 'compactc 0.33', - acceptsRuntime(runtimeVersion) { - try { - checkRuntimeVersion(runtimeVersion); - return true; - } catch { - return false; - } - }, - deploy: generateDeployScript, - call: generateCallScript, - state: generateStateScript, - }, - }, - readers: { - shieldedBalance: readShieldedBalanceCached, - }, - // Imported from this engine's folder, so the copy is the one its install gives it. - async account() { - const [artefacts, connector, context, contract, deposit, errors, owner] = await Promise.all([ - import('@kuiralabs/midnight-account-chain/artefacts'), - import('@kuiralabs/midnight-account-chain/connector'), - import('@kuiralabs/midnight-account-chain/context'), - import('@kuiralabs/midnight-account-chain/contract'), - import('@kuiralabs/midnight-account-chain/deposit'), - import('@kuiralabs/midnight-account-chain/errors'), - import('@kuiralabs/midnight-account-chain/owner'), - ]); - return { artefacts, connector, context, contract, deposit, errors, owner }; - }, -}; diff --git a/packages/engine-rc/README.md b/packages/engine-rc/README.md index de2996af..5c9210d5 100644 --- a/packages/engine-rc/README.md +++ b/packages/engine-rc/README.md @@ -8,7 +8,7 @@ The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, l npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-rc@next ``` -Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). A layout with two copies is refused with `MIXED_SDK_LAYOUT`. A program that also uses stagenet (`@kuiralabs/midnight-engine-beta`) installs both; a process loads one of them. +Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). An install that isn't that tree (bun's installer ignores the shrinkwrap and resolves the packages again) is refused before any SDK module loads, with `MIXED_SDK_LAYOUT` and the npm command; bun can run what npm installed. A program that also uses stagenet (`@kuiralabs/midnight-engine-beta`) installs both; a process loads one of them. ## Entry points diff --git a/packages/engine-rc/api-report.md b/packages/engine-rc/api-report.md index f3b2ce94..61081111 100644 --- a/packages/engine-rc/api-report.md +++ b/packages/engine-rc/api-report.md @@ -6,7 +6,7 @@ Generated by `node scripts/api-report.mjs write` from the code: every entry poin ```ts import { type Engine, type EngineHost } from "@kuiralabs/midnight-cli-core/engine"; -import { type RepoDeps } from "./wallet-data-repository.ts"; +import type { RepoDeps } from "./wallet-data-repository.ts"; export interface RcEngineOptions { readonly repository?: RepoDeps; } diff --git a/packages/engine-rc/src/index.ts b/packages/engine-rc/src/index.ts index 510aec25..e383e50b 100644 --- a/packages/engine-rc/src/index.ts +++ b/packages/engine-rc/src/index.ts @@ -1,37 +1,16 @@ -// The engine for the SDK's release candidates (rc): the wallet SDK 2.0 -// release candidates, ledger 9 and midnight-js 5 as mn pins them. +// @kuiralabs/midnight-engine-rc: the engine, loaded once the install is known to +// be the tree it was tested with. That is checked before any SDK module loads, +// against the npm-shrinkwrap.json the package ships: an installer that ignores +// it (bun's) resolves the ranges again, and the SDK can then fail as it loads, +// before any check inside the engine could say why. -import { readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; +import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { type Engine, type EngineHost, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/engine'; -import * as ledger from '@midnightntwrk/ledger-v9'; -import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; -import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; -import { blockLimitsOf } from './ledger-parameters.ts'; -import { rawContractState } from './contract-providers.ts'; -import { assertAddress } from './addresses.ts'; -import { inspectTxHex } from './tx-inspect.ts'; -import { readOffer, spentNullifiers } from './offer-reader.ts'; -import { createRcWallet } from './wallet.ts'; -import { WalletDataRepository, type RepoDeps } from './wallet-data-repository.ts'; -import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; -import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; -import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; -import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; +import { assertInstalledAsShipped, type Engine, type EngineHost } from '@kuiralabs/midnight-cli-core/engine'; +import type { RepoDeps } from './wallet-data-repository.ts'; -// The account package, whose Midnight libraries are peer dependencies: each -// engine declares it, and its copy in the engine's install resolves them to -// the engine's own SDK set. -const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; - -// The engine's folder (above src/ or dist/), and the SDK packages it declares -// with the account package: each must reach the engine's own copy of every -// WASM package. -const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); -const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) - .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name) || name === ACCOUNT_PACKAGE); -assertOneSdkCopy("mn's rc engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); +assertInstalledAsShipped("mn's rc engine", dirname(dirname(fileURLToPath(import.meta.url)))); +const engine = await import('./rc-engine.ts'); /** What an rc engine is made with besides its host. */ export interface RcEngineOptions { @@ -39,77 +18,7 @@ export interface RcEngineOptions { readonly repository?: RepoDeps; } -/** - * The rc engine for a host: its own wallet repository (the in-memory caches), - * reading the host's settings and telling the host's notices. Each host gets - * one of its own; the work every engine does alike is shared. - */ +/** The rc engine, for a host's engine loader. */ export function createRcEngine(host: EngineHost, options: RcEngineOptions = {}): Engine { - return { ...SHARED, wallet: createRcWallet(new WalletDataRepository(host, options.repository)) }; + return engine.createRcEngine(host, options); } - -// The parts that keep no state: the same for every host's engine. -const SHARED: Omit = { - set: 'rc', - keys: { - unshieldedAddress: deriveUnshieldedAddress, - unshieldedAddresses: deriveAllAddresses, - shieldedAddress: deriveShieldedAddressString, - shieldedAddresses: deriveAllShieldedAddresses, - dustPublicKeyHex: dustPublicKeyHexFromSeed, - shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, - assertAddress, - }, - ledger: { - blockLimits: blockLimitsOf, - nightTokenId: () => ledger.unshieldedToken().raw, - readTransaction: inspectTxHex, - readOffer, - spentNullifiers, - }, - contracts: { - rawState: rawContractState, - acceptsPrivateStatePassword(password) { - try { - validatePassword(password); - return true; - } catch { - return false; - } - }, - scripts: { - packages: SCRIPT_PACKAGES, - packageFolder, - compactRuntimeVersion, - // The compiler release whose contracts compact-runtime 0.20 runs (compactc 0.35.0 writes runtime-version 0.20.0). - compiler: 'compactc 0.35', - acceptsRuntime(runtimeVersion) { - try { - checkRuntimeVersion(runtimeVersion); - return true; - } catch { - return false; - } - }, - deploy: generateDeployScript, - call: generateCallScript, - state: generateStateScript, - }, - }, - readers: { - shieldedBalance: readShieldedBalanceCached, - }, - // Imported from this engine's folder, so the copy is the one its install gives it. - async account() { - const [artefacts, connector, context, contract, deposit, errors, owner] = await Promise.all([ - import('@kuiralabs/midnight-account-chain/artefacts'), - import('@kuiralabs/midnight-account-chain/connector'), - import('@kuiralabs/midnight-account-chain/context'), - import('@kuiralabs/midnight-account-chain/contract'), - import('@kuiralabs/midnight-account-chain/deposit'), - import('@kuiralabs/midnight-account-chain/errors'), - import('@kuiralabs/midnight-account-chain/owner'), - ]); - return { artefacts, connector, context, contract, deposit, errors, owner }; - }, -}; diff --git a/packages/engine-rc/src/rc-engine.ts b/packages/engine-rc/src/rc-engine.ts new file mode 100644 index 00000000..e453647a --- /dev/null +++ b/packages/engine-rc/src/rc-engine.ts @@ -0,0 +1,112 @@ +// The engine for the SDK's release candidates (rc): the wallet SDK 2.0 +// release candidates, ledger 9 and midnight-js 5 as mn pins them. + +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { type Engine, type EngineHost, assertOneSdkCopy } from '@kuiralabs/midnight-cli-core/engine'; +import type { RcEngineOptions } from './index.ts'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { checkRuntimeVersion, versionString as compactRuntimeVersion } from '@midnight-ntwrk/compact-runtime'; +import { validatePassword } from '@midnight-ntwrk/midnight-js-utils'; +import { blockLimitsOf } from './ledger-parameters.ts'; +import { rawContractState } from './contract-providers.ts'; +import { assertAddress } from './addresses.ts'; +import { inspectTxHex } from './tx-inspect.ts'; +import { readOffer, spentNullifiers } from './offer-reader.ts'; +import { createRcWallet } from './wallet.ts'; +import { WalletDataRepository, type RepoDeps } from './wallet-data-repository.ts'; +import { SCRIPT_PACKAGES, generateCallScript, generateDeployScript, generateStateScript, packageFolder } from './contract-scripts.ts'; +import { dustPublicKeyHexFromSeed } from './dust-direct-cache.ts'; +import { readShieldedBalanceCached, shieldedCoinPublicKeyHexFromSeed } from './shielded-direct-cache.ts'; +import { deriveAllAddresses, deriveAllShieldedAddresses, deriveShieldedAddressString, deriveUnshieldedAddress } from './derive-address.ts'; + +// The account package, whose Midnight libraries are peer dependencies: each +// engine declares it, and its copy in the engine's install resolves them to +// the engine's own SDK set. +const ACCOUNT_PACKAGE = '@kuiralabs/midnight-account-chain'; + +// The engine's folder (above src/ or dist/), and the SDK packages it declares +// with the account package: each must reach the engine's own copy of every +// WASM package. +const ENGINE_DIR = dirname(dirname(fileURLToPath(import.meta.url))); +const SDK_DEPENDENCIES = Object.keys((JSON.parse(readFileSync(join(ENGINE_DIR, 'package.json'), 'utf-8')) as { dependencies: Record }).dependencies) + .filter((name) => /^@midnight(ntwrk|-ntwrk)\//.test(name) || name === ACCOUNT_PACKAGE); +assertOneSdkCopy("mn's rc engine", ENGINE_DIR, SDK_DEPENDENCIES, ['@midnightntwrk/ledger-v9', '@midnight-ntwrk/compact-runtime', '@midnightntwrk/onchain-runtime-v4']); + +export type { RcEngineOptions } from './index.ts'; + +/** + * The rc engine for a host: its own wallet repository (the in-memory caches), + * reading the host's settings and telling the host's notices. Each host gets + * one of its own; the work every engine does alike is shared. + */ +export function createRcEngine(host: EngineHost, options: RcEngineOptions = {}): Engine { + return { ...SHARED, wallet: createRcWallet(new WalletDataRepository(host, options.repository)) }; +} + +// The parts that keep no state: the same for every host's engine. +const SHARED: Omit = { + set: 'rc', + keys: { + unshieldedAddress: deriveUnshieldedAddress, + unshieldedAddresses: deriveAllAddresses, + shieldedAddress: deriveShieldedAddressString, + shieldedAddresses: deriveAllShieldedAddresses, + dustPublicKeyHex: dustPublicKeyHexFromSeed, + shieldedCoinPublicKeyHex: shieldedCoinPublicKeyHexFromSeed, + assertAddress, + }, + ledger: { + blockLimits: blockLimitsOf, + nightTokenId: () => ledger.unshieldedToken().raw, + readTransaction: inspectTxHex, + readOffer, + spentNullifiers, + }, + contracts: { + rawState: rawContractState, + acceptsPrivateStatePassword(password) { + try { + validatePassword(password); + return true; + } catch { + return false; + } + }, + scripts: { + packages: SCRIPT_PACKAGES, + packageFolder, + compactRuntimeVersion, + // The compiler release whose contracts compact-runtime 0.20 runs (compactc 0.35.0 writes runtime-version 0.20.0). + compiler: 'compactc 0.35', + acceptsRuntime(runtimeVersion) { + try { + checkRuntimeVersion(runtimeVersion); + return true; + } catch { + return false; + } + }, + deploy: generateDeployScript, + call: generateCallScript, + state: generateStateScript, + }, + }, + readers: { + shieldedBalance: readShieldedBalanceCached, + }, + // Imported from this engine's folder, so the copy is the one its install gives it. + async account() { + const [artefacts, connector, context, contract, deposit, errors, owner] = await Promise.all([ + import('@kuiralabs/midnight-account-chain/artefacts'), + import('@kuiralabs/midnight-account-chain/connector'), + import('@kuiralabs/midnight-account-chain/context'), + import('@kuiralabs/midnight-account-chain/contract'), + import('@kuiralabs/midnight-account-chain/deposit'), + import('@kuiralabs/midnight-account-chain/errors'), + import('@kuiralabs/midnight-account-chain/owner'), + ]); + return { artefacts, connector, context, contract, deposit, errors, owner }; + }, +}; diff --git a/scripts/code-reach.mjs b/scripts/code-reach.mjs index 3d7df3a1..faeca7b3 100644 --- a/scripts/code-reach.mjs +++ b/scripts/code-reach.mjs @@ -96,7 +96,7 @@ const ENGINE_SETS = ['rc', 'beta']; /** * The parts of an Engine and the modules of an engine's package each is made - * of (its index assembles them); a test holds this to both engines' indexes. + * of (its assembler, -engine.ts, puts them together); a test holds this to both engines. */ export const ENGINE_PARTS = { keys: ['derive-address.ts', 'addresses.ts', 'dust-direct-cache.ts', 'shielded-direct-cache.ts'], @@ -130,8 +130,8 @@ export const ENGINE_SITES = [ }, ]; -/** Imports the walk doesn't follow: an engine's index imports its parts' modules, which only a use of that part reaches (ENGINE_SITES). */ -export const CUT_IMPORTS = ENGINE_SETS.flatMap((set) => [...new Set(Object.values(ENGINE_PARTS).flat())].map((file) => [`packages/engine-${set}/src/index.ts`, `packages/engine-${set}/src/${file}`])); +/** Imports the walk doesn't follow: an engine's assembler (-engine.ts, which its index loads) imports its parts' modules, which only a use of that part reaches (ENGINE_SITES). */ +export const CUT_IMPORTS = ENGINE_SETS.flatMap((set) => [...new Set(Object.values(ENGINE_PARTS).flat())].map((file) => [`packages/engine-${set}/src/${set}-engine.ts`, `packages/engine-${set}/src/${file}`])); /** What the shell gives a command whose definition's `shell` asks for it, and the module it loads. */ export const SHELL_PROVISIONS = { diff --git a/src/__tests__/declared-codes.test.ts b/src/__tests__/declared-codes.test.ts index acc5eb3a..818e95d4 100644 --- a/src/__tests__/declared-codes.test.ts +++ b/src/__tests__/declared-codes.test.ts @@ -133,13 +133,13 @@ describe("the scan's tables", () => { expect(DYNAMIC_CLASSES.PrepStepFailedError!.codes).toStrictEqual([]); }); - it("split each engine's index into the parts it assembles, every module it imports in one of them", () => { + it("split each engine's assembler into the parts it puts together, every module it imports in one of them", () => { const parts = new Set(Object.values(ENGINE_PARTS).flat()); for (const set of ['rc', 'beta']) { - const index = join(ROOT, 'packages', `engine-${set}`, 'src', 'index.ts'); + const index = join(ROOT, 'packages', `engine-${set}`, 'src', `${set}-engine.ts`); const own = importsOf(index).filter((each) => !each.typeOnly && each.specifier.startsWith('./')).map((each) => importTarget(index, each.specifier)!.slice(join(ROOT, 'packages', `engine-${set}`, 'src').length + 1)); expect(new Set(own), set).toStrictEqual(parts); - expect(CUT_IMPORTS.filter(([from]) => from === `packages/engine-${set}/src/index.ts`).map(([, to]) => to.split('/').pop()).sort(), set).toStrictEqual([...parts].sort()); + expect(CUT_IMPORTS.filter(([from]) => from === `packages/engine-${set}/src/${set}-engine.ts`).map(([, to]) => to.split('/').pop()).sort(), set).toStrictEqual([...parts].sort()); } }); }); From 82b171d8bc8d44e7ef9f63e2c0bae6c65346c33c Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Wed, 4 Nov 2026 19:21:38 -0800 Subject: [PATCH 85/88] The clean-install check installs with bun too (3J) CI's fresh-install check now also installs the packed packages with bun (CI sets bun up from .bun-version) and checks that each engine refuses to load, under Node and under bun, with MIXED_SDK_LAYOUT naming npm. Where bun isn't installed, the step says so and is skipped. Locally: a fresh install works, the four refusals included. --- scripts/fresh-install-check.mjs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/scripts/fresh-install-check.mjs b/scripts/fresh-install-check.mjs index ff45dd30..6557d38b 100644 --- a/scripts/fresh-install-check.mjs +++ b/scripts/fresh-install-check.mjs @@ -409,6 +409,27 @@ try { const deep = run(process.execPath, ['entry.mjs', `${name}/${deepPath}`], outside).trim(); check(`a program outside mn is refused ${name}/${deepPath}`, deep === 'ERR_PACKAGE_PATH_NOT_EXPORTED', deep); } + + // The same packages installed with bun (Y65): its installer ignores each + // engine's shrinkwrap and resolves the ranges again, so each engine must + // refuse to load, before any SDK module does, with MIXED_SDK_LAYOUT and the + // npm command, under Node and under bun. Skipped where bun isn't installed. + const bunInstalled = (() => { try { run('bun', ['--version'], work); return true; } catch { return false; } })(); + if (bunInstalled) { + const bunOutside = join(work, 'bun-outside'); + mkdirSync(bunOutside); + writeFileSync(join(bunOutside, 'package.json'), JSON.stringify({ name: 'bun-outside', private: true, type: 'module' })); + execFileSync('bun', ['add', ...workspaces.map(({ name, version }) => `${name}@${version}`)], { cwd: bunOutside, env: { ...process.env, BUN_CONFIG_REGISTRY: registry.url, BUN_INSTALL_CACHE_DIR: join(work, 'bun-cache') }, stdio: 'pipe' }); + writeFileSync(join(bunOutside, 'load.mjs'), readFileSync(join(outside, 'load.mjs'), 'utf-8').replace(`console.log(error.code ?? error.message)`, `console.log(error.code, /Install with npm/.test(error.message) ? 'names npm' : '')`).replaceAll(JSON.stringify(join(outside, 'state')), JSON.stringify(join(bunOutside, 'state')))); + for (const runtime of [process.execPath, 'bun']) { + for (const [network, set] of [['undeployed', 'rc'], ['stagenet', 'beta']]) { + const refused = run(runtime, ['load.mjs', network], bunOutside).trim(); + check(`installed with bun, the ${set} engine refuses to load under ${runtime === 'bun' ? 'bun' : 'Node'}, naming npm`, refused === 'MIXED_SDK_LAYOUT names npm', refused); + } + } + } else { + console.log(' (bun is not installed: the bun install is not checked)'); + } } catch (error) { check('the fresh install and its checks ran', false, String(error.stderr || error.message).trim().split('\n').slice(-3).join(' | ')); } finally { From 418b2bbd90d0a64ddcfe03e554525adaf62e54bf Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Thu, 5 Nov 2026 00:00:53 -0800 Subject: [PATCH 86/88] swap make splits a coin; spends leave open offers' coins alone (SJ) An open offer holds every coin it spends, and the shielded wallet spends the smallest coin first, seeing an open offer's coins as free: a second offer of the same token was refused with OFFER_COINS_IN_USE. - Each engine builds its shielded wallet with mn's coin picker (the SDKs' public builders): it skips the coins of the wallet's open offers, except in their cancel, and takes a coin of the exact amount when there is one. When only offers' coins could pay, OFFER_COINS_IN_USE comes before proving. - swap make: when no free coin is worth exactly what it gives, it first splits one (a transfer to itself, a fee in Dust), waits for the receipt and for the wallet to hold the new coin, then makes the offer from it. Its JSON gains `split` (txHash and receipt). - swap cancel spends exactly the offer's coins, so the wallet's other open offers stay live. - The picker derives its keys for each nullifier and clears them: a coin secret key held on its own is cleared by the ledger once its keys are collected (regression test under --expose-gc). --- packages/cli-core/api-report.md | 22 ++++ .../src/__tests__/coin-picker.test.ts | 111 ++++++++++++++++++ packages/cli-core/src/engine.ts | 3 +- packages/cli-core/src/lib/coin-picker.ts | 77 ++++++++++++ packages/cli-core/src/lib/engine.ts | 2 + packages/cli-core/src/lib/sdk-errors.ts | 27 ++++- packages/cli-core/src/lib/wallet-session.ts | 19 +++ .../src/__tests__/shielded-wallet.test.ts | 6 + packages/engine-beta/src/dapp-connector.ts | 37 +++--- packages/engine-beta/src/facade.ts | 17 ++- packages/engine-beta/src/shielded-wallet.ts | 46 ++++++++ .../src/__tests__/shielded-wallet.test.ts | 6 + packages/engine-rc/src/dapp-connector.ts | 37 +++--- packages/engine-rc/src/facade.ts | 17 ++- packages/engine-rc/src/shielded-wallet.ts | 59 ++++++++++ packages/wallet/api-report.md | 6 + .../wallet/src/__tests__/swap-lib.test.ts | 49 +++++++- .../wallet/src/commands/swap.definition.ts | 8 +- packages/wallet/src/commands/swap.guidance.ts | 9 +- packages/wallet/src/commands/swap.ts | 7 +- packages/wallet/src/index.ts | 2 +- packages/wallet/src/lib/swap/make.ts | 41 ++++++- packages/wallet/src/lib/swap/offers.ts | 22 +++- scripts/check-layering.mjs | 2 +- src/__tests__/grant-deposit-command.test.ts | 2 + test-support/coin-picking-gc.ts | 32 +++++ test-support/connector-stub.ts | 10 +- test-support/connector-suite.ts | 63 ++++++++-- 28 files changed, 674 insertions(+), 65 deletions(-) create mode 100644 packages/cli-core/src/__tests__/coin-picker.test.ts create mode 100644 packages/cli-core/src/lib/coin-picker.ts create mode 100644 packages/engine-beta/src/__tests__/shielded-wallet.test.ts create mode 100644 packages/engine-beta/src/shielded-wallet.ts create mode 100644 packages/engine-rc/src/__tests__/shielded-wallet.test.ts create mode 100644 packages/engine-rc/src/shielded-wallet.ts create mode 100644 test-support/coin-picking-gc.ts diff --git a/packages/cli-core/api-report.md b/packages/cli-core/api-report.md index fb90c5a9..7a6c1394 100644 --- a/packages/cli-core/api-report.md +++ b/packages/cli-core/api-report.md @@ -307,6 +307,7 @@ export interface DAppConnector { handOffPendingTx(connectionId: string, txHex: string): boolean; takeOffer(connectionId: string, txHex: string): Promise; cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; + holdsFreeCoin(token: string, amount: bigint): boolean; hasPendingTxs(): boolean; dispose(): void; } @@ -808,6 +809,8 @@ export interface WalletSession { swap(give: TokenAmount[], take: TokenPayment[]): Promise; makeOffer(give: SwapLeg, want: SwapLeg): Promise; takeOffer(tx: string): Promise; + holdsFreeCoin(leg: SwapLeg): Promise; + splitCoin(leg: SwapLeg): Promise; cancelOffers(offers: readonly OpenOffer[]): Promise; sign(data: string, encoding: 'hex' | 'base64' | 'text'): Promise; submit(tx: string): Promise; @@ -1088,6 +1091,23 @@ export declare const SYNC_ATTEMPT_TIMEOUT_MS = 30000; export declare const SYNC_TIMEOUT_MS = 300000; export declare const TOKEN_MULTIPLIER = 1000000; export declare const TX_TTL_MINUTES = 10; +export interface CoinPicking { + pick(coins: readonly C[], tokenType: string, amountNeeded: bigint): C | undefined; + cancelling(offers: readonly OpenOffer[], work: () => Promise): Promise; +} +export type CoinRule = { + readonly kind: 'avoid'; + readonly held: ReadonlyMap; +} | { + readonly kind: 'only'; + readonly allowed: ReadonlySet; +}; +export declare function createCoinPicking(openOffers: () => readonly OpenOffer[], nullifierOf: (coin: C) => string): CoinPicking; +export interface PickableCoin { + readonly type: string; + readonly value: bigint; +} +export declare function pickCoin(coins: readonly C[], tokenType: string, amountNeeded: bigint, nullifierOf: (coin: C) => string, rule: CoinRule): C | undefined; export declare function chooseDustCoins(coins: readonly DustInput[], owed: bigint, combine: (owed: bigint) => DustInput[] | undefined): DustInput[] | undefined; export interface DustInput { token: TToken; @@ -1140,6 +1160,7 @@ export interface DAppConnector { handOffPendingTx(connectionId: string, txHex: string): boolean; takeOffer(connectionId: string, txHex: string): Promise; cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; + holdsFreeCoin(token: string, amount: bigint): boolean; hasPendingTxs(): boolean; dispose(): void; } @@ -1399,6 +1420,7 @@ export interface DustShortfall { available: bigint; } export declare function dustShortfallOf(err: unknown): DustShortfall | undefined; +export declare function heldCoinRefusalOf(err: unknown): OfferCoinsInUseError | undefined; export declare function isColdStartRace(err: unknown): boolean; export declare function isDustRelatedError(err: any): boolean; export declare function isDustShortage(err: unknown): boolean; diff --git a/packages/cli-core/src/__tests__/coin-picker.test.ts b/packages/cli-core/src/__tests__/coin-picker.test.ts new file mode 100644 index 00000000..721a1cf5 --- /dev/null +++ b/packages/cli-core/src/__tests__/coin-picker.test.ts @@ -0,0 +1,111 @@ +// mn's coin picker: which shielded coin a spend takes next, skipping open +// offers' coins outside their cancel and preferring a coin of the exact amount. + +import { describe, expect, it } from 'vitest'; +import { createCoinPicking, pickCoin, type CoinRule } from '../lib/coin-picker.ts'; +import { OfferCoinsInUseError, type OpenOffer } from '../lib/open-offers.ts'; +import { heldCoinRefusalOf, isColdStartRace, toEngineError, withEngineCode } from '../lib/sdk-errors.ts'; + +const T = 'aa'.repeat(32); +const U = 'bb'.repeat(32); +interface Coin { type: string; value: bigint; nonce: string } +const coin = (nonce: string, value: bigint, type = T): Coin => ({ type, value, nonce }); +// A coin's nullifier, here its nonce upper-cased: the picker compares nullifiers without case. +const nullifierOf = (c: Coin) => `N${c.nonce}`.toUpperCase(); +const avoid = (held: Record = {}): CoinRule => ({ kind: 'avoid', held: new Map(Object.entries(held)) }); +const offer = (id: string, nullifiers: string[]): OpenOffer => ({ + id, nullifiers, terms: { give: { token: T, amount: 1n }, want: { token: U, amount: 1n } }, madeAt: new Date(0), expiresAt: new Date(1), +}); + +describe('pickCoin', () => { + it('takes a coin of exactly the amount needed over a smaller one', () => { + const coins = [coin('a', 1n), coin('b', 5n), coin('c', 9n)]; + expect(pickCoin(coins, T, 5n, nullifierOf, avoid())?.nonce).toBe('b'); + }); + + it('takes the smallest coin of the token when none is exact, as the SDK does', () => { + const coins = [coin('a', 7n), coin('b', 3n, U), coin('c', 4n)]; + expect(pickCoin(coins, T, 10n, nullifierOf, avoid())?.nonce).toBe('c'); + }); + + it("skips an open offer's coin even when it is the smallest or the exact one", () => { + const coins = [coin('a', 1n), coin('b', 998n)]; + expect(pickCoin(coins, T, 1n, nullifierOf, avoid({ na: 'offer-1' }))?.nonce).toBe('b'); + }); + + it("refuses with the holding offers when only open offers' coins of the token are left", () => { + const coins = [coin('a', 1n), coin('b', 2n), coin('c', 50n, U)]; + let thrown: unknown; + try { pickCoin(coins, T, 3n, nullifierOf, avoid({ na: 'offer-1', nb: 'offer-2' })); } catch (err) { thrown = err; } + expect(thrown).toBeInstanceOf(OfferCoinsInUseError); + expect((thrown as OfferCoinsInUseError).offerIds.sort()).toEqual(['offer-1', 'offer-2']); + }); + + it('is undefined when the wallet holds none of the token at all (the SDK reports the shortage)', () => { + expect(pickCoin([coin('a', 5n, U)], T, 1n, nullifierOf, avoid({ na: 'offer-1' }))).toBeUndefined(); + }); + + it("in a cancel, takes only the cancelled offers' coins, and is undefined once they are used", () => { + const coins = [coin('a', 1n), coin('b', 2n), coin('c', 3n)]; + const only: CoinRule = { kind: 'only', allowed: new Set(['nb']) }; + expect(pickCoin(coins, T, 6n, nullifierOf, only)?.nonce).toBe('b'); + expect(pickCoin(coins.filter((c) => c.nonce !== 'b'), T, 4n, nullifierOf, only)).toBeUndefined(); + }); +}); + +describe('createCoinPicking', () => { + it('reads the open offers at each pick, so an offer made since is skipped', () => { + let open: OpenOffer[] = []; + const picking = createCoinPicking(() => open, nullifierOf); + const coins = [coin('a', 1n), coin('b', 998n)]; + expect(picking.pick(coins, T, 1n)?.nonce).toBe('a'); + open = [offer('offer-1', ['NA'])]; + expect(picking.pick(coins, T, 1n)?.nonce).toBe('b'); + }); + + it("lets a cancel spend only its offers' coins, and goes back to skipping them after", async () => { + const open = [offer('offer-1', ['NA']), offer('offer-2', ['NB'])]; + const picking = createCoinPicking(() => open, nullifierOf); + const coins = [coin('a', 1n), coin('b', 1n), coin('c', 5n)]; + const inCancel = await picking.cancelling([open[0]!], async () => picking.pick(coins, T, 1n)?.nonce); + expect(inCancel).toBe('a'); + expect(picking.pick(coins, T, 1n)?.nonce).toBe('c'); + }); + + it('goes back to skipping after a cancel that fails', async () => { + const open = [offer('offer-1', ['NA'])]; + const picking = createCoinPicking(() => open, nullifierOf); + await expect(picking.cancelling(open, async () => { throw new Error('proof failed'); })).rejects.toThrow('proof failed'); + expect(picking.pick([coin('a', 1n), coin('c', 5n)], T, 1n)?.nonce).toBe('c'); + }); +}); + +describe("the picker's refusal through the SDK's wrapping", () => { + // As the shielded wallet wraps what its balancer throws: an OtherWalletError + // with it as the cause, inside an Effect FiberFailure. + const FIBER_FAILURE_CAUSE = Symbol.for('effect/Runtime/FiberFailure/Cause'); + const wrapped = () => { + const refusal = new OfferCoinsInUseError(['ab'.repeat(32)]); + const other = Object.assign(new Error('Balancing guaranteed section failed'), { _tag: 'Wallet.Other', cause: refusal }); + const fiber = Object.assign(new Error('(FiberFailure) Wallet.Other: Balancing guaranteed section failed'), { [FIBER_FAILURE_CAUSE]: { _tag: 'Fail', error: other } }); + return { refusal, fiber }; + }; + + it('is found among the causes', () => { + const { refusal, fiber } = wrapped(); + expect(heldCoinRefusalOf(fiber)).toBe(refusal); + expect(heldCoinRefusalOf(new Error('Insufficient funds'))).toBeUndefined(); + }); + + it('reaches mn as OFFER_COINS_IN_USE, and over the connector marked with it', () => { + const { refusal, fiber } = wrapped(); + expect(toEngineError(fiber)).toBe(refusal); + expect((withEngineCode(wrapped().fiber) as { mnCode?: string }).mnCode).toBe('OFFER_COINS_IN_USE'); + }); + + it('is not the cold-start race, so the wallet is not reopened for it', () => { + const { refusal } = wrapped(); + const tagged = Object.assign(new Error('Insufficient funds'), { _tag: 'Wallet.InsufficientFunds', tokenType: T, cause: refusal }); + expect(isColdStartRace(tagged)).toBe(false); + }); +}); diff --git a/packages/cli-core/src/engine.ts b/packages/cli-core/src/engine.ts index 0892f770..20e155e2 100644 --- a/packages/cli-core/src/engine.ts +++ b/packages/cli-core/src/engine.ts @@ -14,6 +14,7 @@ export { PRE_SEND_SYNC_TIMEOUT_MS, PROOF_TIMEOUT_MS, STALE_UTXO_ERROR_CODE, SYNC_ATTEMPT_TIMEOUT_MS, SYNC_TIMEOUT_MS, TOKEN_MULTIPLIER, TX_TTL_MINUTES } from './lib/constants.ts'; +export { type CoinPicking, type CoinRule, createCoinPicking, type PickableCoin, pickCoin } from './lib/coin-picker.ts'; export { chooseDustCoins, type DustInput, planDustInputs, spreadFeeAcrossInputs } from './lib/dust-balancing-plan.ts'; export { DustFeeNotGeneratedError, planRegistration } from './lib/dust-registration-plan.ts'; export { awaitDustForFee, DUST_SHORT_WAIT_MS, type DustWaitPlan, payWhenDustCovers, planDustWait, sleep } from './lib/dust-wait.ts'; @@ -33,7 +34,7 @@ export { assertSpendsNoOfferCoin } from './lib/open-offers.ts'; export { createPhaseTracker, type PhaseTracker } from './lib/phase-tracker.ts'; export { dustCacheDir, getDustCachePath, getShieldedCachePath, nativeCheckpointName } from './lib/reader-cache-files.ts'; export { - type DustShortfall, dustShortfallOf, isColdStartRace, isDustRelatedError, isDustShortage, + type DustShortfall, dustShortfallOf, heldCoinRefusalOf, isColdStartRace, isDustRelatedError, isDustShortage, isSdkInsufficientFundsError, markingEngineCodes, refusalCodeOf, reportingEngineErrors, toEngineError, withDustShortfall, withEngineCode } from './lib/sdk-errors.ts'; diff --git a/packages/cli-core/src/lib/coin-picker.ts b/packages/cli-core/src/lib/coin-picker.ts new file mode 100644 index 00000000..0b2e2c1b --- /dev/null +++ b/packages/cli-core/src/lib/coin-picker.ts @@ -0,0 +1,77 @@ +// Which shielded coin a spend takes next. The SDK's balancer asks for one coin +// at a time, with the amount still needed, and by default takes the smallest +// coin it holds unspent. An open swap offer's coins are unspent on chain, so a +// wallet opened later sees them as free: spending one cancels the offer. mn's +// picker skips them (except in the cancel of those offers) and takes a coin +// equal to the amount needed when there is one, so an offer made after a split +// spends exactly the coin the split made. + +import { OfferCoinsInUseError, type OpenOffer } from './open-offers.ts'; + +/** A coin as the picker reads it: its token and its value. */ +export interface PickableCoin { + readonly type: string; + readonly value: bigint; +} + +/** What a spend may use: every coin but the open offers' (`avoid`, the offer holding each by nullifier), or only the coins of the offers it cancels (`only`). */ +export type CoinRule = + | { readonly kind: 'avoid'; readonly held: ReadonlyMap } + | { readonly kind: 'only'; readonly allowed: ReadonlySet }; + +/** + * The coin of `tokenType` a spend takes next, of `coins`, under `rule`: one + * whose value is `amountNeeded` if there is one, otherwise the smallest. + * Undefined when the wallet holds none it may use; throws OfferCoinsInUseError + * when the only ones left are held by open offers. + */ +export function pickCoin(coins: readonly C[], tokenType: string, amountNeeded: bigint, nullifierOf: (coin: C) => string, rule: CoinRule): C | undefined { + const ofToken = coins.filter((coin) => coin.type === tokenType); + const usable = ofToken.filter((coin) => { + const nullifier = nullifierOf(coin).toLowerCase(); + return rule.kind === 'avoid' ? !rule.held.has(nullifier) : rule.allowed.has(nullifier); + }); + if (usable.length > 0) { + return usable.find((coin) => coin.value === amountNeeded) ?? usable.reduce((smallest, coin) => (coin.value < smallest.value ? coin : smallest)); + } + if (rule.kind === 'avoid' && ofToken.length > 0) { + const holding = [...new Set(ofToken.map((coin) => rule.held.get(nullifierOf(coin).toLowerCase())!))]; + throw new OfferCoinsInUseError(holding); + } + return undefined; +} + +/** A wallet's coin picking: the picker its SDK balancer calls, and the cancel that may spend its offers' coins. */ +export interface CoinPicking { + /** The coin a spend takes next, as pickCoin picks it under the wallet's open offers now. */ + pick(coins: readonly C[], tokenType: string, amountNeeded: bigint): C | undefined; + /** Runs `work` with only the coins of `offers` spendable: their cancel. */ + cancelling(offers: readonly OpenOffer[], work: () => Promise): Promise; +} + +/** + * The coin picking of a wallet whose open offers `openOffers` reads (mn's + * record, read at each pick, so an offer made since counts) and whose coins' + * nullifiers `nullifierOf` gives. + */ +export function createCoinPicking(openOffers: () => readonly OpenOffer[], nullifierOf: (coin: C) => string): CoinPicking { + let cancel: ReadonlySet | undefined; + const ruleNow = (): CoinRule => { + if (cancel !== undefined) return { kind: 'only', allowed: cancel }; + const held = new Map(); + for (const offer of openOffers()) for (const nullifier of offer.nullifiers) held.set(nullifier.toLowerCase(), offer.id); + return { kind: 'avoid', held }; + }; + return { + pick: (coins, tokenType, amountNeeded) => pickCoin(coins, tokenType, amountNeeded, nullifierOf, ruleNow()), + async cancelling(offers, work) { + if (cancel !== undefined) throw new Error('A cancel of open offers is already being built'); + cancel = new Set(offers.flatMap((offer) => offer.nullifiers.map((n) => n.toLowerCase()))); + try { + return await work(); + } finally { + cancel = undefined; + } + }, + }; +} diff --git a/packages/cli-core/src/lib/engine.ts b/packages/cli-core/src/lib/engine.ts index fa5a0f67..eaf69054 100644 --- a/packages/cli-core/src/lib/engine.ts +++ b/packages/cli-core/src/lib/engine.ts @@ -412,6 +412,8 @@ export interface DAppConnector { takeOffer(connectionId: string, txHex: string): Promise; /** Cancels open swap offers of this wallet's by spending their coins back to itself; the cancel, sealed, hex, pending until submitted. Refused when it wouldn't spend every coin of every offer. */ cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise; + /** Whether the wallet holds, unspent and in none of its open swap offers, a shielded coin of `token` worth exactly `amount`. */ + holdsFreeCoin(token: string, amount: bigint): boolean; /** True if any connection has a balanced-but-not-submitted transaction. */ hasPendingTxs(): boolean; dispose(): void; diff --git a/packages/cli-core/src/lib/sdk-errors.ts b/packages/cli-core/src/lib/sdk-errors.ts index 5978b88d..c6c039af 100644 --- a/packages/cli-core/src/lib/sdk-errors.ts +++ b/packages/cli-core/src/lib/sdk-errors.ts @@ -21,6 +21,7 @@ import { TransactionRefusedError, type RefusalCode, } from './errors.ts'; +import { OfferCoinsInUseError } from './open-offers.ts'; import { carriesOwnCode, isTransportFailure } from './transport-failure.ts'; /** @@ -75,6 +76,26 @@ export function isDustShortage(err: unknown): boolean { return false; } +/** + * mn's coin picker refused inside the SDK's balancing: the only coins left + * that could pay are held by open swap offers. The SDK wraps what its picker + * throws (an `OtherWalletError` with it as the cause, inside a FiberFailure), + * so the refusal is found among the causes; undefined when there is none. + */ +export function heldCoinRefusalOf(err: unknown): OfferCoinsInUseError | undefined { + const seen = new Set(); + const pending: unknown[] = [err]; + while (pending.length > 0) { + const current = pending.pop(); + if (!current || typeof current !== 'object' || seen.has(current)) continue; + seen.add(current); + if (current instanceof OfferCoinsInUseError) return current; + const e = current as Record; + pending.push(e.cause, e[FIBER_FAILURE_CAUSE], e.error, e.defect, e.left, e.right); + } + return undefined; +} + /** What a Dust shortage carries when the wallet worked out what the fee would take. */ export interface DustShortfall { /** Dust (Specks) the wallet has to hold before the fee can be paid. */ @@ -145,7 +166,7 @@ export function isSdkInsufficientFundsError(err: any): boolean { * facade restarts for it crashed the ledger WASM ("unreachable"). */ export function isColdStartRace(err: unknown): boolean { - return isSdkInsufficientFundsError(err) && !isDustShortage(err); + return isSdkInsufficientFundsError(err) && !isDustShortage(err) && heldCoinRefusalOf(err) === undefined; } /** The wallet SDK's message on the error it wraps a node's refusal in, at each level. */ @@ -277,6 +298,8 @@ const carriesCode = (err: unknown): boolean => !isConnectorApiError(err) && carr */ export function toEngineError(err: unknown): unknown { if (err instanceof TransactionRefusedError) return err; + const held = heldCoinRefusalOf(err); + if (held !== undefined) return held; const reason = nodeRefusalOf(err); if (reason !== undefined) return new TransactionRefusedError(reason, { cause: err, code: refusalCodeOf(reason) }); const marked = mnCodeOf(err); @@ -293,7 +316,7 @@ export function toEngineError(err: unknown): unknown { */ export function withEngineCode(err: unknown): unknown { if (err === null || typeof err !== 'object' || isConnectorApiError(err) || carriesCode(err) || mnCodeOf(err) !== undefined) return err; - const code = engineCodeOf(err); + const code = heldCoinRefusalOf(err)?.code ?? engineCodeOf(err); if (code !== undefined) Object.defineProperty(err, MN_CODE, { value: code, enumerable: false, configurable: true, writable: true }); return err; } diff --git a/packages/cli-core/src/lib/wallet-session.ts b/packages/cli-core/src/lib/wallet-session.ts index ede4d0f5..ea80f4bf 100644 --- a/packages/cli-core/src/lib/wallet-session.ts +++ b/packages/cli-core/src/lib/wallet-session.ts @@ -87,6 +87,14 @@ export interface WalletSession { * hex), to submit. Check the terms and that the offer is live first. */ takeOffer(tx: string): Promise; + /** Whether the wallet holds a shielded coin worth exactly `leg`, unspent and in none of its open swap offers. */ + holdsFreeCoin(leg: SwapLeg): Promise; + /** + * Splits a coin: sends `leg` to the wallet's own shielded address, from its + * coins in no open offer, which leaves it a coin worth exactly that and the + * change (a fee in Dust). The transaction (sealed, hex), to submit. + */ + splitCoin(leg: SwapLeg): Promise; /** Cancels open swap offers of this wallet's by spending their coins back to itself (a fee in Dust); the cancel (sealed, hex), to submit. */ cancelOffers(offers: readonly OpenOffer[]): Promise; /** Signs `data` (hex, base64 or text, as `encoding` says) with the wallet's unshielded key. */ @@ -195,6 +203,17 @@ export function sessionOver( current.connector.handOffPendingTx(SESSION_CONNECTION, offer); return offer; }, + async holdsFreeCoin(leg) { + if (closed) throw new Error('The wallet session is closed'); + return current.connector.holdsFreeCoin(leg.token, leg.amount); + }, + async splitCoin(leg) { + const { shieldedAddress } = (await call('getShieldedAddresses', {})) as { shieldedAddress: string }; + return build(async () => ((await call('makeTransfer', { + desiredOutputs: [{ kind: 'shielded', type: leg.token, value: leg.amount, recipient: shieldedAddress }], + options: { payFees: true }, + })) as { tx: string }).tx); + }, async takeOffer(tx) { if (closed) throw new Error('The wallet session is closed'); return build(() => reported(() => current.connector.takeOffer(SESSION_CONNECTION, tx))); diff --git a/packages/engine-beta/src/__tests__/shielded-wallet.test.ts b/packages/engine-beta/src/__tests__/shielded-wallet.test.ts new file mode 100644 index 00000000..f76ec77a --- /dev/null +++ b/packages/engine-beta/src/__tests__/shielded-wallet.test.ts @@ -0,0 +1,6 @@ +// The beta engine's coin picking, through garbage collection (test-support/coin-picking-gc.ts). + +import { fileURLToPath } from 'node:url'; +import { coinPickingSurvivesCollection } from '../../../../test-support/coin-picking-gc.ts'; + +coinPickingSurvivesCollection('beta', fileURLToPath(new URL('../shielded-wallet.ts', import.meta.url))); diff --git a/packages/engine-beta/src/dapp-connector.ts b/packages/engine-beta/src/dapp-connector.ts index f102a620..c5202724 100644 --- a/packages/engine-beta/src/dapp-connector.ts +++ b/packages/engine-beta/src/dapp-connector.ts @@ -579,28 +579,31 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } /** - * Cancels open swap offers of this wallet's: sends its whole balance of - * each token they give back to its own shielded address, which spends the - * offers' coins (it costs a fee in Dust). Refused, and nothing kept, when - * the transaction doesn't spend every coin of every offer (one already - * taken, or coins this wallet no longer sees). Held pending for the - * connection until it is submitted. + * Cancels open swap offers of this wallet's: sends the value of the offers' + * coins back to its own shielded address, spending exactly those coins (the + * coin picker allows no other while the cancel is built), for a fee in Dust. + * Its other open offers stay live. Refused, and nothing kept, when the + * wallet no longer holds every coin of every offer (one already taken), or + * the transaction doesn't spend them all. Held pending for the connection + * until it is submitted. */ async function cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise { assertWalletStarted(); const state = getState(); - const tokens = [...new Set(offers.map((offer) => offer.terms.give.token))]; - const outputs = tokens.map((type) => { - const amount = state.shielded.balances[type] ?? 0n; - if (amount === 0n) throw createApiError('InvalidRequest', `This wallet holds none of token ${type}: the offer's coins are gone (it was taken)`); - return { type, amount, receiverAddress: state.shielded.address }; - }); + const held = new Map(state.shielded.availableCoins.map((available) => [available.nullifier.toLowerCase(), available.coin])); + const amounts = new Map(); + for (const nullifier of offers.flatMap((offer) => offer.nullifiers)) { + const coin = held.get(nullifier.toLowerCase()); + if (coin === undefined) throw createApiError('InvalidRequest', "This wallet no longer holds the offer's coins: it was taken"); + amounts.set(coin.type, (amounts.get(coin.type) ?? 0n) + coin.value); + } + const outputs = [...amounts].map(([type, amount]) => ({ type, amount, receiverAddress: state.shielded.address })); const context: RpcHandlerContext = { notify: () => {}, connectionId, requestId: 0, metadata: {} }; const tracker = makeTracker('cancelOffers', context); tracker.start('approve'); await requireApproval('cancelOffers', offers.map((offer) => ({ label: 'Cancel', value: `${offer.id.slice(0, 16)}… (${describeLeg(offer.terms.give)})` })), context); tracker.start('building'); - const recipe = await withDustRetry(() => facade.transferTransaction([{ type: 'shielded' as const, outputs }], secretKeys, { ttl: createTtl() })); + const recipe = await bundle.coinPicking.cancelling(offers, () => withDustRetry(() => facade.transferTransaction([{ type: 'shielded' as const, outputs }], secretKeys, { ttl: createTtl() }))); const { hex, finalized } = await processRecipe(recipe, tracker, offers.map((offer) => offer.id)); const spent = new Set(spentNullifiers(hex).map((n) => n.toLowerCase())); if (!offers.every((offer) => offer.nullifiers.every((n) => spent.has(n.toLowerCase())))) { @@ -611,6 +614,12 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return hex; } + /** Whether the wallet holds a shielded coin of `token` worth exactly `amount`, unspent and in none of its open swap offers. */ + function holdsFreeCoin(token: string, amount: bigint): boolean { + const held = new Set((options.openOffers?.() ?? []).flatMap((offer) => offer.nullifiers.map((n) => n.toLowerCase()))); + return getState().shielded.availableCoins.some((available) => available.coin.type === token && available.coin.value === amount && !held.has(available.nullifier.toLowerCase())); + } + /** Encode an SDK address object to bech32m string. */ function encodeAddress(address: any): string { return MidnightBech32m.encode(networkId, address).asString(); @@ -1108,5 +1117,5 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } // Each handler answers with its failure marked by mn's code, its message and causes as they were. - return { handlers: markingEngineCodes(handlers), revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; + return { handlers: markingEngineCodes(handlers), revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, holdsFreeCoin, hasPendingTxs, dispose }; } diff --git a/packages/engine-beta/src/facade.ts b/packages/engine-beta/src/facade.ts index 52deb33e..eb659b5b 100644 --- a/packages/engine-beta/src/facade.ts +++ b/packages/engine-beta/src/facade.ts @@ -1,4 +1,3 @@ -import { ShieldedWallet } from '@midnightntwrk/wallet-sdk-shielded'; import { getNetworkId, type WalletCacheData, DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, SYNC_TIMEOUT_MS, PRE_SEND_SYNC_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/engine'; import { type NoticeSink, type NetworkConfig, type VerboseLog, CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { @@ -22,6 +21,10 @@ import { makeDefaultSubmissionService } from '@midnightntwrk/wallet-sdk-capabili import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; import { assertNetworkAnswers, isStreamEmpty } from '@kuiralabs/midnight-chain'; +import { readOpenOffers, type NetworkName } from '@kuiralabs/midnight-cli-core'; +import type { CoinPicking } from '@kuiralabs/midnight-cli-core/engine'; +import { PickingShieldedWallet, shieldedCoinPicking, type ShieldedCoin } from './shielded-wallet.ts'; +import { deriveUnshieldedAddress } from './derive-address.ts'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust @@ -46,6 +49,8 @@ export interface FacadeBundle { secretKeys: WalletSecretKeys; /** Active subscription that keeps shareReplay buffers alive. Cleaned up by stopFacade. */ keepAlive?: rx.Subscription; + /** How the shielded wallet picks the coins a spend uses: never an open offer's, except in its cancel. */ + coinPicking: CoinPicking; /** Whether the facade was restored from cached state (vs built from scratch). */ restoredFromCache?: boolean; /** The network's indexer (HTTP), for reads the facade doesn't offer, like the chain's clock. */ @@ -90,6 +95,10 @@ export async function buildFacade( dustSecretKey: ledger.DustSecretKey.fromSeed(deriveDustSeed(seedBuffer)), }; const keystore = createKeystore({ kind: 'schnorr', secret: deriveUnshieldedSeed(seedBuffer) }, networkId); + // The wallet's open swap offers, as mn's record under the root keeps them (the network id is the network's name). + const network = networkId as NetworkName; + const walletAddress = deriveUnshieldedAddress(seedBuffer, network); + const coinPicking = shieldedCoinPicking(deriveShieldedSeed(seedBuffer), () => readOpenOffers(root, network, walletAddress)); // Merged configuration for WalletFacade.init() — all wallet types // and services draw from this single config object. @@ -113,7 +122,7 @@ export async function buildFacade( const initFresh = () => WalletFacade.init({ configuration, submissionService: (config) => submissionOnDemand(config.relayURL), - shielded: (cfg) => ShieldedWallet(cfg).startWithSecretKeys(secretKeys.shieldedSecretKeys), + shielded: (cfg) => PickingShieldedWallet(cfg, coinPicking).startWithSecretKeys(secretKeys.shieldedSecretKeys), unshielded: (cfg) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(keystore)), dust: (cfg) => DustWallet(cfg).startWithSecretKey(secretKeys.dustSecretKey, ledger.LedgerParameters.initialParameters().dust), }); @@ -136,7 +145,7 @@ export async function buildFacade( facade = await WalletFacade.init({ configuration, submissionService: (config) => submissionOnDemand(config.relayURL), - shielded: (cfg) => ShieldedWallet(cfg).restore(effectiveCache.shielded), + shielded: (cfg) => PickingShieldedWallet(cfg, coinPicking).restore(effectiveCache.shielded), unshielded: (cfg) => UnshieldedWallet(cfg).restore(effectiveCache.unshielded), dust: (cfg) => DustWallet(cfg).restore(effectiveCache.dust), }); @@ -152,7 +161,7 @@ export async function buildFacade( facade = await initFresh(); } - return { facade, keystore, secretKeys, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; + return { facade, keystore, secretKeys, coinPicking, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; } /** What the facade submits through, as WalletFacade.init takes it. */ diff --git a/packages/engine-beta/src/shielded-wallet.ts b/packages/engine-beta/src/shielded-wallet.ts new file mode 100644 index 00000000..e186b5c5 --- /dev/null +++ b/packages/engine-beta/src/shielded-wallet.ts @@ -0,0 +1,46 @@ +// The shielded wallet the facade wraps, built as the beta SDK's +// `ShieldedWallet` builds it (one ledger-9 variant) with mn's coin picker: a +// spend skips the coins of the wallet's open swap offers, except in their +// cancel, and takes a coin of the exact amount when there is one. + +import { CustomShieldedWallet, type ShieldedWallet, type ShieldedWalletClass } from '@midnightntwrk/wallet-sdk-shielded'; +import { V1Builder } from '@midnightntwrk/wallet-sdk-shielded/v1'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { createCoinPicking, type CoinPicking } from '@kuiralabs/midnight-cli-core/engine'; +import type { OpenOffer } from '@kuiralabs/midnight-cli-core'; + +/** A shielded coin as the SDK's balancer hands it to the picker. */ +export type ShieldedCoin = ledger.QualifiedShieldedCoinInfo; + +/** + * A coin's nullifier under the wallet's shielded seed. The keys are derived + * for each one and cleared after: a key held on its own is cleared by the + * ledger once the keys it came from are collected ("Coin secret key was + * cleared"), which broke a spend rebuilt after a wait for Dust. + */ +export function shieldedNullifier(shieldedSeed: Uint8Array, coin: ShieldedCoin): string { + const keys = ledger.ZswapSecretKeys.fromSeed(shieldedSeed); + try { + return ledger.coinNullifier({ type: coin.type, nonce: coin.nonce, value: coin.value }, keys.coinSecretKey); + } finally { + keys.clear(); + } +} + +/** The coin picking of the wallet with this shielded seed, whose open offers `openOffers` reads. */ +export function shieldedCoinPicking(shieldedSeed: Uint8Array, openOffers: () => readonly OpenOffer[]): CoinPicking { + return createCoinPicking(openOffers, (coin) => shieldedNullifier(shieldedSeed, coin)); +} + +/** What the SDK's own `ShieldedWallet` is built from. */ +type ShieldedConfiguration = Parameters[0]; + +/** The shielded wallet class for `configuration` (the facade's), spending as `picking` picks. */ +export function PickingShieldedWallet(configuration: ShieldedConfiguration, picking: CoinPicking): ShieldedWalletClass { + return CustomShieldedWallet( + configuration, + new V1Builder() + .withDefaults() + .withCoinSelection(() => (coins, tokenType, amountNeeded) => picking.pick(coins, tokenType, amountNeeded)), + ); +} diff --git a/packages/engine-rc/src/__tests__/shielded-wallet.test.ts b/packages/engine-rc/src/__tests__/shielded-wallet.test.ts new file mode 100644 index 00000000..050e3d2b --- /dev/null +++ b/packages/engine-rc/src/__tests__/shielded-wallet.test.ts @@ -0,0 +1,6 @@ +// The rc engine's coin picking, through garbage collection (test-support/coin-picking-gc.ts). + +import { fileURLToPath } from 'node:url'; +import { coinPickingSurvivesCollection } from '../../../../test-support/coin-picking-gc.ts'; + +coinPickingSurvivesCollection('rc', fileURLToPath(new URL('../shielded-wallet.ts', import.meta.url))); diff --git a/packages/engine-rc/src/dapp-connector.ts b/packages/engine-rc/src/dapp-connector.ts index a37a3fb2..ef948704 100644 --- a/packages/engine-rc/src/dapp-connector.ts +++ b/packages/engine-rc/src/dapp-connector.ts @@ -576,28 +576,31 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } /** - * Cancels open swap offers of this wallet's: sends its whole balance of - * each token they give back to its own shielded address, which spends the - * offers' coins (it costs a fee in Dust). Refused, and nothing kept, when - * the transaction doesn't spend every coin of every offer (one already - * taken, or coins this wallet no longer sees). Held pending for the - * connection until it is submitted. + * Cancels open swap offers of this wallet's: sends the value of the offers' + * coins back to its own shielded address, spending exactly those coins (the + * coin picker allows no other while the cancel is built), for a fee in Dust. + * Its other open offers stay live. Refused, and nothing kept, when the + * wallet no longer holds every coin of every offer (one already taken), or + * the transaction doesn't spend them all. Held pending for the connection + * until it is submitted. */ async function cancelOffers(connectionId: string, offers: readonly OpenOffer[]): Promise { assertWalletsOnLedger9(); const state = getState(); - const tokens = [...new Set(offers.map((offer) => offer.terms.give.token))]; - const outputs = tokens.map((type) => { - const amount = state.shielded.balances[type] ?? 0n; - if (amount === 0n) throw createApiError('InvalidRequest', `This wallet holds none of token ${type}: the offer's coins are gone (it was taken)`); - return { type, amount, receiverAddress: state.shielded.address }; - }); + const held = new Map(state.shielded.availableCoins.map((available) => [available.nullifier.toLowerCase(), available.coin])); + const amounts = new Map(); + for (const nullifier of offers.flatMap((offer) => offer.nullifiers)) { + const coin = held.get(nullifier.toLowerCase()); + if (coin === undefined) throw createApiError('InvalidRequest', "This wallet no longer holds the offer's coins: it was taken"); + amounts.set(coin.type, (amounts.get(coin.type) ?? 0n) + coin.value); + } + const outputs = [...amounts].map(([type, amount]) => ({ type, amount, receiverAddress: state.shielded.address })); const context: RpcHandlerContext = { notify: () => {}, connectionId, requestId: 0, metadata: {} }; const tracker = makeTracker('cancelOffers', context); tracker.start('approve'); await requireApproval('cancelOffers', offers.map((offer) => ({ label: 'Cancel', value: `${offer.id.slice(0, 16)}… (${describeLeg(offer.terms.give)})` })), context); tracker.start('building'); - const recipe = await withDustRetry(() => facade.transferTransaction([{ type: 'shielded' as const, outputs }], { ttl: createTtl() })); + const recipe = await bundle.coinPicking.cancelling(offers, () => withDustRetry(() => facade.transferTransaction([{ type: 'shielded' as const, outputs }], { ttl: createTtl() }))); const { hex, finalized } = await processRecipe(recipe, tracker, offers.map((offer) => offer.id)); const spent = new Set(spentNullifiers(hex).map((n) => n.toLowerCase())); if (!offers.every((offer) => offer.nullifiers.every((n) => spent.has(n.toLowerCase())))) { @@ -608,6 +611,12 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto return hex; } + /** Whether the wallet holds a shielded coin of `token` worth exactly `amount`, unspent and in none of its open swap offers. */ + function holdsFreeCoin(token: string, amount: bigint): boolean { + const held = new Set((options.openOffers?.() ?? []).flatMap((offer) => offer.nullifiers.map((n) => n.toLowerCase()))); + return getState().shielded.availableCoins.some((available) => available.coin.type === token && available.coin.value === amount && !held.has(available.nullifier.toLowerCase())); + } + /** Encode an SDK address object to bech32m string. */ function encodeAddress(address: any): string { return MidnightBech32m.encode(networkId, address).asString(); @@ -1105,5 +1114,5 @@ export function createDAppConnector(options: DAppConnectorOptions): DAppConnecto } // Each handler answers with its failure marked by mn's code, its message and causes as they were. - return { handlers: markingEngineCodes(handlers), revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, hasPendingTxs, dispose }; + return { handlers: markingEngineCodes(handlers), revertPendingTxs, handOffPendingTx, takeOffer, cancelOffers, holdsFreeCoin, hasPendingTxs, dispose }; } diff --git a/packages/engine-rc/src/facade.ts b/packages/engine-rc/src/facade.ts index 9b076d94..79ffa89e 100644 --- a/packages/engine-rc/src/facade.ts +++ b/packages/engine-rc/src/facade.ts @@ -1,4 +1,3 @@ -import { ShieldedWallet } from '@midnightntwrk/wallet-sdk/shielded'; import { getNetworkId, type WalletCacheData, DUST_COST_OVERHEAD, DUST_FEE_BLOCKS_MARGIN, SYNC_TIMEOUT_MS, PRE_SEND_SYNC_TIMEOUT_MS } from '@kuiralabs/midnight-cli-core/engine'; import { type NoticeSink, type NetworkConfig, type VerboseLog, CancelledError, SyncTimeoutError, throwIfCancelled } from '@kuiralabs/midnight-cli-core'; import { @@ -24,6 +23,10 @@ import { FORK_SCHEDULE } from './fork-schedule.ts'; import { deriveShieldedSeed, deriveUnshieldedSeed, deriveDustSeed } from './derivation.ts'; import { loadDustCache, dustPublicKeyHex, type DustCacheEntry } from './dust-direct-cache.ts'; import { assertNetworkAnswers, isStreamEmpty } from '@kuiralabs/midnight-chain'; +import { readOpenOffers, type NetworkName } from '@kuiralabs/midnight-cli-core'; +import type { CoinPicking } from '@kuiralabs/midnight-cli-core/engine'; +import { PickingShieldedWallet, shieldedCoinPicking, type ShieldedCoin } from './shielded-wallet.ts'; +import { deriveUnshieldedAddress } from './derive-address.ts'; export type SyncMode = 'full' | 'lite' | 'no-dust'; // full = shielded + unshielded + dust @@ -43,6 +46,8 @@ export interface FacadeBundle { seeds: WalletSeeds; /** The shielded and dust wallets the facade wraps, kept so a restored facade can be started from seeds. */ seedStartable: { shielded: SeedStartable; dust: SeedStartable }; + /** How the shielded wallet picks the coins a spend uses: never an open offer's, except in its cancel. */ + coinPicking: CoinPicking; /** Active subscription that keeps shareReplay buffers alive. Cleaned up by stopFacade. */ keepAlive?: rx.Subscription; /** Whether the facade was restored from cached state (vs built from scratch). */ @@ -90,6 +95,10 @@ export async function buildFacade( dust: deriveDustSeed(seedBuffer), }; const keystore = createKeystore({ kind: 'schnorr', secret: seeds.unshielded }, networkId); + // The wallet's open swap offers, as mn's record under the root keeps them (the network id is the network's name). + const network = networkId as NetworkName; + const walletAddress = deriveUnshieldedAddress(seedBuffer, network); + const coinPicking = shieldedCoinPicking(seeds.shielded, () => readOpenOffers(root, network, walletAddress)); // Merged configuration for WalletFacade.init() — all wallet types // and services draw from this single config object. @@ -120,7 +129,7 @@ export async function buildFacade( const initFresh = () => WalletFacade.init({ configuration, submissionService: (config) => submissionOnDemand(config.relayURL), - shielded: async (cfg) => (shielded = await ShieldedWallet(cfg).startWithSeed(seeds.shielded)), + shielded: async (cfg) => (shielded = await PickingShieldedWallet(cfg, coinPicking).startWithSeed(seeds.shielded)), unshielded: (cfg) => UnshieldedWallet(cfg).startWithPublicKey(PublicKey.fromKeyStore(keystore)), dust: async (cfg) => (dust = await DustWallet(cfg).startWithSeed(seeds.dust)), }); @@ -143,7 +152,7 @@ export async function buildFacade( facade = await WalletFacade.init({ configuration, submissionService: (config) => submissionOnDemand(config.relayURL), - shielded: (cfg) => (shielded = ShieldedWallet(cfg).restore(effectiveCache.shielded)), + shielded: (cfg) => (shielded = PickingShieldedWallet(cfg, coinPicking).restore(effectiveCache.shielded)), unshielded: (cfg) => UnshieldedWallet(cfg).restore(effectiveCache.unshielded), dust: (cfg) => (dust = DustWallet(cfg).restore(effectiveCache.dust)), }); @@ -162,7 +171,7 @@ export async function buildFacade( if (!shielded || !dust) { throw new Error('Wallet facade was built without its shielded or dust wallet'); } - return { facade, keystore, seeds, seedStartable: { shielded, dust }, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; + return { facade, keystore, seeds, seedStartable: { shielded, dust }, coinPicking, restoredFromCache, indexerHttpUrl: networkConfig.indexer, indexerWsUrl: networkConfig.indexerWS }; } /** What the facade submits through, as WalletFacade.init takes it. */ diff --git a/packages/engine-rc/src/shielded-wallet.ts b/packages/engine-rc/src/shielded-wallet.ts new file mode 100644 index 00000000..81b47db8 --- /dev/null +++ b/packages/engine-rc/src/shielded-wallet.ts @@ -0,0 +1,59 @@ +// The shielded wallet the facade wraps, built as the SDK's `ShieldedWallet` +// builds it (a variant either side of the ledger-9 boundary, the chain asked +// which side it is on) with mn's coin picker on the ledger-9 side: a spend +// skips the coins of the wallet's open swap offers, except in their cancel, +// and takes a coin of the exact amount when there is one. The ledger-8 side +// keeps the SDK's picker: every network mn writes to is past the boundary. + +import { CustomForkingShieldedWallet, type ShieldedWallet, type ShieldedWalletClass } from '@midnightntwrk/wallet-sdk/shielded'; +import { V1Builder } from '@midnightntwrk/wallet-sdk/shielded/v1'; +import { Migration, V2Builder } from '@midnightntwrk/wallet-sdk/shielded/v2'; +import { makeIndexerChainVersionProbe } from '@midnightntwrk/wallet-sdk/capabilities'; +import * as ledger from '@midnightntwrk/ledger-v9'; +import { createCoinPicking, type CoinPicking } from '@kuiralabs/midnight-cli-core/engine'; +import type { OpenOffer } from '@kuiralabs/midnight-cli-core'; + +/** A shielded coin as the SDK's balancer hands it to the picker. */ +export type ShieldedCoin = ledger.QualifiedShieldedCoinInfo; + +/** + * A coin's nullifier under the wallet's shielded seed. The keys are derived + * for each one and cleared after: a key held on its own is cleared by the + * ledger once the keys it came from are collected ("Coin secret key was + * cleared"), which broke a spend rebuilt after a wait for Dust. + */ +export function shieldedNullifier(shieldedSeed: Uint8Array, coin: ShieldedCoin): string { + const keys = ledger.ZswapSecretKeys.fromSeed(shieldedSeed); + try { + return ledger.coinNullifier({ type: coin.type, nonce: coin.nonce, value: coin.value }, keys.coinSecretKey); + } finally { + keys.clear(); + } +} + +/** The coin picking of the wallet with this shielded seed, whose open offers `openOffers` reads. */ +export function shieldedCoinPicking(shieldedSeed: Uint8Array, openOffers: () => readonly OpenOffer[]): CoinPicking { + return createCoinPicking(openOffers, (coin) => shieldedNullifier(shieldedSeed, coin)); +} + +/** What the SDK's own `ShieldedWallet` is built from. */ +type ShieldedConfiguration = Parameters[0]; + +/** The shielded wallet class for `configuration` (the facade's), spending as `picking` picks. */ +export function PickingShieldedWallet(configuration: ShieldedConfiguration, picking: CoinPicking): ShieldedWalletClass { + const withProbe = { + ...configuration, + chainVersionProbe: configuration.chainVersionProbe ?? makeIndexerChainVersionProbe(configuration), + }; + return CustomForkingShieldedWallet( + withProbe, + { builder: new V1Builder().withDefaults(), configuration }, + { + builder: new V2Builder() + .withDefaults() + .withMigration(() => Migration.makeCrossLedgerMigration()) + .withCoinSelection(() => (coins, tokenType, amountNeeded) => picking.pick(coins, tokenType, amountNeeded)), + configuration, + }, + ); +} diff --git a/packages/wallet/api-report.md b/packages/wallet/api-report.md index 1ca80a2c..00340d62 100644 --- a/packages/wallet/api-report.md +++ b/packages/wallet/api-report.md @@ -73,18 +73,24 @@ export interface SwapOffersListed { readonly network: NetworkName; readonly offers: readonly ListedOffer[]; } +export interface CoinSplit { + readonly txHash: string; + readonly receipt?: Receipt; +} export interface MadeSwapOffer { readonly network: NetworkName; readonly id: string; readonly terms: SwapTerms; readonly expiresAt: Date; readonly file: string; + readonly split?: CoinSplit; } export declare function makeSwapOffer(host: Host, options: MakeSwapOfferOptions): Promise; export interface MakeSwapOfferOptions extends PaidCallOptions { terms: SwapTerms; expiresAt: Date; now?: Date; + receiptWaitMs?: number; } export interface SwapNetworkChosen { readonly kind: 'swap-network'; diff --git a/packages/wallet/src/__tests__/swap-lib.test.ts b/packages/wallet/src/__tests__/swap-lib.test.ts index e7a57d24..c052e411 100644 --- a/packages/wallet/src/__tests__/swap-lib.test.ts +++ b/packages/wallet/src/__tests__/swap-lib.test.ts @@ -16,7 +16,7 @@ import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; import { WebSocketServer } from 'ws'; -import { createHost, type Host, saveCliConfig, type ConnectOptions, type Payer, type PayingTarget, encodeOfferEnvelope, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; +import { createHost, type Host, saveCliConfig, type ConnectOptions, type Payer, type PayingTarget, encodeOfferEnvelope, readOpenOffers, recordOpenOffer, type OpenOffer, type WalletSession } from '@kuiralabs/midnight-cli-core'; import { rcEngine, rcKeys } from '../../../../test-support/rc-engine.ts'; import { loadInstalledEngine } from '../../../../test-support/test-host.ts'; import { makeSwapOffer } from '../lib/swap/make.ts'; @@ -220,6 +220,53 @@ describe('makeSwapOffer', () => { }); }); +describe('makeSwapOffer with a wallet that opens', () => { + /** A program's payer whose session is its own: it records each call, holds a free coin of exactly the amount from the start when `holdsAtFirst`, otherwise once it has submitted (the split), and makes the real offer. */ + function sessionPayer(holdsAtFirst: boolean) { + const calls: string[] = []; + let holds = holdsAtFirst; + const unused = async (): Promise => { throw new Error('not used by swap make'); }; + const session: WalletSession = { + network: 'undeployed', + addresses: unused, + balances: unused, + balanceTransaction: unused, + swap: unused, + makeOffer: async (give, want) => { calls.push(`makeOffer ${give.amount} ${want.amount}`); return SWAP_OFFER_HEX; }, + takeOffer: unused, + cancelOffers: unused, + holdsFreeCoin: async (leg) => { calls.push(`holdsFreeCoin ${leg.amount}`); return holds; }, + splitCoin: async (leg) => { calls.push(`splitCoin ${leg.amount}`); return 'split-tx'; }, + sign: unused, + submit: async (tx) => { calls.push(`submit ${tx}`); holds = true; return 'ab'.repeat(32); }, + readTransaction: unused, + close: async () => { calls.push('close'); }, + }; + const payer: Payer = { assertCanPay: unused, serve: unused, connect: async () => session }; + return { payer, calls }; + } + + it('with no free coin of exactly the amount, splits one first, waits for it, then makes the offer from it', async () => { + alice(); + const { payer, calls } = sessionPayer(false); + const said: unknown[] = []; + const made = await makeSwapOffer(host, { ...on(), terms: TERMS, expiresAt: new Date(NOW.getTime() + 60_000), now: NOW, payer, receiptWaitMs: 0, onProgress: (event) => said.push(event) }); + expect(calls).toEqual(['holdsFreeCoin 10', 'splitCoin 10', 'submit split-tx', 'holdsFreeCoin 10', 'makeOffer 10 7', 'close']); + expect(made.split).toEqual({ txHash: 'ab'.repeat(32) }); + expect(made.id).toBe(OFFER.id); + expect(said).toContainEqual({ kind: 'done', message: 'Coin split' }); + expect(readOpenOffers(root, 'undeployed', ADDRESS).map((o) => o.id)).toEqual([OFFER.id]); + }); + + it('with a free coin of exactly the amount, makes the offer with no split', async () => { + alice(); + const { payer, calls } = sessionPayer(true); + const made = await makeSwapOffer(host, { ...on(), terms: TERMS, expiresAt: new Date(NOW.getTime() + 60_000), now: NOW, payer, receiptWaitMs: 0 }); + expect(calls).toEqual(['holdsFreeCoin 10', 'makeOffer 10 7', 'close']); + expect(made.split).toBeUndefined(); + }); +}); + describe('cancelSwapOffer', () => { it('opens the payer\'s wallet with its shielded side synced, for the wallet named', async () => { alice(); diff --git a/packages/wallet/src/commands/swap.definition.ts b/packages/wallet/src/commands/swap.definition.ts index e31bdf43..43bb0628 100644 --- a/packages/wallet/src/commands/swap.definition.ts +++ b/packages/wallet/src/commands/swap.definition.ts @@ -99,7 +99,8 @@ export const swapDefinition: CommandDefinition = { usage: 'midnight swap [options]', flags: [ 'make Make an offer: give --give of --give-token for --want of --want-token;', - ' writes the offer file to hand the taker', + ' writes the offer file to hand the taker. The offer holds one coin worth', + ' exactly --give: with none free, this wallet splits one first (a fee in Dust)', 'inspect What an offer file offers, whether it is still live, and its expiry', 'take Take an offer at the terms agreed (--give, --give-token, --want,', ' --want-token, as the maker states them); this wallet pays the fee', @@ -138,6 +139,7 @@ export const swapDefinition: CommandDefinition = { receipt: 'The transaction once the indexer lists it: blockHeight, blockHash, blockTime, fee (DUST, exact), feeSpecks, result; null when it has not within 60 s (take, and cancel when submitted)', receiptMissing: 'Why receipt is null; check later with midnight tx status ', cancelled: 'Whether a cancel was submitted; false when the offer was taken already (cancel)', + split: 'The split made first when no free coin was worth exactly the amount given: txHash, and receipt or receiptMissing as above; absent when none was needed (make)', offers: 'The wallet\'s open offers, each with whether it is expired or taken (list)', }, }, @@ -150,7 +152,7 @@ export const swapDefinition: CommandDefinition = { tools: [ { name: 'midnight_swap_make', - description: 'Make a swap offer: the wallet gives one shielded token for another, and the offer file it writes is what to hand the taker (returns pending token). The taker pays the fee.', + description: 'Make a swap offer: the wallet gives one shielded token for another, and the offer file it writes is what to hand the taker (returns pending token). The taker pays the swap\'s fee; with no free coin worth exactly the amount given, the wallet first splits one, for a fee in Dust.', annotations: { destructiveHint: true, openWorldHint: true }, params: [ { flag: 'give' }, @@ -167,7 +169,7 @@ export const swapDefinition: CommandDefinition = { confirmation: { describe: (params) => { const { network, wallet } = confirmationTarget(params); - return `Offer ${describeTerms(params)} from wallet ${wallet} on ${network}; its coins stay committed until the offer is taken`; + return `Offer ${describeTerms(params)} from wallet ${wallet} on ${network}, splitting a coin first (a fee in Dust) when none is worth exactly the amount given; that coin stays committed until the offer is taken`; }, async check(_params, call) { const { prepareMake } = await import('../lib/swap/request.ts'); diff --git a/packages/wallet/src/commands/swap.guidance.ts b/packages/wallet/src/commands/swap.guidance.ts index 2290488e..ea50759a 100644 --- a/packages/wallet/src/commands/swap.guidance.ts +++ b/packages/wallet/src/commands/swap.guidance.ts @@ -28,7 +28,7 @@ named by their raw type (64 hex) and amounts are in the smallest unit. midnight swap make --give --give-token --want --want-token [--expires-in ] [--out ] [--json] - → { id, file, terms, expiresAt, network } + → { id, file, terms, expiresAt, network, split? } midnight swap inspect [--json] → { id, terms, expiresAt, live, expired, network } midnight swap take --give --give-token --want --want-token [--json] @@ -43,8 +43,11 @@ wants). Before the taker's wallet builds anything, take refuses an offer whose terms differ (TERMS_MISMATCH), one past its expiry (OFFER_EXPIRED), one already taken, and a file that is not an offer or says other than its transaction (NOT_AN_OFFER). An offer's coins stay committed until it is -taken: the maker's own spends that would use them are refused -(OFFER_COINS_IN_USE). The expiry is mn's own: the chain lets an expired +taken. make spends one coin worth exactly what it gives: when the wallet +holds none outside its open offers, it first splits one (a transfer to +itself, a fee in Dust; split gives its txHash and receipt). The wallet's +other spends leave open offers' coins alone, and are refused +(OFFER_COINS_IN_USE) only when nothing else could pay. The expiry is mn's own: the chain lets an expired offer be taken until its maker cancels it, which spends its coins back to the maker (a fee in Dust). diff --git a/packages/wallet/src/commands/swap.ts b/packages/wallet/src/commands/swap.ts index c1f01428..1209032e 100644 --- a/packages/wallet/src/commands/swap.ts +++ b/packages/wallet/src/commands/swap.ts @@ -51,10 +51,15 @@ export default async function swapCommand(args: ParsedArgs, ctx: CallContext): P const file = out ?? `offer-${made.id.slice(0, 16)}.json`; writeFileSync(file, made.file, { flag: 'wx' }); if (jsonMode) { - ctx.output.result({ subcommand: 'make', network: made.network, id: made.id, file, terms: termsJson(made.terms), expiresAt: made.expiresAt.toISOString() }); + const split = made.split === undefined ? {} : { split: { txHash: made.split.txHash, ...(made.split.receipt === undefined ? {} : receiptJson(made.split.receipt)) } }; + ctx.output.result({ subcommand: 'make', network: made.network, id: made.id, file, terms: termsJson(made.terms), expiresAt: made.expiresAt.toISOString(), ...split }); return; } ctx.output.stdout(file + '\n'); + if (made.split !== undefined) { + ctx.output.stderr('\n' + keyValue('Split', `${made.split.txHash} (a coin of exactly ${made.terms.give.amount}, for the offer)`) + '\n'); + if (made.split.receipt !== undefined) ctx.output.stderr(receiptText(made.split.receipt, made.split.txHash)); + } ctx.output.stderr('\n' + keyValue('Offer', made.id) + '\n'); ctx.output.stderr(keyValue('File', file) + '\n'); ctx.output.stderr(keyValue('Expires', made.expiresAt.toISOString()) + '\n'); diff --git a/packages/wallet/src/index.ts b/packages/wallet/src/index.ts index 6b476da4..caec9c9a 100644 --- a/packages/wallet/src/index.ts +++ b/packages/wallet/src/index.ts @@ -20,7 +20,7 @@ export { } from './lib/swap/inspect.ts'; export { type ListSwapOffersOptions, listSwapOffers, type SwapOffersListed } from './lib/swap/list.ts'; export { - type MadeSwapOffer, makeSwapOffer, type MakeSwapOfferOptions, type SwapNetworkChosen + type CoinSplit, type MadeSwapOffer, makeSwapOffer, type MakeSwapOfferOptions, type SwapNetworkChosen } from './lib/swap/make.ts'; export { cancelOffer, type CancelOutcome, type MadeOffer, makeOffer, NoSuchOfferError, type ReadOffer, diff --git a/packages/wallet/src/lib/swap/make.ts b/packages/wallet/src/lib/swap/make.ts index b42b4fd9..925ce516 100644 --- a/packages/wallet/src/lib/swap/make.ts +++ b/packages/wallet/src/lib/swap/make.ts @@ -1,10 +1,15 @@ // Making a swap offer: the maker's wallet proves its half, and the offer -// comes back as an offer file's text for the maker to hand to a taker. +// comes back as an offer file's text for the maker to hand to a taker. An +// offer holds every coin it spends until it is taken or cancelled, so when no +// free coin is worth exactly what it gives, the wallet first splits one (a +// transfer to itself), and the offer holds only the coin the split made. import { type Host, throwIfCancelled, type NetworkName, networkTargetOf, progressSteps, withCallSdkWarnings, type SwapTerms } from '@kuiralabs/midnight-cli-core'; import { networkChoiceOf } from '../wallet/wallet-call.ts'; import type { PaidCallOptions } from '../wallet/paid-call.ts'; -import { makeOffer } from './offers.ts'; +import { type Receipt, RECEIPT_WAIT_MS } from '@kuiralabs/midnight-chain'; +import { receiptOfSubmitted } from '../wallet/submit-steps.ts'; +import { awaitFreeCoin, makeOffer } from './offers.ts'; import { offerWalletAddress, withSwapSession } from './swap-session.ts'; /** The swap's network is known: its wallet opens next. */ @@ -20,6 +25,15 @@ export interface MakeSwapOfferOptions extends PaidCallOptions expiresAt: Date; /** When the offer is made, as mn's record of the wallet's open offers keeps it; the time of the call when not given. */ now?: Date; + /** How long to wait for the indexer to list a split, in milliseconds: RECEIPT_WAIT_MS when not given; 0 does not wait. */ + receiptWaitMs?: number; +} + +/** The split that left the wallet a coin worth exactly what the offer gives. */ +export interface CoinSplit { + readonly txHash: string; + /** The split once the indexer lists it, or why it is missing; absent when `receiptWaitMs` is 0. */ + readonly receipt?: Receipt; } /** An offer made. */ @@ -32,28 +46,45 @@ export interface MadeSwapOffer { readonly expiresAt: Date; /** The offer file's text, to hand to the taker. */ readonly file: string; + /** The split made first, when no free coin was worth exactly what the offer gives; absent when none was needed. */ + readonly split?: CoinSplit; } /** * Makes a swap offer with the payer's wallet: proves its half of the swap * (it gives `terms.give` and is paid `terms.want`), and records the offer * among the wallet's open offers so its later spends don't cancel it unawares. - * Its coins stay committed until the offer is taken or cancelled. + * The offer spends one coin worth exactly `terms.give`: when the wallet holds + * none outside its open offers, it first splits one (a transfer to itself, + * paying a fee in Dust), waits for the indexer to list it and for the wallet + * to hold the new coin. The coin stays committed until the offer is taken or + * cancelled. A cancel after the split leaves the split made and no offer. */ export async function makeSwapOffer(host: Host, options: MakeSwapOfferOptions): Promise { const { terms, expiresAt, signal, onProgress } = options; const now = options.now ?? new Date(); + const receiptWaitMs = options.receiptWaitMs ?? RECEIPT_WAIT_MS; throwIfCancelled(signal); const target = networkTargetOf(host, networkChoiceOf(options)); - const { network, root } = target; + const { network, root, networkConfig } = target; onProgress?.({ kind: 'swap-network', network }); const address = await offerWalletAddress(host, root, options.wallet, network); return withCallSdkWarnings(host.sdkWarnings, options.sdkWarnings, (sdkWarnings) => withSwapSession(target, options, sdkWarnings, async (session) => { const steps = progressSteps(onProgress); + let split: CoinSplit | undefined; + if (!(await session.holdsFreeCoin(terms.give))) { + steps.start('Splitting a coin worth exactly what the offer gives (a transfer to this wallet)...'); + const txHash = await session.submit(await session.splitCoin(terms.give)); + const receipt = await receiptOfSubmitted(networkConfig.indexer, txHash, steps, signal, receiptWaitMs, 'Coin split'); + split = { txHash, ...(receipt === undefined ? {} : { receipt }) }; + steps.start('Waiting for the wallet to hold the new coin...'); + await awaitFreeCoin(session, terms.give, signal); + steps.done('New coin held'); + } steps.start('Making the offer (proving its half)...'); const made = await makeOffer(session, await host.engines.for(session.network), root, address, terms, expiresAt, now); steps.done('Offer made'); - return { network, id: made.envelope.id, terms: made.envelope.terms, expiresAt, file: made.file }; + return { network, id: made.envelope.id, terms: made.envelope.terms, expiresAt, file: made.file, ...(split === undefined ? {} : { split }) }; })); } diff --git a/packages/wallet/src/lib/swap/offers.ts b/packages/wallet/src/lib/swap/offers.ts index 4b14f3ad..0692038e 100644 --- a/packages/wallet/src/lib/swap/offers.ts +++ b/packages/wallet/src/lib/swap/offers.ts @@ -5,7 +5,7 @@ // what the file says, that the terms are the agreed ones, that the maker's // expiry hasn't passed, and that none of its coins is spent. -import { sdkSetOf, type Engine, type HostEngines, type NetworkConfig, type NetworkName, type WalletSession, UsageError, checkTerms, type OfferContents, type SwapTerms, assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, type OfferEnvelope, closeOpenOffers, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; +import { sdkSetOf, sleep, SyncTimeoutError, type SwapLeg, type Engine, type HostEngines, type NetworkConfig, type NetworkName, type WalletSession, UsageError, checkTerms, type OfferContents, type SwapTerms, assertEnvelopeMatches, assertOfferUnexpired, decodeOfferEnvelope, encodeOfferEnvelope, type OfferEnvelope, closeOpenOffers, readOpenOffers, recordOpenOffer, type OpenOffer } from '@kuiralabs/midnight-cli-core'; import { spendsOf, type CoinSpend } from '@kuiralabs/midnight-chain'; /** An offer made: its file's text and what it is. */ @@ -29,6 +29,26 @@ export async function makeOffer(session: WalletSession, engine: Engine, root: st return { envelope, file: encodeOfferEnvelope(envelope) }; } +/** How often the wallet is asked whether it holds the coin a split made, in milliseconds. */ +export const SPLIT_COIN_POLL_MS = 1_000; +/** How long the wallet has to sync the coin a finalized split made, in milliseconds. */ +export const SPLIT_COIN_WAIT_MS = 120_000; + +/** + * Waits until the session's wallet holds a free coin worth exactly `leg`, as + * it does once it has synced the split that made it. Throws SyncTimeoutError + * after `waitMs`. + */ +export async function awaitFreeCoin(session: WalletSession, leg: SwapLeg, signal?: AbortSignal, waitMs: number = SPLIT_COIN_WAIT_MS): Promise { + const deadline = Date.now() + waitMs; + while (!(await session.holdsFreeCoin(leg))) { + if (Date.now() >= deadline) { + throw new SyncTimeoutError(`The wallet has not synced the coin the split made within ${Math.round(waitMs / 1000)} s: the split is final, so run the same \`swap make\` again; it makes the offer from that coin.`); + } + await sleep(SPLIT_COIN_POLL_MS, signal); + } +} + /** An offer file read and checked against its own bytes, for this network. */ export interface ReadOffer { envelope: OfferEnvelope; diff --git a/scripts/check-layering.mjs b/scripts/check-layering.mjs index e7c65889..f266a25f 100644 --- a/scripts/check-layering.mjs +++ b/scripts/check-layering.mjs @@ -77,7 +77,7 @@ const HOMES = [ // The SDK engines: each is the only code that imports its SDK set. ['engine', /^engine\//], - ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|verbose|error-trim|command-flags|run-command|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|host|transport-failure|progress|network-target)\.ts$/], + ['core', /^lib\/(argv|errors|engine|exit-codes|json-output|constants|cli-config|network|network-id|resolve-network|payer|blockfrost|durable-file|keystore|verbose|error-trim|command-flags|run-command|phase-tracker|sdk-errors|amount|duration|sdk-warnings|notices|prompter|settings|state-root|command-definition|call-context|sleep|exec-program|agent-guidance|error-codes|wallet-cache|cache-indexer|reader-cache-files|connector-api|dust-wait|fee-limits|tx-serde|sign-data|approval|dust-balancing-plan|dust-registration-plan|shielded-policy|wallet-session|sdk-layout|swap-offer|offer-envelope|open-offers|coin-picker|host|transport-failure|progress|network-target)\.ts$/], ['core', /^ui\/(colors|format|spinner|terminal-prompter)\.ts$/], // What a host calls on its own process: the SDK rejection guard, the sync heap advice. ['core', /^process\//], diff --git a/src/__tests__/grant-deposit-command.test.ts b/src/__tests__/grant-deposit-command.test.ts index 0fe2c85a..3d64ec3a 100644 --- a/src/__tests__/grant-deposit-command.test.ts +++ b/src/__tests__/grant-deposit-command.test.ts @@ -84,6 +84,8 @@ function payerHolding(shielded: Record): Payer { makeOffer: unused, takeOffer: unused, cancelOffers: unused, + holdsFreeCoin: unused, + splitCoin: unused, sign: unused, submit: unused, readTransaction: unused, diff --git a/test-support/coin-picking-gc.ts b/test-support/coin-picking-gc.ts new file mode 100644 index 00000000..90006b11 --- /dev/null +++ b/test-support/coin-picking-gc.ts @@ -0,0 +1,32 @@ +// The engine's coin picking still works after garbage collection: a coin +// secret key held on its own is cleared by the ledger once the keys it came +// from are collected, which broke a spend rebuilt after a wait for Dust ("Coin +// secret key was cleared"). Run in a child process with --expose-gc, so the +// collection really happens between the picks. + +import { spawnSync } from 'node:child_process'; +import { describe, expect, it } from 'vitest'; + +/** Tests the coin picking of the engine whose shielded-wallet module is at `source` (an absolute path). */ +export function coinPickingSurvivesCollection(engine: string, source: string): void { + describe(`coin picking (${engine} engine) after garbage collection`, () => { + it("computes the same nullifier before and after the keys could be collected, and picks around an open offer's coin", () => { + const script = ` + const { shieldedCoinPicking, shieldedNullifier } = await import(${JSON.stringify(source)}); + const seed = new Uint8Array(32).fill(9); + const coin = (nonce, value) => ({ type: '00'.repeat(31) + '01', nonce, value, mt_index: 0n }); + const held = coin('11'.repeat(32), 10n), free = coin('22'.repeat(32), 10n); + const before = shieldedNullifier(seed, held); + const offer = { id: 'f8'.repeat(32), nullifiers: [before], terms: {}, madeAt: new Date(0), expiresAt: new Date(0) }; + const picking = shieldedCoinPicking(seed, () => [offer]); + const first = picking.pick([held, free], held.type, 10n).nonce; + for (let i = 0; i < 5; i++) { globalThis.gc(); await new Promise((r) => setTimeout(r, 20)); } + const second = picking.pick([held, free], held.type, 10n).nonce; + console.log(JSON.stringify({ same: shieldedNullifier(seed, held) === before, first, second })); + `; + const run = spawnSync(process.execPath, ['--expose-gc', '--conditions=midnight-cli-source', '--import', 'tsx', '--input-type=module', '-e', script], { encoding: 'utf8' }); + expect(run.stderr).toBe(''); + expect(JSON.parse(run.stdout.trim())).toEqual({ same: true, first: '22'.repeat(32), second: '22'.repeat(32) }); + }); + }); +} diff --git a/test-support/connector-stub.ts b/test-support/connector-stub.ts index 378e7328..0faa1abd 100644 --- a/test-support/connector-stub.ts +++ b/test-support/connector-stub.ts @@ -6,7 +6,7 @@ import { vi } from 'vitest'; import * as rx from 'rxjs'; import type { NetworkConfig, RpcHandlerContext } from '@kuiralabs/midnight-cli-core'; -import type { ApprovalOptions } from '@kuiralabs/midnight-cli-core/engine'; +import { type ApprovalOptions, type CoinPicking, createCoinPicking } from '@kuiralabs/midnight-cli-core/engine'; /** A connector test's host: nobody at a terminal to ask, and the connector's lines dropped. */ export const NO_TERMINAL = { prompter: null, notice: (_line: string): void => {} } as const; @@ -19,6 +19,7 @@ export interface StubConnector { handOffPendingTx(connectionId: string, txHex: string): boolean; takeOffer(connectionId: string, txHex: string): Promise; cancelOffers(connectionId: string, offers: readonly unknown[]): Promise; + holdsFreeCoin(token: string, amount: bigint): boolean; hasPendingTxs(): boolean; } @@ -56,6 +57,8 @@ export const HISTORY = [ export interface BundleOverrides { stateFn?: () => rx.Observable; + /** How the wallet picks coins; mn's own over no open offers when not given. */ + coinPicking?: CoinPicking<{ type: string; value: bigint; nonce: string }>; transferTransaction?: (...args: any[]) => Promise; signRecipe?: (...args: any[]) => Promise; finalizeRecipe?: (...args: any[]) => Promise; @@ -79,6 +82,8 @@ export function connectorStub(engine: StubEngine) { function mockState(overrides?: { unshieldedBalances?: Record; shieldedBalances?: Record; + /** The shielded coins the wallet holds unspent, each with its nullifier, as the SDK's state lists them. */ + shieldedCoins?: { coin: { type: string; value: bigint; nonce: string }; nullifier: string }[]; dustBalance?: bigint; protocolVersion?: { shielded: bigint; unshielded: bigint; dust: bigint }; isSynced?: boolean; @@ -95,6 +100,7 @@ export function connectorStub(engine: StubEngine) { }, shielded: { balances: overrides?.shieldedBalances ?? {}, + availableCoins: overrides?.shieldedCoins ?? [], address: WALLET_SHIELDED, }, dust: { @@ -134,6 +140,8 @@ export function connectorStub(engine: StubEngine) { getPublicKey: vi.fn().mockReturnValue({ tag: 'schnorr', value: '5678efghpubkey' }), }, ...(engine.secretKeys !== undefined ? { secretKeys: engine.secretKeys } : {}), + // mn's own coin picking, over no open offers; a coin's nullifier here is its nonce. + coinPicking: overrides?.coinPicking ?? createCoinPicking<{ type: string; value: bigint; nonce: string }>(() => [], (coin) => coin.nonce), }; } diff --git a/test-support/connector-suite.ts b/test-support/connector-suite.ts index fa99f60c..ae5c2c8b 100644 --- a/test-support/connector-suite.ts +++ b/test-support/connector-suite.ts @@ -19,7 +19,7 @@ import { startLocalIndexer, type LocalIndexer } from './local-indexer.ts'; import { ledgerTx, type Ledger } from './ledger-tx.ts'; import { SWAP_OFFER_HEX, OFFER_GIVE } from './fixtures/swap-offer.ts'; import { OfferCoinsInUseError, type OpenOffer, type RpcHandlerContext, classifyError, type NetworkName } from '@kuiralabs/midnight-cli-core'; -import { NotAnOfferError, signedMessageBytes, PROOF_TIMEOUT_MS, toEngineError, withDustShortfall, type FeeLimits, type ApprovalOptions } from '@kuiralabs/midnight-cli-core/engine'; +import { createCoinPicking, NotAnOfferError, signedMessageBytes, PROOF_TIMEOUT_MS, toEngineError, withDustShortfall, type FeeLimits, type ApprovalOptions } from '@kuiralabs/midnight-cli-core/engine'; import type { SignatureVerifyingKey } from '@midnightntwrk/ledger-v9'; import { CORE_CODES } from './core-codes.ts'; @@ -1669,29 +1669,59 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(connector.hasPendingTxs()).toBe(false); }); - it('cancels an offer by sending its whole balance of the token back to itself, which spends the offer\'s coins', async () => { - const transfer = vi.fn().mockResolvedValue({ type: 'UNPROVEN_TRANSACTION' }); + it("cancels an offer by sending the value of its coins back to itself, building with only those coins spendable", async () => { + const offer = openOffer(); + const offerCoin = { type: OFFER_GIVE, value: 12n, nonce: offerNullifier() }; + const otherOffersCoin = { type: OFFER_GIVE, value: 5n, nonce: 'other-offer-coin' }; + const freeCoin = { type: OFFER_GIVE, value: 83n, nonce: 'free-coin' }; + const coinPicking = createCoinPicking(() => [offer, { ...offer, id: 'e7'.repeat(32), nullifiers: ['other-offer-coin'] }], (coin) => coin.nonce); + const picked: (string | undefined)[] = []; + const transfer = vi.fn().mockImplementation(async () => { + // What the SDK's balancer would pick while the cancel is built: the offer's coin and none other. + const coins = [freeCoin, otherOffersCoin, offerCoin]; + picked.push(coinPicking.pick(coins, OFFER_GIVE, 12n)?.nonce); + picked.push(coinPicking.pick([freeCoin, otherOffersCoin], OFFER_GIVE, 1n)?.nonce); + return { type: 'UNPROVEN_TRANSACTION' }; + }); const bundle = createBundleStub({ - stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 100n } })), + stateFn: () => rx.of(mockState({ + shieldedBalances: { [OFFER_GIVE]: 100n }, + shieldedCoins: [freeCoin, otherOffersCoin, offerCoin].map((coin) => ({ coin, nullifier: coin.nonce })), + })), + coinPicking, transferTransaction: transfer, finalizeRecipe: () => Promise.resolve(offerTx()), }); - connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, openOffers: () => [openOffer()], notice: NO_TERMINAL.notice }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, openOffers: () => [offer], notice: NO_TERMINAL.notice }); - expect(await connector.cancelOffers('maker', [openOffer()])).toBe(SWAP_OFFER_HEX); + expect(await connector.cancelOffers('maker', [offer])).toBe(SWAP_OFFER_HEX); const [[outputs]] = transfer.mock.calls; expect(outputs).toHaveLength(1); expect(outputs[0].type).toBe('shielded'); expect(outputs[0].outputs).toHaveLength(1); - expect(outputs[0].outputs[0]).toMatchObject({ type: OFFER_GIVE, amount: 100n }); + expect(outputs[0].outputs[0]).toMatchObject({ type: OFFER_GIVE, amount: 12n }); expect(outputs[0].outputs[0].receiverAddress.coinPublicKeyString()).toBe(WALLET_SHIELDED.coinPublicKeyString()); + expect(picked).toEqual([offerNullifier(), undefined]); + // After the cancel is built, spends skip the offers' coins again. + expect(coinPicking.pick([freeCoin, otherOffersCoin, offerCoin], OFFER_GIVE, 12n)?.nonce).toBe('free-coin'); expect(connector.hasPendingTxs()).toBe(true); }); - it('refuses a cancel that would not spend the offer\'s coins, keeping nothing', async () => { + it("refuses a cancel when the wallet no longer holds the offer's coins, building nothing", async () => { + const transfer = vi.fn(); + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 100n } })), transferTransaction: transfer }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, notice: NO_TERMINAL.notice }); + + await expect(connector.cancelOffers('maker', [openOffer()])).rejects.toMatchObject({ code: 'InvalidRequest' }); + expect(transfer).not.toHaveBeenCalled(); + expect(connector.hasPendingTxs()).toBe(false); + }); + + it("refuses a cancel that would not spend the offer's coins, keeping nothing", async () => { const revertFn = vi.fn().mockResolvedValue(undefined); + const offerCoin = { type: OFFER_GIVE, value: 12n, nonce: offerNullifier() }; const bundle = createBundleStub({ - stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 100n } })), + stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 12n }, shieldedCoins: [{ coin: offerCoin, nullifier: offerCoin.nonce }] })), finalizeRecipe: () => Promise.resolve(sealedTx(5)), }); (bundle.facade as any).revert = revertFn; @@ -1701,6 +1731,21 @@ export function connectorSuite(engine: ConnectorEngine): void { expect(revertFn).toHaveBeenCalled(); expect(connector.hasPendingTxs()).toBe(false); }); + + it('says whether the wallet holds a free coin of exactly an amount: not one of its open offers\' coins', () => { + const offer = openOffer(); + const coins = [ + { coin: { type: OFFER_GIVE, value: 10n, nonce: 'a' }, nullifier: offerNullifier() }, + { coin: { type: OFFER_GIVE, value: 7n, nonce: 'b' }, nullifier: 'free-7' }, + ]; + const bundle = createBundleStub({ stateFn: () => rx.of(mockState({ shieldedBalances: { [OFFER_GIVE]: 17n }, shieldedCoins: coins })) }); + connector = engine.createDAppConnector({ bundle, networkConfig: TEST_NETWORK_CONFIG, approvalOptions: { ...NO_TERMINAL, approveAll: true }, openOffers: () => [offer], notice: NO_TERMINAL.notice }); + + expect(connector.holdsFreeCoin(OFFER_GIVE, 7n)).toBe(true); + expect(connector.holdsFreeCoin(OFFER_GIVE, 10n)).toBe(false); + expect(connector.holdsFreeCoin(OFFER_GIVE, 3n)).toBe(false); + expect(connector.holdsFreeCoin('00'.repeat(31) + '02', 7n)).toBe(false); + }); }); describe('pending tx tracking (hex-based)', () => { From b9dbe1f3b72abaa0181b07e8b3baa26b12a08957 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Thu, 5 Nov 2026 16:26:15 -0800 Subject: [PATCH 87/88] release 0.6.0-rc.14 Several open swap offers of one token (swap make splits a coin; spends leave open offers' coins alone), mounting mn's commands from core, a README per package, two typed codes, bun runs what npm installed (a bun install refused), account-chain 0.3.0-rc.3, and two fixes found by the consumer project. Every @kuiralabs workspace package moves to 0.1.0-rc.3; mn to 0.6.0-rc.14. --- CHANGELOG.md | 24 +++++++++ package-lock.json | 84 +++++++++++++++---------------- package.json | 20 ++++---- packages/chain/package.json | 4 +- packages/cli-core/package.json | 2 +- packages/connect/package.json | 8 +-- packages/contract/package.json | 8 +-- packages/dev/package.json | 12 ++--- packages/engine-beta/package.json | 6 +-- packages/engine-rc/package.json | 6 +-- packages/grant/package.json | 10 ++-- packages/wallet/package.json | 6 +-- 12 files changed, 107 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9774c2a..670da798 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,30 @@ All notable changes to midnight-wallet-cli will be documented in this file. ## [Unreleased] +## [0.6.0-rc.14] - 2026-11-05 + +### Added + +- **Several open swap offers of one token.** `mn swap make` needs a free coin worth exactly what the offer gives. When the wallet has none, it first sends that amount to itself, paying a fee in Dust. It then waits for the receipt and for the new coin, and makes the offer from it. The JSON gains `split` (`txHash` and the receipt). +- **Mounting mn's commands in a program.** Core exports `runCommand` (what mn's shell does around a handler), `captureCommand` (the MCP form) and `toolDescription` (a tool's description with its codes). Each package's `./commands` exports its registry entry: `coreCommands`, `chainCommands`, `walletCommands`, `swapCommands`, `contractCommands`, `connectCommands`, `devCommands` and `grantCommands`. +- **A README for each package:** how to install it, its entry points, what you call, its codes, and an example that mounts its commands. Every example is run as written in the test suite. +- **New codes:** `CONTRACT_NOT_COMPILED` ("No compiled contract found") and `NO_TEST_CONFIG` ("No dapp.test.json found"). Both used to report `UNKNOWN`. + +### Changed + +- **Spends leave open offers' coins alone.** Both engines pick shielded coins with mn's own picker. A spend never takes an open offer's coins, except to cancel that offer, and it prefers a coin of the exact amount. `OFFER_COINS_IN_USE` now comes only when nothing else could pay, before any proof is made. `mn swap cancel` spends only the cancelled offer's coins, so the wallet's other offers stay live. +- **Install with npm, run with Node or bun.** An engine installed by bun's installer is refused before any SDK loads, with `MIXED_SDK_LAYOUT` naming the npm command. bun's installer resolves the dependency ranges again and ignores the engine's shrinkwrap. A tree that npm installed, nested or hoisted, runs under both Node and bun. +- **Grant on account-chain 0.3.0-rc.3:** both engines pin `@kuiralabs/midnight-account-chain` 0.3.0-rc.3, which batches inbox appends (one transaction for up to four entries), and grant pins `@kuiralabs/midnight-account` 0.2.0-rc.1. An account deployed with rc.2 has the older contract, so deploy a new one. + +### Fixed + +- **A program's mounted command drew its spinners on the process's stderr** whatever output the program gave it. Progress now draws through the call's output. +- **Under bun, a program's contract deploy failed** because the script couldn't import `ws`. The engines now find the script's packages under bun as Node does. + +### Packages + +- Every `@kuiralabs` workspace package moves to `0.1.0-rc.3`. + ## [0.6.0-rc.13] - 2026-11-04 ### Added diff --git a/package-lock.json b/package-lock.json index 12d1b534..5cfa686c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.13", + "version": "0.6.0-rc.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.13", + "version": "0.6.0-rc.14", "license": "Apache-2.0", "workspaces": [ "packages/connector", @@ -21,15 +21,15 @@ "packages/grant" ], "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-connect": "0.1.0-rc.2", - "@kuiralabs/midnight-contract": "0.1.0-rc.2", - "@kuiralabs/midnight-dev": "0.1.0-rc.2", - "@kuiralabs/midnight-engine-beta": "0.1.0-rc.2", - "@kuiralabs/midnight-engine-rc": "0.1.0-rc.2", - "@kuiralabs/midnight-grant": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-connect": "0.1.0-rc.3", + "@kuiralabs/midnight-contract": "0.1.0-rc.3", + "@kuiralabs/midnight-dev": "0.1.0-rc.3", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.3", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.3", + "@kuiralabs/midnight-grant": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3", "@modelcontextprotocol/sdk": "^1.27.1" }, "bin": { @@ -5732,10 +5732,10 @@ }, "packages/chain": { "name": "@kuiralabs/midnight-chain", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "ws": "^8.19.0" }, "engines": { @@ -5744,7 +5744,7 @@ }, "packages/cli-core": { "name": "@kuiralabs/midnight-cli-core", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "engines": { "node": ">=22" @@ -5752,12 +5752,12 @@ }, "packages/connect": { "name": "@kuiralabs/midnight-connect", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3", "ws": "^8.19.0" }, "engines": { @@ -5789,12 +5789,12 @@ }, "packages/contract": { "name": "@kuiralabs/midnight-contract", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2" + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3" }, "engines": { "node": ">=22" @@ -5802,14 +5802,14 @@ }, "packages/dev": { "name": "@kuiralabs/midnight-dev", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-connect": "0.1.0-rc.2", - "@kuiralabs/midnight-contract": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2" + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-connect": "0.1.0-rc.3", + "@kuiralabs/midnight-contract": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3" }, "engines": { "node": ">=22" @@ -5817,12 +5817,12 @@ }, "packages/engine-beta": { "name": "@kuiralabs/midnight-engine-beta", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", @@ -6325,12 +6325,12 @@ }, "packages/engine-rc": { "name": "@kuiralabs/midnight-engine-rc", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", @@ -6356,14 +6356,14 @@ }, "packages/grant": { "name": "@kuiralabs/midnight-grant", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.1", - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-contract": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2" + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-contract": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3" }, "engines": { "node": ">=22" @@ -6371,11 +6371,11 @@ }, "packages/wallet": { "name": "@kuiralabs/midnight-wallet", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "license": "Apache-2.0", "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "@scure/bip39": "^2.0.1" }, "engines": { diff --git a/package.json b/package.json index 40e9c396..f05bef5a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "midnight-wallet-cli", - "version": "0.6.0-rc.13", + "version": "0.6.0-rc.14", "type": "module", "description": "Git-style CLI wallet for the Midnight blockchain", "license": "Apache-2.0", @@ -71,15 +71,15 @@ "package-readmes": "tsx --conditions=midnight-cli-source scripts/write-package-readmes.ts" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-connect": "0.1.0-rc.2", - "@kuiralabs/midnight-contract": "0.1.0-rc.2", - "@kuiralabs/midnight-dev": "0.1.0-rc.2", - "@kuiralabs/midnight-engine-beta": "0.1.0-rc.2", - "@kuiralabs/midnight-engine-rc": "0.1.0-rc.2", - "@kuiralabs/midnight-grant": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-connect": "0.1.0-rc.3", + "@kuiralabs/midnight-contract": "0.1.0-rc.3", + "@kuiralabs/midnight-dev": "0.1.0-rc.3", + "@kuiralabs/midnight-engine-beta": "0.1.0-rc.3", + "@kuiralabs/midnight-engine-rc": "0.1.0-rc.3", + "@kuiralabs/midnight-grant": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3", "@modelcontextprotocol/sdk": "^1.27.1" }, "devDependencies": { diff --git a/packages/chain/package.json b/packages/chain/package.json index 0c57888a..cbf6da63 100644 --- a/packages/chain/package.json +++ b/packages/chain/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-chain", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "Read-only network access for the Midnight CLI packages: node, indexer and proof-server readiness, chain id, tip, events and the ledger-version guard", "license": "Apache-2.0", @@ -35,7 +35,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "ws": "^8.19.0" } } diff --git a/packages/cli-core/package.json b/packages/cli-core/package.json index 33620c5d..083c9658 100644 --- a/packages/cli-core/package.json +++ b/packages/cli-core/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-cli-core", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "The base of the Midnight CLI packages: arguments, typed errors and exit codes, JSON output, config, the state root, network endpoints, terminal formatting, the command registry contract, the payer and the SDK engine interface", "license": "Apache-2.0", diff --git a/packages/connect/package.json b/packages/connect/package.json index 58213493..13236adb 100644 --- a/packages/connect/package.json +++ b/packages/connect/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-connect", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "mn serve for the Midnight CLI packages: the DApp connector API over a local WebSocket JSON-RPC server, the serve manager that starts or reuses one, and the payer that pays a command through it", "license": "Apache-2.0", @@ -35,9 +35,9 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3", "ws": "^8.19.0" } } diff --git a/packages/contract/package.json b/packages/contract/package.json index ef7ef31b..6927c046 100644 --- a/packages/contract/package.json +++ b/packages/contract/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-contract", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "Contracts for the Midnight CLI packages: deploying, calling and reading a Compact contract from its dApp folder through mn serve, the requests a deploy or call is built from, a compiled contract's circuits and witnesses, and the chain's block limits", "license": "Apache-2.0", @@ -35,8 +35,8 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2" + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3" } } diff --git a/packages/dev/package.json b/packages/dev/package.json index 3fe93155..7dc49221 100644 --- a/packages/dev/package.json +++ b/packages/dev/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-dev", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "Development for the Midnight CLI packages: mn dev (compile, deploy and test a dApp as its files change, on dev wallets), mn test (prepare, run and scaffold a dApp's test suites) and mn localnet (a local network in Docker)", "license": "Apache-2.0", @@ -35,10 +35,10 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-connect": "0.1.0-rc.2", - "@kuiralabs/midnight-contract": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2" + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-connect": "0.1.0-rc.3", + "@kuiralabs/midnight-contract": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3" } } diff --git a/packages/engine-beta/package.json b/packages/engine-beta/package.json index af469680..7e217ade 100644 --- a/packages/engine-beta/package.json +++ b/packages/engine-beta/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-engine-beta", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK 5.0 beta split packages, ledger 9 rc.3, midnight-js 5 beta): everything the CLI does with that SDK set, behind the engine interface", "license": "Apache-2.0", @@ -32,8 +32,8 @@ }, "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "@midnight-ntwrk/compact-js": "2.5.5-rc.7", "@midnight-ntwrk/compact-runtime": "0.18.0-rc.1", "@midnight-ntwrk/midnight-js-contracts": "5.0.0-beta.6", diff --git a/packages/engine-rc/package.json b/packages/engine-rc/package.json index ba663375..e7f7d382 100644 --- a/packages/engine-rc/package.json +++ b/packages/engine-rc/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-engine-rc", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, ledger 9 rc, midnight-js 5 rc): everything the CLI does with that SDK set, behind the engine interface", "license": "Apache-2.0", @@ -32,8 +32,8 @@ }, "dependencies": { "@kuiralabs/midnight-account-chain": "0.3.0-rc.3", - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "@midnight-ntwrk/compact-js": "3.0.0-rc.3", "@midnight-ntwrk/compact-runtime": "0.20.0", "@midnight-ntwrk/ledger-v8": "8.1.0", diff --git a/packages/grant/package.json b/packages/grant/package.json index 81c4ccd0..fc75ea10 100644 --- a/packages/grant/package.json +++ b/packages/grant/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-grant", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "Grants for the Midnight CLI packages: mn grant (the wallet owner's account and the grants that let an agent spend from it, its owner devices and backups) over @kuiralabs/midnight-account-chain, and the protector wallet protect seals the accounts' records with", "license": "Apache-2.0", @@ -37,9 +37,9 @@ }, "dependencies": { "@kuiralabs/midnight-account": "0.2.0-rc.1", - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", - "@kuiralabs/midnight-contract": "0.1.0-rc.2", - "@kuiralabs/midnight-wallet": "0.1.0-rc.2" + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", + "@kuiralabs/midnight-contract": "0.1.0-rc.3", + "@kuiralabs/midnight-wallet": "0.1.0-rc.3" } } diff --git a/packages/wallet/package.json b/packages/wallet/package.json index e424f750..4cbeb416 100644 --- a/packages/wallet/package.json +++ b/packages/wallet/package.json @@ -1,6 +1,6 @@ { "name": "@kuiralabs/midnight-wallet", - "version": "0.1.0-rc.2", + "version": "0.1.0-rc.3", "type": "module", "description": "Wallets for the Midnight CLI packages: mn's passphrase and sealed wallet files, seeds, balances, NIGHT transfers and airdrops, Dust registration, and swap offers", "license": "Apache-2.0", @@ -35,8 +35,8 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json" }, "dependencies": { - "@kuiralabs/midnight-chain": "0.1.0-rc.2", - "@kuiralabs/midnight-cli-core": "0.1.0-rc.2", + "@kuiralabs/midnight-chain": "0.1.0-rc.3", + "@kuiralabs/midnight-cli-core": "0.1.0-rc.3", "@scure/bip39": "^2.0.1" } } From 09cb4459a868f9cacabdca47248f5a82392f0d27 Mon Sep 17 00:00:00 2001 From: Norman Lopez Date: Thu, 5 Nov 2026 18:33:35 -0800 Subject: [PATCH 88/88] Release on npm 11: npm 12 drops npm-shrinkwrap.json rc.14's release job stopped before publishing: it installs the latest npm, and npm 12 (4 Nov) prints `npm pack --json` as an object keyed by name and `npm view --json` as an array, and neither reads nor packs npm-shrinkwrap.json, which each engine, grant and mn ship (Y32). - publish-manifest.mjs reads the tarball name from either pack shape (packedFilename); make-shrinkwrap.mjs reads either view shape (viewedField). Under npm 12 the old code threw in pack, and registryDist returned {}: a shrinkwrap with no tarballs or integrity. Regression tests for both; the pack tests fail under npm 12 without the fix. - The release job installs npm@11 (trusted publishing needs 11.5.1+). - MIXED_SDK_LAYOUT names npm 12 with bun's installer, and says to install with npm 11 or older (npx -y npm@11 install ... under npm 12); the READMEs and the changelog say so. Checked: under npm 12 an install of rc.14 lays out 4 ledger-v9 copies and both engines refuse; through npx npm@11 it lays out 2 and mn runs on both engines. --- .github/workflows/release-sidecar.yml | 5 ++-- CHANGELOG.md | 2 +- README.md | 2 +- packages/chain/README.md | 2 +- packages/cli-core/README.md | 2 +- .../cli-core/src/__tests__/sdk-layout.test.ts | 2 +- packages/cli-core/src/lib/sdk-layout.ts | 4 ++-- packages/connect/README.md | 2 +- packages/contract/README.md | 2 +- packages/dev/README.md | 2 +- packages/engine-beta/README.md | 2 +- packages/engine-rc/README.md | 2 +- packages/grant/README.md | 2 +- packages/wallet/README.md | 2 +- scripts/make-shrinkwrap.d.mts | 5 ++++ scripts/make-shrinkwrap.mjs | 14 ++++++++++- scripts/publish-manifest.d.mts | 2 ++ scripts/publish-manifest.mjs | 15 ++++++++++-- src/__tests__/make-shrinkwrap.test.ts | 24 +++++++++++++++++++ src/__tests__/publish-manifest.test.ts | 19 ++++++++++++++- 20 files changed, 92 insertions(+), 20 deletions(-) create mode 100644 scripts/make-shrinkwrap.d.mts create mode 100644 src/__tests__/make-shrinkwrap.test.ts diff --git a/.github/workflows/release-sidecar.yml b/.github/workflows/release-sidecar.yml index a9b9535b..4a4da581 100644 --- a/.github/workflows/release-sidecar.yml +++ b/.github/workflows/release-sidecar.yml @@ -111,9 +111,10 @@ jobs: - uses: oven-sh/setup-bun@v2 with: bun-version-file: .bun-version - # OIDC trusted publishing needs npm >= 11.5.1; Node 22 ships npm 10.x. + # OIDC trusted publishing needs npm >= 11.5.1; Node 22 ships npm 10.x. Held at npm 11: npm 12 neither packs + # nor reads npm-shrinkwrap.json, which each engine and grant ship (and mn's own). - name: Upgrade npm for OIDC trusted publishing - run: npm install -g npm@latest + run: npm install -g npm@11 - run: npm ci - name: Download all platform binaries if: env.PRERELEASE != 'true' diff --git a/CHANGELOG.md b/CHANGELOG.md index 670da798..b915a6cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ All notable changes to midnight-wallet-cli will be documented in this file. ### Changed - **Spends leave open offers' coins alone.** Both engines pick shielded coins with mn's own picker. A spend never takes an open offer's coins, except to cancel that offer, and it prefers a coin of the exact amount. `OFFER_COINS_IN_USE` now comes only when nothing else could pay, before any proof is made. `mn swap cancel` spends only the cancelled offer's coins, so the wallet's other offers stay live. -- **Install with npm, run with Node or bun.** An engine installed by bun's installer is refused before any SDK loads, with `MIXED_SDK_LAYOUT` naming the npm command. bun's installer resolves the dependency ranges again and ignores the engine's shrinkwrap. A tree that npm installed, nested or hoisted, runs under both Node and bun. +- **Install with npm 11 or older, run with Node or bun.** Each engine ships an `npm-shrinkwrap.json` with the SDK set it was tested on. npm 12 no longer reads one, and bun's installer ignores it, so both resolve the dependency ranges again. An engine installed that way is refused before any SDK loads, with `MIXED_SDK_LAYOUT` and the command to use instead. With npm 12, install with `npx -y npm@11 install -g midnight-wallet-cli@next`. A tree that npm 11 or older installed, nested or hoisted, runs under both Node and bun. - **Grant on account-chain 0.3.0-rc.3:** both engines pin `@kuiralabs/midnight-account-chain` 0.3.0-rc.3, which batches inbox appends (one transaction for up to four entries), and grant pins `@kuiralabs/midnight-account` 0.2.0-rc.1. An account deployed with rc.2 has the older contract, so deploy a new one. ### Fixed diff --git a/README.md b/README.md index bf7b227a..5df39758 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ npm install -g midnight-wallet-cli@next # this ledger-9 prerelease This installs two commands: `midnight` (or `mn` for short) and `midnight-wallet-mcp`. -Install the prerelease with npm (or run it with `npx`). Each engine ships an `npm-shrinkwrap.json` that pins the SDK set it was tested with; bun's installer ignores it and resolves the packages again, so an engine bun installed is refused before any SDK loads, saying so (`MIXED_SDK_LAYOUT`). bun can run what npm installed. +Install the prerelease with npm 11 or older (or run it with `npx`; with npm 12, `npx -y npm@11 install -g midnight-wallet-cli@next`). Each engine ships an `npm-shrinkwrap.json` that pins the SDK set it was tested with; npm 12 and bun's installer ignore it and resolve the packages again, so an engine either installed is refused before any SDK loads, saying so (`MIXED_SDK_LAYOUT`). bun can run what npm installed. ## Commands diff --git a/packages/chain/README.md b/packages/chain/README.md index 2797feeb..c554cbd8 100644 --- a/packages/chain/README.md +++ b/packages/chain/README.md @@ -8,7 +8,7 @@ Read-only network access for the Midnight CLI packages: whether a node, an index npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-chain@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). ## Entry points diff --git a/packages/cli-core/README.md b/packages/cli-core/README.md index ae0227e0..d145e46e 100644 --- a/packages/cli-core/README.md +++ b/packages/cli-core/README.md @@ -8,7 +8,7 @@ The base of the Midnight CLI packages: the host a program passes to them, typed npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. bun's installer ignores it and resolves the packages again, so an engine bun installed refuses to load, before any SDK module does, with `MIXED_SDK_LAYOUT` and the npm command; bun runs what npm installed. A program that runs the SDK installs an engine too: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. bun's installer ignores it and resolves the packages again, so an engine bun installed refuses to load, before any SDK module does, with `MIXED_SDK_LAYOUT` and the npm command; bun runs what npm installed. A program that runs the SDK installs an engine too: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. ## Entry points diff --git a/packages/cli-core/src/__tests__/sdk-layout.test.ts b/packages/cli-core/src/__tests__/sdk-layout.test.ts index 7084b3f2..7a259219 100644 --- a/packages/cli-core/src/__tests__/sdk-layout.test.ts +++ b/packages/cli-core/src/__tests__/sdk-layout.test.ts @@ -105,7 +105,7 @@ describe('an engine installed as shipped', () => { expect(refusal).toBeInstanceOf(NotInstalledAsShippedError); expect((refusal as NotInstalledAsShippedError).code).toBe('MIXED_SDK_LAYOUT'); expect((refusal as Error).message).toContain('the test engine isn\'t installed as it was tested: 1 of its dependencies'); - expect((refusal as Error).message).toContain('Install with npm'); + expect((refusal as Error).message).toContain('Install with npm 11 or older'); }); // As bun's installer leaves graphql-tag: sharing the top-level graphql instead of the one nested for it. diff --git a/packages/cli-core/src/lib/sdk-layout.ts b/packages/cli-core/src/lib/sdk-layout.ts index 677b79bf..39e03971 100644 --- a/packages/cli-core/src/lib/sdk-layout.ts +++ b/packages/cli-core/src/lib/sdk-layout.ts @@ -79,8 +79,8 @@ export class NotInstalledAsShippedError extends Error { super( `${engine} isn't installed as it was tested: ${drift.length} of its dependencies resolve to other versions than the npm-shrinkwrap.json it ships ` + `(${first.name} ${first.found ?? 'missing'} where ${first.shipped} was tested, for ${first.from}), so it could fail in ways nobody has seen. ` + - 'This happens with an installer that ignores the shrinkwrap, such as bun\'s. ' + - 'Install with npm (npm install -g midnight-wallet-cli for mn, or npm install for a program); bun can run what npm installed.', + 'This happens with an installer that ignores the shrinkwrap, such as bun\'s or npm 12 and later. ' + + 'Install with npm 11 or older (npm install -g midnight-wallet-cli for mn, or npm install for a program; with npm 12, npx -y npm@11 install …); bun can run what npm installed.', ); this.name = 'NotInstalledAsShippedError'; this.drift = drift; diff --git a/packages/connect/README.md b/packages/connect/README.md index 7852dfd2..bc5f22e8 100644 --- a/packages/connect/README.md +++ b/packages/connect/README.md @@ -8,7 +8,7 @@ npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-wallet@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). ## Entry points diff --git a/packages/contract/README.md b/packages/contract/README.md index 9ce875a9..fd4ff52b 100644 --- a/packages/contract/README.md +++ b/packages/contract/README.md @@ -8,7 +8,7 @@ Contracts for the Midnight CLI packages: deploying, calling and reading a Compac npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-contract@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). ## Entry points diff --git a/packages/dev/README.md b/packages/dev/README.md index 60c8526c..1a0b7eca 100644 --- a/packages/dev/README.md +++ b/packages/dev/README.md @@ -8,7 +8,7 @@ Development for the Midnight CLI packages: `mn dev` (compile, deploy and test a npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-dev@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). ## Entry points diff --git a/packages/engine-beta/README.md b/packages/engine-beta/README.md index 558e7067..4af097cc 100644 --- a/packages/engine-beta/README.md +++ b/packages/engine-beta/README.md @@ -8,7 +8,7 @@ The Midnight CLI's engine for the SDK's beta set that stagenet runs (wallet SDK npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-beta@next ``` -Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). An install that isn't that tree (bun's installer ignores the shrinkwrap and resolves the packages again) is refused before any SDK module loads, with `MIXED_SDK_LAYOUT` and the npm command; bun can run what npm installed. A program that also uses the other networks (`@kuiralabs/midnight-engine-rc`) installs both; a process loads one of them. +Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). An install that isn't that tree (bun's installer ignores the shrinkwrap and resolves the packages again) is refused before any SDK module loads, with `MIXED_SDK_LAYOUT` and the npm command; bun can run what npm installed. A program that also uses the other networks (`@kuiralabs/midnight-engine-rc`) installs both; a process loads one of them. ## Entry points diff --git a/packages/engine-rc/README.md b/packages/engine-rc/README.md index 5c9210d5..a3adc892 100644 --- a/packages/engine-rc/README.md +++ b/packages/engine-rc/README.md @@ -8,7 +8,7 @@ The Midnight CLI's engine for the SDK's release candidates (wallet SDK 2.0 rc, l npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-engine-rc@next ``` -Install with npm: this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). An install that isn't that tree (bun's installer ignores the shrinkwrap and resolves the packages again) is refused before any SDK module loads, with `MIXED_SDK_LAYOUT` and the npm command; bun can run what npm installed. A program that also uses stagenet (`@kuiralabs/midnight-engine-beta`) installs both; a process loads one of them. +Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): this package ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it, so it gets exactly the SDK it was tested with (one copy of each ledger). An install that isn't that tree (bun's installer ignores the shrinkwrap and resolves the packages again) is refused before any SDK module loads, with `MIXED_SDK_LAYOUT` and the npm command; bun can run what npm installed. A program that also uses stagenet (`@kuiralabs/midnight-engine-beta`) installs both; a process loads one of them. ## Entry points diff --git a/packages/grant/README.md b/packages/grant/README.md index 46495dfd..b986f6ef 100644 --- a/packages/grant/README.md +++ b/packages/grant/README.md @@ -8,7 +8,7 @@ Grants for the Midnight CLI packages: `mn grant`, the wallet owner's side of an npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-wallet@next @kuiralabs/midnight-grant@next @kuiralabs/midnight-connect@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). ## Entry points diff --git a/packages/wallet/README.md b/packages/wallet/README.md index 98e9decc..26e737ae 100644 --- a/packages/wallet/README.md +++ b/packages/wallet/README.md @@ -8,7 +8,7 @@ Wallets for the Midnight CLI packages: mn's passphrase and sealed wallet files, npm install @kuiralabs/midnight-cli-core@next @kuiralabs/midnight-wallet@next @kuiralabs/midnight-engine-rc@next ``` -Every package is a release candidate on the `next` tag. Install with npm: each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). +Every package is a release candidate on the `next` tag. Install with npm 11 or older (npm 12 no longer reads a package's shrinkwrap): each engine ships an `npm-shrinkwrap.json` that pins its SDK set, and npm 11 honours it. A program that runs the SDK installs an engine: `@kuiralabs/midnight-engine-rc` for preprod, preview and a local network, `@kuiralabs/midnight-engine-beta` for stagenet. How a program sets up its process for the SDK (the rejection guard, the heap, Ctrl-C, ending) is in [core's README](https://github.com/kuiralabs/midnight-cli/blob/main/packages/cli-core/README.md#your-process-what-mns-shell-does-that-you-must-do). ## Entry points diff --git a/scripts/make-shrinkwrap.d.mts b/scripts/make-shrinkwrap.d.mts new file mode 100644 index 00000000..d4593417 --- /dev/null +++ b/scripts/make-shrinkwrap.d.mts @@ -0,0 +1,5 @@ +// Types for what scripts/make-shrinkwrap.mjs exports that the tests import. +/** A published package's tarball and integrity, as `registry` serves them. */ +export function registryDist(registry: string): (name: string, version: string) => { resolved: string; integrity: string }; +/** The one field `npm view @ --json` printed (npm 11's value or npm 12's array of one). */ +export function viewedField(output: string): unknown; diff --git a/scripts/make-shrinkwrap.mjs b/scripts/make-shrinkwrap.mjs index 5966ffe7..dd4d4ac4 100644 --- a/scripts/make-shrinkwrap.mjs +++ b/scripts/make-shrinkwrap.mjs @@ -39,11 +39,23 @@ const repo = fileURLToPath(new URL('..', import.meta.url)); /** A published package's tarball and integrity, as `registry` serves them. */ export function registryDist(registry) { return (name, version) => { - const dist = JSON.parse(execFileSync('npm', ['view', `${name}@${version}`, 'dist', '--json', '--registry', registry], { encoding: 'utf-8' })); + const dist = viewedField(execFileSync('npm', ['view', `${name}@${version}`, 'dist', '--json', '--registry', registry], { encoding: 'utf-8' })); return { resolved: dist.tarball, integrity: dist.integrity }; }; } +/** + * The one field `npm view @ --json` printed: the value + * itself up to npm 11, an array of one value from npm 12 (the release job + * installs the latest npm). + */ +export function viewedField(output) { + const parsed = JSON.parse(output); + if (!Array.isArray(parsed)) return parsed; + if (parsed.length !== 1) throw new Error(`npm view --json printed ${parsed.length} values, not one: ${output.slice(0, 200)}`); + return parsed[0]; +} + /** The lockfile path a package named `name` resolves to from the package at `from`, or undefined. */ function resolveIn(packages, from, name) { for (let dir = from; ; dir = dir === '' ? null : parentOf(dir)) { diff --git a/scripts/publish-manifest.d.mts b/scripts/publish-manifest.d.mts index 6af9ce4f..aaacdb63 100644 --- a/scripts/publish-manifest.d.mts +++ b/scripts/publish-manifest.d.mts @@ -5,3 +5,5 @@ export const SOURCE_CONDITION: string; export function publishedManifest(manifest: T): T; /** Packs the package in `dir` into `destination` with its published manifest, its own package.json put back; returns the tarball's path. */ export function packPublished(dir: string, destination: string): string; +/** The tarball's file name in what `npm pack --json` printed for one package (npm 11's array or npm 12's object). */ +export function packedFilename(output: string): string; diff --git a/scripts/publish-manifest.mjs b/scripts/publish-manifest.mjs index 120e8cc4..d4d1ee9d 100644 --- a/scripts/publish-manifest.mjs +++ b/scripts/publish-manifest.mjs @@ -29,6 +29,18 @@ export function publishedManifest(manifest) { return manifest.exports === undefined ? manifest : { ...manifest, exports: withoutSourceCondition(manifest.exports) }; } +/** + * The tarball's file name in what `npm pack --json` printed for one package: + * an array of one entry up to npm 11, an object keyed by the package's name + * from npm 12 (the release job installs the latest npm). + */ +export function packedFilename(output) { + const parsed = JSON.parse(output); + const entries = Array.isArray(parsed) ? parsed : Object.values(parsed ?? {}); + if (entries.length !== 1 || typeof entries[0]?.filename !== 'string') throw new Error(`npm pack --json printed no single tarball: ${output.slice(0, 200)}`); + return entries[0].filename; +} + /** * Packs the package in `dir` into `destination` with its published manifest, * putting its own package.json back afterwards, byte for byte, whatever @@ -40,8 +52,7 @@ export function packPublished(dir, destination) { const original = readFileSync(path, 'utf-8'); writeFileSync(path, JSON.stringify(publishedManifest(JSON.parse(original)), null, 2) + '\n'); try { - const [packed] = JSON.parse(execFileSync('npm', ['pack', '--json', '--pack-destination', destination], { cwd: dir, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] })); - return join(destination, packed.filename); + return join(destination, packedFilename(execFileSync('npm', ['pack', '--json', '--pack-destination', destination], { cwd: dir, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }))); } finally { writeFileSync(path, original); } diff --git a/src/__tests__/make-shrinkwrap.test.ts b/src/__tests__/make-shrinkwrap.test.ts new file mode 100644 index 00000000..fbc6750d --- /dev/null +++ b/src/__tests__/make-shrinkwrap.test.ts @@ -0,0 +1,24 @@ +// The shrinkwrap's tarballs and integrity come from `npm view ... dist --json`, +// whose output changed shape in npm 12 (the release job installs the latest npm). + +import { describe, expect, it } from 'vitest'; +import { viewedField } from '../../scripts/make-shrinkwrap.mjs'; + +describe("the field in npm view's output", () => { + // As npm prints `npm view @kuiralabs/midnight-cli-core@0.1.0-rc.2 dist --json`. + const dist = { + shasum: '542a05420f0c64de2ff4e164e8d60aa00dd0411d', + tarball: 'https://registry.npmjs.org/@kuiralabs/midnight-cli-core/-/midnight-cli-core-0.1.0-rc.2.tgz', + integrity: 'sha512-example', + }; + + it('is read from npm 11 (the value) and npm 12 (an array of one)', () => { + expect(viewedField(JSON.stringify(dist))).toStrictEqual(dist); + expect(viewedField(JSON.stringify([dist]))).toStrictEqual(dist); + }); + + it('is refused when npm 12 prints other than one value', () => { + expect(() => viewedField('[]')).toThrow('0 values, not one'); + expect(() => viewedField(JSON.stringify([dist, dist]))).toThrow('2 values, not one'); + }); +}); diff --git a/src/__tests__/publish-manifest.test.ts b/src/__tests__/publish-manifest.test.ts index 713ab109..a23922ed 100644 --- a/src/__tests__/publish-manifest.test.ts +++ b/src/__tests__/publish-manifest.test.ts @@ -10,7 +10,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; import { PUBLIC_PACKAGES } from '../../scripts/api-report.mjs'; -import { SOURCE_CONDITION, packPublished, publishedManifest } from '../../scripts/publish-manifest.mjs'; +import { SOURCE_CONDITION, packPublished, packedFilename, publishedManifest } from '../../scripts/publish-manifest.mjs'; const PACKAGES = join(import.meta.dirname, '..', '..', 'packages'); const manifestOf = (dir: string) => readFileSync(join(PACKAGES, dir, 'package.json'), 'utf8'); @@ -46,3 +46,20 @@ describe('the published manifest', () => { } }, 60_000); }); + +describe("the tarball's name in npm pack's output", () => { + // As npm prints `npm pack --json` for one package: npm 11 an array of one + // entry, npm 12 an object keyed by the package's name (the release job + // installs the latest npm; npm 12 broke rc.14's first release run). + const entry = { id: '@kuiralabs/midnight-cli-core@0.1.0-rc.3', name: '@kuiralabs/midnight-cli-core', version: '0.1.0-rc.3', filename: 'kuiralabs-midnight-cli-core-0.1.0-rc.3.tgz', files: [] }; + + it('is read from npm 11 and from npm 12', () => { + expect(packedFilename(JSON.stringify([entry]))).toBe(entry.filename); + expect(packedFilename(JSON.stringify({ [entry.name]: entry }))).toBe(entry.filename); + }); + + it('is refused when the output names no single tarball', () => { + expect(() => packedFilename('[]')).toThrow('no single tarball'); + expect(() => packedFilename(JSON.stringify({ a: entry, b: entry }))).toThrow('no single tarball'); + }); +});